﻿/// <reference path="GMAPJSHelper_Release.js"/>
var geocoder = null;
var map;
var adress;
var directions;
var SWon = 0;
var svOverlay;
var listener;
var b;

function testcoord(data) {
if (data.code == 200) 
    document.getElementById("divCoord").innerHTML ="Finns";
    else
    document.getElementById("divCoord").innerHTML ="Inte;";
}

var qsParm = new Array();
function qs() {
    var query = window.location.search.substring(1);
    var parms = query.split('&');
    for (var i = 0; i < parms.length; i++) {
        var pos = parms[i].indexOf('=');
        if (pos > 0) {
            var key = parms[i].substring(0, pos);
            var val = parms[i].substring(pos + 1);
            qsParm[key] = val;
        }
    }
} 

function load() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map_canv"));
        map.enableScrollWheelZoom();
        map.addControl(new GMapTypeControl());
        map.addControl(new GLargeMapControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10, 30)));
        b = new SVButtons();
        map.addControl(b);
        b.VisaVisible(true);

        qs();
        if (qsParm["adress"] != null) {
            if (qsParm["typ"] == 'karta') {
                var gGeocoder = new GClientGeocoder();
                gGeocoder.getLatLng(unescape(qsParm["adress"]), function(position) {
                    if (position == null) {
                        alert('Kan inte hitta adressen...');
                    }
                    else {
                        map.setCenter(position, 16);
                        map.addOverlay(new GMarker(position));
                    }
                });
            }
            else
                mapLatitudeAndLongitude(unescape(qsParm["adress"]));
        }
        else {
            var point = new GLatLng("63.03503931552975", "16.171875");
            map.setCenter(point, 5);
            map.enableContinuousZoom();
        }
    }
}

function CloseStreet() {
    document.getElementById("map_canv").style.display = "block";
    document.getElementById("street").style.display = "none";
    SideBarVisible(true);
}

function asdf() { 

    Stang();
    map.clearOverlays();
    document.getElementById("felMeddelande").style.display = 'none';
    var txt = document.getElementById("adress");
    var tmp = txt.value
    geocoder = new GClientGeocoder();
    if (document.getElementById('rbSverige').checked == true)
        tmp += ' Sverige';
    geocoder.getLocations(tmp, addToMap2);
}

//    function addToMap(response)
//   {
//     if(response.Placemark !=null)
//      {
//          var place = response.Placemark[0];
//          var point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
//          bla(point);
//      }
//      else Error('Tyvärr hittades ingen adress enligt ovan, försök med något annat.',0);
//  }
function addToMap2(response) {
    if (response.Placemark != null) {
        var place = response.Placemark[0];
        var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
        map.setCenter(point, 12);
        var marker = new GMarker(point);
        var tx = document.getElementById("adress");
        map.addOverlay(marker);
        marker.openInfoWindowHtml(tx.value);
    }
    else Error('Tyvärr hittades ingen adress enligt ovan, försök med något annat.', 0);
}

function handleErrors() {
    if (directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
        Error("Tyvärr hittades ingen adress enligt ovan, försök med något annat.", directions.getStatus().code);
    else if (directions.getStatus().code == G_GEO_SERVER_ERROR)
        Error("Ett okänt fel inträffade, adressen kunde inte hittas.", directions.getStatus().code);
    else if (directions.getStatus().code == G_GEO_MISSING_QUERY)
        Error("Ett fält är tomt, fyll i fältet ovan och testa igen.", directions.getStatus().code);
    else if (directions.getStatus().code == G_GEO_BAD_KEY)
        Error("Fel på nyckeln. ", directions.getStatus().code);
    else if (directions.getStatus().code == G_GEO_BAD_REQUEST)
        Error("Tolkningsfel.", directions.getStatus().code);
    else Error("Ett okänt fel inträffade, adressen kunde inte hittas.", 0);
}

function onGDirectionsLoad() {
}

function dirr(adress, adress2) {
    if (adress != '' && adress2 != '') {
        if (document.getElementById('rbSverige').checked == true) {
            adress += ' Sverige';
            adress2 += ' Sverige';
        }
        var fel = document.getElementById("felMeddelande");
        fel.style.display = 'none';
        if (GBrowserIsCompatible()) {
            map.clearOverlays();
            document.getElementById("divDir").innerHTML = "";
            directions = new GDirections(map, document.getElementById("divDir"));
            GEvent.addListener(directions, "load", onGDirectionsLoad);
            GEvent.addListener(directions, "addoverlay", xxxx);
            GEvent.addListener(directions, "error", handleErrors);
            setDirections(adress, adress2, "sv_SE");
        }
    }
    else Error('Ange en start och en slutadress!', 0);
}

function setDirections(fromAddress, toAddress, locale) {
    directions.load("from: " + fromAddress + " to: " + toAddress, { "locale": locale });

}
function xxxx() {
    document.getElementById("divDir").style.display = "block";
    document.getElementById("aStang").style.display = "inline";
    map.zoomOut();
}
function handleErrors() {
    if (directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
        Error("Tyvärr hittades ingen adress enligt ovan, försök med något annat.", directions.getStatus().code);
    else if (directions.getStatus().code == G_GEO_SERVER_ERROR)
        Error("Ett okänt fel inträffade, adressen kunde inte hittas.", directions.getStatus().code);
    else if (directions.getStatus().code == G_GEO_MISSING_QUERY)
        Error("Ett fält är tomt, fyll i fältet ovan och testa igen.", directions.getStatus().code);
    else if (directions.getStatus().code == G_GEO_BAD_KEY)
        Error("Fel på nyckeln.", directions.getStatus().code);
    else if (directions.getStatus().code == G_GEO_BAD_REQUEST)
        Error("Tolkningsfel.", directions.getStatus().code);
    else Error("Ett okänt fel inträffade, adressen kunde inte hittas.", 0);
}
function Stang() {
    document.getElementById("divDir").style.display = "none";
    document.getElementById("aStang").style.display = "none";
}

function Error(x, z) {
    Stang();
    var y = document.getElementById("felMeddelande");
    y.style.display = 'block';
    y.innerHTML = x;

}

function SideBarVisible(bool) {
    if (bool) {
        document.getElementById("bar").style.display = "block";
        document.getElementById("barbutton").style.display = "block";
        document.getElementById("barbutton").style.left = "251px";
        document.getElementById("Image1").style.display = "";
        document.getElementById("Image1").src = "/onetoone/img/map-putin-off.gif";
    }
    else {
        document.getElementById("bar").style.display = "none";
        document.getElementById("barbutton").style.display = "none";
        document.getElementById("Image1").style.display = "none";
    }
}

function Toggle() {
    var bar = document.getElementById("bar");
    var barbutton = document.getElementById("barbutton");
    var image = document.getElementById("Image1");
    if (bar.style.display != "none") {
        image.src = "/onetoone/img/map-putut-off.gif";
        bar.style.display = "none";
        barbutton.style.left = "0px";
    }
    else {
        image.src = "/onetoone/img/map-putin-off.gif";
        bar.style.display = "block";
        barbutton.style.left = "251px";
        barbutton.style.display = "";
    }
}

function VisaForetag(result) {
    var x = result;

    if (x != null) {
        for (var i = 0; i < x.length; i++) {
        
            var z = new Array();
            z = x[i].split(":");
           
            var icons = new Array();
            icons["red"] = new GIcon();
            icons["red"].image = "/onetoone/img/bluedot.png";
            icons["red"].iconSize = new GSize(6, 6);
           
            icons["red"].iconAnchor = new GPoint(6, 6);
            icons["red"].infoWindowAnchor = new GPoint(9, 2);
            icons["red"].imageMap = [0, 0, 6, 0, 6, 6, 0, 6]; 

            var icon = new GIcon(icons["red"]);
            var point = new GLatLng(z[0], z[1]);
            var marker = new GMarker(point, {icon:icon,draggable:true});
            marker.enableDragging();
            var html = '<a href="http://' + z[3] + '" target="_blank">' + z[2] + '</a><br/><br/>' + z[4] + '<br/>' + z[5] + ' ' + z[6] + '<br/>' + z[7] + '-' + z[8];
            if (z[10] != null && z!='' && z!=' ')
                html ='<table><tr><td>'+html+'</td><td><img src="http://www.121.nu/kunder/' + z[9] + '/' + z[10] + '></td></tr></table>';
            marker.bindInfoWindowHtml(html);
            map.addOverlay(marker);
           
        } 
    }
}

function OnError(error) {
    alert(error);
}
function test() {
    var x = map.getBounds();
    if (map.getZoom() >= 10) {
        map.clearOverlays();
        WS.GetCompaniesOnMap(x.getSouthWest() + ':' + x.getNorthEast(), VisaForetag, OnError);
    }
    else
        alert('Du måste zooma in lite');
}
function All() {
    WS.GetCompaniesOnMap('(55.37172000000,11.17198000000):(67.93830400000,24.13739200000)', VisaForetag, OnError);
}


function bla(data) {
    if (data.code != 200) {
        alert('Det finns ingen "street view" på den här koordinaten. Du måste klicka på en blåmarkerad väg. ');// + panoData.code);
        return;
    }
    else {
        var street = new GStreetviewPanorama(document.getElementById("street"));
        street.setLocationAndPOV(data.location.latlng);

        document.getElementById("map_canv").style.display = "none";
        SideBarVisible(false);
        document.getElementById("street").style.display = "";
    }
}
  
function DisplaySV(x) {
    if (SWon == 0 && x == 1) {
        SWon = 1;
        b.VisaVisible(false);
        svOverlay = new GStreetviewOverlay();
        map.addOverlay(svOverlay);
        document.getElementById("map_canv").style.cursor = 'pointer';
        
        listener = GEvent.addListener(map, "click", function(overlay, latlng) {
            client = new GStreetviewClient();
            client.getNearestPanorama(latlng, bla);
        });
    }
    else if (SWon == 1 && x == 0) {
    SWon = 0;
    b.VisaVisible(true);
        map.removeOverlay(svOverlay);
        GEvent.removeListener(listener);
    }
}

function SVButtons() {
}
    SVButtons.prototype = new GControl();
    
    
    SVButtons.prototype.initialize = function(m)
    {
        this.container = document.createElement("div");
        this.svVisa = document.createElement("div");
        this.setButtonStyle_(this.svVisa);
        this.container.appendChild(this.svVisa);
        this.svVisa.appendChild(document.createTextNode("Visa Street View"));
        GEvent.addDomListener(this.svVisa, "click", function() {
            DisplaySV(1);
        });

        this.svDolj = document.createElement("div");
        this.setButtonStyle_(this.svDolj);
        this.container.appendChild(this.svDolj);
        this.svDolj.appendChild(document.createTextNode("Dölj Street View"));
        GEvent.addDomListener(this.svDolj, "click", function() {
            DisplaySV(0);
        });

        m.getContainer().appendChild(this.container);
        return this.container;
    }

SVButtons.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(400, 7));
}

SVButtons.prototype.setButtonStyle_ = function(button) {
    button.style.textDecoration = "underline";
    button.style.color = "#0000cc";
    button.style.backgroundColor = "white";
    button.style.font = "small Arial";
    button.style.border = "1px solid black";
    button.style.padding = "2px";
    button.style.marginBottom = "3px";
    button.style.textAlign = "center";
    button.style.width = "10em";
    button.style.cursor = "pointer";
}

SVButtons.prototype.VisaVisible = function(bool) {
this.svVisa.style.display = bool ? '' : 'none';
this.svDolj.style.display = bool ? 'none' : '';
}


function mapLatitudeAndLongitude(address) {
    var gGeocoder = new GClientGeocoder();
    gGeocoder.getLatLng(address,function(position) {
				    if (position == null) {
				        alert('Kan inte hitta adressen...');
				    } else {
				        map.setCenter(position, 16);
				        map.addOverlay(new GMarker(position));
				        var gStreetView = new GStreetviewClient();
				        gStreetView.getNearestPanoramaLatLng(
							position,
							function(camera) {
							    if (camera == null) {
							        alert('Kan inte hitta streetviewkamera...');
							    } else {
							        var bearing = LatLon.bearing(camera.lat(), camera.lng(), position.lat(), position.lng());
							        var pov = { yaw: bearing };
							        document.getElementById("map_canv").style.display = "none";
							        document.getElementById("street").style.display = "";
							        SideBarVisible(false);							        
							        var street = new GStreetviewPanorama(document.getElementById("street"));
							        street.setLocationAndPOV(camera, pov);
							    }
							}
						)
				    }
				}
			);
}


LatLon.distHaversine = function(lat1, lon1, lat2, lon2) {
    var R = 6371; 
    var dLat = (lat2 - lat1).toRad();
    var dLon = (lon2 - lon1).toRad();
    lat1 = lat1.toRad(), lat2 = lat2.toRad();

    var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
          Math.cos(lat1) * Math.cos(lat2) *
          Math.sin(dLon / 2) * Math.sin(dLon / 2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    var d = R * c;
    return d;
}


LatLon.distCosineLaw = function(lat1, lon1, lat2, lon2) {
    var R = 6371; 
    var d = Math.acos(Math.sin(lat1.toRad()) * Math.sin(lat2.toRad()) +
                    Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * Math.cos((lon2 - lon1).toRad())) * R;
    return d;
}


LatLon.bearing = function(lat1, lon1, lat2, lon2) {
    lat1 = lat1.toRad(); lat2 = lat2.toRad();
    var dLon = (lon2 - lon1).toRad();

    var y = Math.sin(dLon) * Math.cos(lat2);
    var x = Math.cos(lat1) * Math.sin(lat2) -
          Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon);
    return Math.atan2(y, x).toBrng();
}


LatLon.midPoint = function(lat1, lon1, lat2, lon2) {
    lat1 = lat1.toRad();
    lat2 = lat2.toRad();
    var dLon = (lon2 - lon1).toRad();

    var Bx = Math.cos(lat2) * Math.cos(dLon);
    var By = Math.cos(lat2) * Math.sin(dLon);

    lat3 = Math.atan2(Math.sin(lat1) + Math.sin(lat2),
                    Math.sqrt((Math.cos(lat1) + Bx) * (Math.cos(lat1) + Bx) + By * By));
    lon3 = lon1.toRad() + Math.atan2(By, Math.cos(lat1) + Bx);

    if (isNaN(lat3) || isNaN(lon3)) return null;
    return new LatLon(lat3.toDeg(), lon3.toDeg());
}


LatLon.prototype.destPoint = function(brng, d) {
    var R = 6371; 
    var lat1 = this.lat.toRad(), lon1 = this.lon.toRad();
    brng = brng.toRad();

    var lat2 = Math.asin(Math.sin(lat1) * Math.cos(d / R) +
                        Math.cos(lat1) * Math.sin(d / R) * Math.cos(brng));
    var lon2 = lon1 + Math.atan2(Math.sin(brng) * Math.sin(d / R) * Math.cos(lat1),
                               Math.cos(d / R) - Math.sin(lat1) * Math.sin(lat2));
    lon2 = (lon2 + Math.PI) % (2 * Math.PI) - Math.PI;  

    if (isNaN(lat2) || isNaN(lon2)) return null;
    return new LatLon(lat2.toDeg(), lon2.toDeg());
}


LatLon.prototype.finalBrng = function(brng, d) {
    var p1 = this, p2 = p1.destPoint(brng, d);
   
    var rev = LatLon.bearing(p2.lat, p2.lon, p1.lat, p1.lon);
   
    var brng = (rev + 180) % 360;
    return brng;
}


LatLon.distRhumb = function(lat1, lon1, lat2, lon2) {
    var R = 6371; 
    var dLat = (lat2 - lat1).toRad(), dLon = Math.abs(lon2 - lon1).toRad();
    var dPhi = Math.log(Math.tan(lat2.toRad() / 2 + Math.PI / 4) / Math.tan(lat1.toRad() / 2 + Math.PI / 4));
    var q = (Math.abs(dLat) > 1e-10) ? dLat / dPhi : Math.cos(lat1.toRad());
   
    if (dLon > Math.PI) dLon = 2 * Math.PI - dLon;
    var d = Math.sqrt(dLat * dLat + q * q * dLon * dLon);
    return d * R;
}

LatLon.brngRhumb = function(lat1, lon1, lat2, lon2) {
    var dLon = (lon2 - lon1).toRad();
    var dPhi = Math.log(Math.tan(lat2.toRad() / 2 + Math.PI / 4) / Math.tan(lat1.toRad() / 2 + Math.PI / 4));
    if (Math.abs(dLon) > Math.PI) dLon = dLon > 0 ? -(2 * Math.PI - dLon) : (2 * Math.PI + dLon);
    return Math.atan2(dLon, dPhi).toBrng();
}

LatLon.prototype.destPointRhumb = function(brng, dist) {
    var R = 6371; 
    var d = parseFloat(dist) / R;  
    var lat1 = this.lat.toRad(), lon1 = this.lon.toRad();
    brng = brng.toRad();

    var lat2 = lat1 + d * Math.cos(brng);
    var dLat = lat2 - lat1;
    var dPhi = Math.log(Math.tan(lat2 / 2 + Math.PI / 4) / Math.tan(lat1 / 2 + Math.PI / 4));
    var q = (Math.abs(dLat) > 1e-10) ? dLat / dPhi : Math.cos(lat1);
    var dLon = d * Math.sin(brng) / q;
    if (Math.abs(lat2) > Math.PI / 2) lat2 = lat2 > 0 ? Math.PI - lat2 : -(Math.PI - lat2);
    lon2 = (lon1 + dLon + Math.PI) % (2 * Math.PI) - Math.PI;

    if (isNaN(lat2) || isNaN(lon2)) return null;
    return new LatLon(lat2.toDeg(), lon2.toDeg());
}

function LatLon(lat, lon) {
    this.lat = lat;
    this.lon = lon;
}

LatLon.prototype.toString = function() {
    return this.lat.toLat() + ', ' + this.lon.toLon();
}

String.prototype.parseDeg = function() {
    if (!isNaN(this)) return Number(this);                 

    var degLL = this.replace(/^-/, '').replace(/[NSEW]/i, '');  
    var dms = degLL.split(/[^0-9.]+/);                     
    for (var i in dms) if (dms[i] == '') dms.splice(i, 1);    
    switch (dms.length) {                                  
        case 3:                                              
            var deg = dms[0] / 1 + dms[1] / 60 + dms[2] / 3600; break;
        case 2:                                              
            var deg = dms[0] / 1 + dms[1] / 60; break;
        case 1:                                            
            if (/[NS]/i.test(this)) degLL = '0' + degLL;   
            var deg = dms[0].slice(0, 3) / 1 + dms[0].slice(3, 5) / 60 + dms[0].slice(5) / 3600; break;
        default: return NaN;
    }
    if (/^-/.test(this) || /[WS]/i.test(this)) deg = -deg; 
    return deg;
}

Number.prototype.toRad = function() {  
    return this * Math.PI / 180;
}

Number.prototype.toDeg = function() {  
    return this * 180 / Math.PI;
}

Number.prototype.toBrng = function() { 
    return (this.toDeg() + 360) % 360;
}


Number.prototype.toDMS = function() {  
    var d = Math.abs(this);  
    d += 1 / 7200; 
    var deg = Math.floor(d);
    var min = Math.floor((d - deg) * 60);
    var sec = Math.floor((d - deg - min / 60) * 3600);
    
    if (deg < 100) deg = '0' + deg; if (deg < 10) deg = '0' + deg;
    if (min < 10) min = '0' + min;
    if (sec < 10) sec = '0' + sec;
    return deg + '\u00B0' + min + '\u2032' + sec + '\u2033';
}

Number.prototype.toLat = function() {  
    return this.toDMS().slice(1) + (this < 0 ? 'S' : 'N');  
}

Number.prototype.toLon = function() {  
    return this.toDMS() + (this > 0 ? 'E' : 'W');
}

Number.prototype.toPrecision = function(fig) { 
    if (this == 0) return 0;                   
    var scale = Math.ceil(Math.log(this) * Math.LOG10E);
    var mult = Math.pow(10, fig - scale);
    return Math.round(this * mult) / mult;
}

