﻿//Global Variables
var map;
var currentAddress = "";
var currentLat;
var currentLng;
var currentPoint;
var divDirection;
var gDir;
var mapDiv;
var newdiv;
var directions;



//    Intializes the Map and divDirection objects
function Intialize() {
    mapDiv = document.getElementById("map");
    map = new GMap2(mapDiv);
    map.addControl(new GSmallMapControl());
    map.addControl(new GMenuMapTypeControl());
    mapDiv.style.height = divmapHeight + 'px';
    mapDiv.style.width = divmapWidth + 'px';
    directions = document.getElementById('directions');
    if (newdiv != null) {
        var olddiv = document.getElementById('divDirection');
        directions.removeChild(olddiv);
    }

    newdiv = document.createElement('div');
    var divIdName = 'divDirection';
    newdiv.setAttribute('id', divIdName);

    directions.appendChild(newdiv);
    divDirection = document.getElementById(divIdName);
    gDir = new GDirections(map, divDirection);
}

//    Creates the PushPin (Marker) on the Map
function createMarker(point, html) {
    var marker;
    marker = new GMarker(point);
    GEvent.addListener(marker, "click", function () {
        marker.openInfoWindowHtml(html);
    });
    return marker;
}

//    This method draws the map
//    Display marker for current location and nearest store locations
function FindStoreLocations(txtStrretClientID, txtSuburbClientID, txtPostalCodeClientID) {
    Intialize();
    //        Getting Current Address
    currentAddress = "";
    var currentStreet = document.getElementById(txtStrretClientID);
    var currentSuburb = document.getElementById(txtSuburbClientID);
    var currentZipCode = document.getElementById(txtPostalCodeClientID);

    if (currentStreet.value != "") {
        currentAddress = currentStreet.value;
    }
    if (currentSuburb.value != "") {
        if (currentAddress != "") {
            currentAddress = currentAddress + "," + currentSuburb.value;
        }
        else {
            currentAddress = currentSuburb.value;
        }
    }
    if (country != "" && currentAddress != "") {
        currentAddress = currentAddress + "," + country;
    }
    else {
        currentAddress = country;
    }

    if (currentZipCode.value != "") {
        currentAddress = currentAddress + "," + currentZipCode.value;
    }
    //        Getting the lat and lng for current location
    var latLng = new GClientGeocoder();
    latLng.getLatLng(currentAddress, ReturnLatLng);
}

//    CallBack function for getting lat and lng for source location
function ReturnLatLng(result) {
    currentLat = result.lat();
    currentLng = result.lng();
    currentPoint = new GLatLng(currentLat, currentLng);
    var currentMarker = createMarker(currentPoint, "<b>You are Here: </b>" + currentAddress);
    map.addOverlay(currentMarker);
    map.setCenter(currentPoint, 10);
    DisplayStoreLocations();
}

function DisplayStoreLocations() {

    map.enableDoubleClickZoom();
    map.enableScrollWheelZoom();
    for (counter = 0; counter < output.length; counter++) {
        var latLon = output[counter][1].split(",");
        var point = new GLatLng(latLon[0], latLon[1]);
        //            Calculate the distance between current address and store location
        var srcdestdistance = CalculateDistance(point);
        //            check if distance is in between search radii
        if (srcdestdistance < parseFloat(searchRadii)) {
            //                    Generate the HTML for direction
            var html = output[counter][2];
            html = html + output[counter][0];
            html = html + "<input type='hidden' id='daddr' name='daddr' value='" + latLon[0] + "," + latLon[1] + "' />";
            html = html + "<br/>" + "<a onclick='javascript:GetDirections();' href='#'>" + getDirectionText + "</a>";
            if (output[counter][3] != '#' && output[counter][3] != '') {
                html = html + "&nbsp;" + "<a href='" + output[counter][3] + "'>" + storePageText + "</a>";
            }
            var marker = createMarker(point, html);
            map.addOverlay(marker);
            map.setCenter(point, 10);
        }
    }
}

//    Function to calculate the distance
function CalculateDistance(dest) {
    var distance;
    var distance = currentPoint.distanceFrom(dest, 3959);
    if (distanceUnitMeasure == 'km') {
        distance = (distance * 1.609344).toFixed(2);
    }
    return distance;
}

//    Function to get the directions
function GetDirections() {
    divDirection.style.display = "none";
    var dAddress = document.getElementById('daddr');
    var dLatLng = dAddress.value.split(",");
    var query = "from: " + dLatLng[0] + "," + dLatLng[1] + " to:" + currentLat + "," + currentLng;
    gDir.load(query, G_TRAVEL_MODE_DRIVING);
    divDirection.style.display = "block";
}

function InitializeStaticMap(country) {
    mapDiv = document.getElementById("map");
    map = new GMap2(mapDiv);
    map.addControl(new GSmallMapControl());
    map.addControl(new GMenuMapTypeControl());
    mapDiv.style.height = '350px';
    mapDiv.style.width = '300px';
    currentAddress = country;
    var latLng = new GClientGeocoder();
    latLng.getLatLng(currentAddress, ReturnLatLng_ForStaticMap);


}

//    CallBack function for getting lat and lng for source location
function ReturnLatLng_ForStaticMap(result) {

    DisplayAllStoreLocations();
    //This was above DisplayAllStoreLocations Function
    currentLat = result.lat();
    currentLng = result.lng();
    currentPoint = new GLatLng(currentLat, currentLng);
    var currentMarker = createMarker(currentPoint, "<b>You are Here: </b>" + currentAddress);
    map.addOverlay(currentMarker);
    map.setCenter(currentPoint, 10);

}

function InitStaticMap(latitude, longitude) {

    mapDiv = document.getElementById("map");
    map = new GMap2(mapDiv);
    map.addControl(new GSmallMapControl());
    map.addControl(new GMenuMapTypeControl());
    mapDiv.style.height = '380px';
    mapDiv.style.width = '360px';
    currentPoint = new GLatLng(latitude, longitude);
    //var currentMarker = createMarker(currentPoint, "<b>Olet tässä</b>");  /* Removed as it was creating the unwanted marker on the map which was not related to any store.*/
    //map.addOverlay(currentMarker);/* Removed as it was creating the unwanted marker on the map which was not related to any store.*/
    //alert(currentPoint);
    map.setCenter(currentPoint, 4);

    map.panBy(new GSize(130, 285))
}

function InitStaticMapCountry(latitude, longitude, cntryName, storeBrand) {
    mapDiv = document.getElementById("map");
    map = new GMap2(mapDiv);
    map.addControl(new GSmallMapControl());
    map.addControl(new GMenuMapTypeControl());

    mapDiv.style.height = '380px';
    mapDiv.style.width = '360px';
    currentPoint = new GLatLng(latitude, longitude);

    var zoomlevel = 4;
    if (cntryName == "Latvia" || cntryName == "Estonia") {
        zoomlevel = 6;
    }
    else if (cntryName == "Russia") {
        zoomlevel = 4;
    }
    map.setCenter(currentPoint, zoomlevel);

    if (cntryName == "Finland")
        map.panBy(new GSize(0, 50)) //Finland

    if (cntryName == "Sweden")
    //        map.panTo(currentPoint)
        map.panBy(new GSize(100, 240)) //Sweden

    if (cntryName == "Estonia")
        map.panBy(new GSize(175, 120)) //Estonia

    if (cntryName == "Latvia")
        map.panBy(new GSize(190, 150)) //Latvia

    if (cntryName == "Russia")
        map.panBy(new GSize(0, 50)) //TODO: Russia (Need to get correct size)

    // map.checkResize();

}

function DisplayAllStoreLocations(largeMapText, siteURL) {
    for (counter = 0; counter < output.length; counter++) {
        var latLon = output[counter][1].split(",");
        var point = new GLatLng(latLon[0], latLon[1]);
        var html = output[counter][2];
        var storeURL = siteURL;
        html = html + output[counter][0];
        html = html + "<input type='hidden' id='daddr' name='daddr' value='" + latLon[0] + "," + latLon[1] + "' />";

        if (output[counter][3] != '#' && output[counter][3] != '') {
            html = html + "<br/><br/>" + "<a href='" + output[counter][3] + "' target='_blank'>" + storePageText + "</a>";
        }
        storeURL = storeURL.replace('storeplace', output[counter][4]);

        html = html + "<br/><br/>" + "<a href= '" + storeURL + "' + target='_blank'>" + largeMapText + "</a>";


        var marker = createCenteredMarker(point, html);
        storeURL = "";

        //        GEvent.addListener(marker, "click", function () {
        //            // options.pixelOffset = new GSize(130, 285);
        //            marker.openInfoWindowHtml(html);
        //        });
        map.addOverlay(marker);
        // map.panTo(point);

    }
    //    map.setCenter(currentPoint, 4);
    //    map.panBy(new GSize(130, 285))   
}

function ShowStore(lati, longi, index) {

    mapDiv = document.getElementById("map");
    map = new GMap2(mapDiv);
    map.addControl(new GSmallMapControl());
    map.addControl(new GMenuMapTypeControl());
    mapDiv.style.height = '300px';
    mapDiv.style.width = '220px';

    var point = new GLatLng(lati, longi);
    var html = output[index][2];
    html = html + output[index][0];
    html = html + "<input type='hidden' id='daddr' name='daddr' value='" + lati + "," + longi + "' />";
    if (output[index][3] != '#' && output[index][3] != '') {
        html = html + "<br/><br/>" + "<a href='" + output[index][3] + "' target='_blank'>" + storePageText + "</a>";
    }
    html = html + "<br/><br/>" + "<a href=http://maps.google.com?q=" + lati + "," + longi + " target='_blank'>Suurempi kartta</a>";
    var marker;
    marker = new GMarker(point);
    map.addOverlay(marker);
    map.setCenter(point, 4);
    map.panBy(new GSize(-300, 140));
    marker.openInfoWindowHtml(html);

}

function createCenteredMarker(point, html) {
    var marker;
    marker = new GMarker(point);
    GEvent.addListener(marker, "click", function () {
        marker.openInfoWindowHtml(html);
        //map.panTo(point);
        map.checkResize();
    });

    return marker;

}

   

    
