﻿// JScript File
var mapIcons   = new Array();
mapIconsAdd ('home', false, false, undefined, mapDesignPath+'assets/img/mapIcons/iconMyHome.png', 35, 22, mapDesignPath+'assets/img/mapIcons/iconMyHomeShadow.png', 54, 22, 18, 34, 5, 1)
mapIconsAdd ('store', false, false, undefined, mapDesignPath+'assets/img/mapIcons/iconStoreNormal.png', 22, 28, mapDesignPath+'assets/img/mapIcons/iconStoreShadow.png', 49, 28, 8, 27, 5, 1)
mapIconsAdd ('store', false, false, 'available', mapDesignPath+'assets/img/mapIcons/iconStoreAvailable.png', 22, 28, mapDesignPath+'assets/img/mapIcons/iconStoreShadow.png', 49, 28, 8, 27, 5, 1)
mapIconsAdd ('store', false, false, 'exhausted', mapDesignPath+'assets/img/mapIcons/iconStoreLimited.png', 22, 28, mapDesignPath+'assets/img/mapIcons/iconStoreShadow.png', 49, 28, 8, 27, 5, 1)
mapIconsAdd ('store', false, false, 'unavailable', mapDesignPath+'assets/img/mapIcons/iconStoreUnavailable.png', 22, 28, mapDesignPath+'assets/img/mapIcons/iconStoreShadow.png', 49, 28, 8, 27, 5, 1)
mapIconsAdd ('store', true, false, undefined, mapDesignPath+'assets/img/mapIcons/iconMyStoreNormal.png', 29, 40, mapDesignPath+'assets/img/mapIcons/iconMyStoreShadow.png', 56, 40, 16, 39, 5, 1)
mapIconsAdd ('store', false, true, undefined, mapDesignPath + 'assets/img/mapIcons/iconCheckoutNormal.png', 29, 40, mapDesignPath + 'assets/img/mapIcons/iconMyStoreShadow.png', 56, 40, 16, 39, 5, 1)
mapIconsAdd ('store', true, false, 'available', mapDesignPath+'assets/img/mapIcons/iconMyStoreAvailable.png', 29, 40, mapDesignPath+'assets/img/mapIcons/iconMyStoreShadow.png', 56, 40, 16, 39, 5, 1)
mapIconsAdd ('store', true, false, 'exhausted', mapDesignPath+'assets/img/mapIcons/iconMyStoreLimited.png', 29, 40, mapDesignPath+'assets/img/mapIcons/iconMyStoreShadow.png', 56, 40, 16, 39, 5, 1)
mapIconsAdd ('store', true, false, 'unavailable', mapDesignPath+'assets/img/mapIcons/iconMyStoreUnavailable.png', 29, 40, mapDesignPath+'assets/img/mapIcons/iconMyStoreShadow.png', 56, 40, 16, 39, 5, 1)
var mapStores = new Array ();
var markers = new Array();
var mapGeocoder = null;
var map = null;
var mapPoints = new Array();
var mapAlreadyLoaded = false;
var mapStoresPointSet = false;
var infoWindow;

function mapAddHome (point)
{
    var i = mapGetIcon ('home', false, false, undefined);
    if (i != null)
    {
        var icon = new google.maps.MarkerImage();
        icon.url = i.iconPath;
        icon.size = new google.maps.Size(i.iconWidth, i.iconHeight);
        icon.anchor = new google.maps.Point(i.iconAnchorX, i.iconAnchorY);

        var shadow = new google.maps.MarkerImage();
        shadow.url = i.shadowPath;
        shadow.size = new google.maps.Size(i.shadowWidth, i.shadowHeight);
        
        //icon.infoWindowAnchor = new google.maps.Point(i.infoAnchorX, i.infoAnchorY);
        markers.push(mapCreateMarker (point, icon, shadow, 'Casa tua'));
        //map.addOverlay(marker);
    }
}
function mapAddStores ()
{
    for (thisStore in mapStores)
    {
        var s = mapStores[thisStore];
        if (typeof (s.point) != 'undefined' && s.point.lng() != 0)
        {
            var ic = mapGetIcon('store', (typeof (mapFavouriteStore) == 'undefined' || mapFavouriteStore != s.id) ? false : true,
                (typeof (mapCheckoutStore) == 'undefined' || mapCheckoutStore != s.id) ? false : true,
                s.productStatus);
            if (ic != null)
            {
                var icon = new google.maps.MarkerImage();
                icon.url = ic.iconPath;
                icon.iconSize = new google.maps.Size(ic.iconWidth, ic.iconHeight);
                icon.anchor = new google.maps.Point(ic.iconAnchorX, ic.iconAnchorY);

                var shadow = new google.maps.MarkerImage();
                shadow.url = ic.shadowPath;
                shadow.size = new google.maps.Size(ic.shadowWidth, ic.shadowHeight);
                
                //icon.infoWindowAnchor = new google.maps.Point(ic.infoAnchorX, ic.infoAnchorY);
                markers.push(mapCreateMarker4store (s.point, icon, shadow, s));
                //map.addOverlay(marker);
            }
        }
    }
}
function mapAppendCell (row, text)
{
    var c = row.insertCell ();
    c.innerText = text;
}
function mapBounds (point1, point2)
{
    var laF = Math.min (point1.lat(), point2.lat())
        , laT = Math.max(point1.lat(), point2.lat())
        , lnF   = Math.min (point1.lng(), point2.lng())
        , lnT   = Math.max(point1.lng(), point2.lng());
    return (new google.maps.LatLngBounds (new google.maps.LatLng (laF, lnF), new google.maps.LatLng(laT, lnT)));
}
function mapBoundsExtend(bounds, quota)
{
    var pF = bounds.getSouthWest()
        , pT = bounds.getNorthEast()
        , laF = pF.lat()
        , laT = pT.lat()
        , lnF = pF.lng()
        , lnT = pT.lng()
        , ila = (laT - laF) * quota
        , iln = (lnT - lnF) * quota;
    return (new google.maps.LatLngBounds (new google.maps.LatLng(laF - ila, lnF - iln), new google.maps.LatLng (laT + ila, lnT + iln)));
}
function mapCreateMarker(point, icon, shadow, text)
{
    var marker = new google.maps.Marker({
        map: map,
        icon: icon,
        shadow: shadow,
        position: point });
    google.maps.event.addListener(marker, "click", function () {
        infoWindow.setContent('Casa tua');
        infoWindow.open(map, marker);
    });
    return (marker);
}
function mapCreateMarker4store(point, icon, shadow, store)
{
    var marker = new google.maps.Marker({
        map: map,
        icon: icon,
        shadow: shadow,
        position: point });
    google.maps.event.addListener(marker, "click", function () {
        //if (typeof (store.hours) == 'undefined' && typeof (store.phones) == 'undefined' && typeof (store.email) == 'undefined') {
            infoWindow.setContent(mapFirstTab(store));
            infoWindow.open(map, marker);
        /*}
        else {
            var ts = [new google.maps.InfoWindowTab(mapStoreAddress, mapFirstTab(store))
                , new google.maps.InfoWindowTab(mapStoreOther
                    , '<div class="mapsStoreDetailsDiv">'
                        + ((typeof (store.hours) == 'undefined') ? ''
                            : '<p class="mapsStoreDetailsInfo"><strong>' + mapstoreHours + '</strong>: ' + store.hours + '</p>')
                        + ((typeof (store.phones) == 'undefined') ? ''
                            : '<p class="mapsStoreDetailsInfo"><strong>' + mapteleph + '</strong>: ' + store.phones + '</p>')
                        + ((typeof (store.email) == 'undefined') ? ''
                            : '<p class="mapsStoreDetailsInfo"><strong>' + mapemail + '</strong>: <a href="mailto:' + store.email + '">'
                                + store.email + '</a></p>')
                        + '</div>')
                        ];
            infoWindow.open(map, ts);
        }*/
    });
    return (marker);
}
function mapErrorAdd (text)
{
    document.getElementById('mapError').innerHTML += text + '<br>';
}
function mapFirstTab (store)
{
    return ('<p class="mapsStoreDetailsTitle">' + store.name
        + ((typeof(store.centre) == 'undefined') ? '' : ', ' + store.centre) + '</p>'
        + '<div class="mapsStoreDetailsDiv">'
        + ((typeof (store.address) == 'undefined') ? ''
             : '<p class="mapsStoreDetailsInfo"><strong>'+mapaddressCaps+'</strong>:</p><p class="mapsStoreDetailsInfo">' + store.address
                + ((typeof (store.streetNumber) == 'undefined') ? '' : ', ' + store.streetNumber) + '</p>')
        + '<p class="mapsStoreDetailsInfo">'
        + ((typeof (store.zip) == 'undefined') ? '' : store.zip)
        + ' - ' + ((typeof (store.city) == 'undefined') ? '' : ' ' + store.city) + '</p>'
			  + ((typeof (store.phones) == 'undefined') ? ''
            : '<br /><p class="mapsStoreDetailsInfo"><strong>' + mapteleph + '</strong>: ' + store.phones + '</p>')
        + ((typeof (store.email) == 'undefined') ? ''
            : '<p class="mapsStoreDetailsInfo"><strong>' + mapemail + '</strong>: <a href="mailto:' + store.email + '">'
                + store.email + '</a></p>')
        + '</div>'
        + ((typeof (store.thumbnail) == 'undefined') ? ''
            : '<div class="mapsStoreDetailsDiv"><a href="' + store.image + '" target=_blank><img alt="' + store.name + '" src="'
                + store.thumbnail + '"></a></div>')
        + '<p class="buttons">'
        + ((typeof (mapUser) != 'undefined' && (typeof (mapFavouriteStore) == 'undefined' || store.id != mapFavouriteStore) && !isCheckout)
            ? '<a href="javascript:loaderMapShow();mapSetMyStore(' + store.id
                + ')">'+mapsetPreStore+'</a>'
            : '')
        + ((typeof (mapUser) != 'undefined' && (typeof (mapCheckoutStore) == 'undefined' || store.id != mapCheckoutStore) && isCheckout && store.availableForRopis)
            ? '<a href="javascript:loaderMapShow();mapSetCheckoutStore(' + store.id
                + ')">' + mapsetCheckoutStore + '</a>'
            : '')
				+ '<br class="clearingElement" /></p>'		
        + '<div class="mapsStoreDetailsDiv">'
        + ((typeof (store.newStatus) == 'undefined') ? ''
            : '<p class="mapsStoreDetailsInfo"><strong>'+mapnewprod+'</strong>: ' + mapStatusTranslate (store.newStatus) + '</p>')
        + ((typeof (store.secondHandStatus) == 'undefined') ? ''
            : '<p class="mapsStoreDetailsInfo"><strong>'+mapusedprod+'</strong>: ' + mapStatusTranslate(store.secondHandStatus) + '</p>')
        + '</div>'
        + '<div class="mapsStoreDetailsDiv">'
        + ((typeof (store.hours) == 'undefined') ? ''
            : '<p class="mapsStoreDetailsInfo"><strong>' + mapstoreHours + '</strong>: ' + store.hours + '</p>')
        + ((typeof (store.phones) == 'undefined') ? ''
            : '<p class="mapsStoreDetailsInfo"><strong>' + mapteleph + '</strong>: ' + store.phones + '</p>')
        + ((typeof (store.email) == 'undefined') ? ''
            : '<p class="mapsStoreDetailsInfo"><strong>' + mapemail + '</strong>: <a href="mailto:' + store.email + '">'
                + store.email + '</a></p>')
        + '</div>');
}
function mapGetIcon (type, favourite, checkout, productStatus)
{
    for (var i=0 ; i < mapIcons.length ; i++)
    {
        var ic = mapIcons[i];
        if (ic.type == type && ic.favourite == favourite && ic.checkout == checkout &&
            (typeof(ic.productStatus) == 'undefined' && typeof(productStatus) == 'undefined' || ic.productStatus == productStatus))
            return (ic);
    }
    mapErrorAdd ('icon ' + type + ', ' + favourite + ', ' + productStatus + ' non found');
    return (null);
}
function mapGetStore (id)
{
    return mapStores[id.toString()];
}
function mapIcon (type, favourite, checkout, productStatus, iconPath, iconWidth, iconHeight, shadowPath, shadowWidth, shadowHeight
    , iconAnchorX, iconAnchorY, infoAnchorX, infoAnchorY)
{
    this.type   = type;
    this.favourite  = favourite;
    this.checkout = checkout;
    this.productStatus  = productStatus;
    this.iconPath   = iconPath;
    this.iconWidth  = iconWidth;
    this.iconHeight = iconHeight;
    this.shadowPath = shadowPath;
    this.shadowWidth    = shadowWidth;
    this.shadowHeight   = shadowHeight;
    this.iconAnchorX    = iconAnchorX;
    this.iconAnchorY    = iconAnchorY;
    this.infoAnchorX    = infoAnchorX;
    this.infoAnchorY    = infoAnchorY;
}
function mapIconsAdd (type, favourite, productStatus, iconPath, iconWidth, iconHeight, shadowPath, shadowWidth, shadowHeight
    , iconAnchorX, iconAnchorY, infoAnchorX, infoAnchorY)
{
    mapIcons[mapIcons.length] = new mapIcon (type, favourite, productStatus, iconPath, iconWidth, iconHeight, shadowPath, shadowWidth
        , shadowHeight, iconAnchorX, iconAnchorY, infoAnchorX, infoAnchorY);
}
function mapLoad()
{
    mapStoresSetPoint();
    mapAlreadyLoaded = true;
    if (typeof (google.maps) != 'undefined')
    {
        infoWindow = new google.maps.InfoWindow();
        var myOptions = {
            zoom: 8,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("mapDiv"), myOptions);
        //map.addControl(new google.maps.SmallMapControl());
        //map.addControl(new google.maps.TypeControl());
        mapGeocoder = new google.maps.Geocoder();
        if (typeof (mapHome) != 'undefined')
        {
            retrieveLocation(mapHome);
        }
        else
        {
            mapShow(null);
        }
    }
}

function retrieveLocation(address) {
    if (mapGeocoder)
        mapGeocoder.geocode(
            { address: address,
                region: mapCountryCode
            }, function (result, status) {
                if (status != "OK") {
                    mapShow(null);
                }
                else {
                    resultPoint = result[0].geometry.location;
                    document.getElementById('mapHomePosition').value = resultPoint.lng() + ',' + resultPoint.lat();
                    mapShow(resultPoint);
                }
            });
}

function mapSetMyStore(id)
{
    mapFavouriteStore = id;
    document.getElementById('mapFavouriteStore').value = id;
    __doPostBack(mapClientId.replace('_', '$') + '$bSetFavouriteStore','');
}

function mapSetCheckoutStore(id) {
    mapCheckoutStore = id;
    document.getElementById('mapCheckoutStore').value = id;
    javascript: WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ucCheckout0$map$bSetCheckoutStore", "", true, "", "", false, true))
    //__doPostBack(mapClientId.replace('_', '$') + '$bSetCheckoutStore', '');
}


function mapShow(home)
{
    document.getElementById("searchNoResults").innerHTML = "";
    if (home == null)
    {
        if (typeof (mapFavouriteStore) == 'number')
            home = mapGetStore(mapFavouriteStore).point;
        else if (typeof (mapCheckoutStore) == 'number')
            home = mapGetStore(mapCheckoutStore).point;
        else if (typeof (mapHomeLat) != 'undefined' && typeof (mapHomeLng) != 'undefined')
            home = new google.maps.LatLng(mapHomeLat, mapHomeLng);
        
        document.getElementById("searchNoResults").innerHTML = cantFindTheAddress;
    }
    if (home) {
        for (thisStore in mapStores) {
            var s = mapStores[thisStore];
            if (typeof (s.point) != 'undefined'
                && (typeof (mapProduct) == 'undefined'
                    || typeof (s.productStatus) != 'undefined' && s.productStatus != 'unavailable')) {
                s.distanceFromHome = google.maps.geometry.spherical.computeDistanceBetween(home, s.point);
            }
        }
        mapStoresSorted = sortAssoc(mapStores);
        if (isCheckout)
            showNearStores(home.lng(), home.lat());
    }
    else {
        mapStoresSorted = mapStores;
    }
    
    var firstPoint = home;
    var bounds = null;
    var store;
    var i=0;

    if (home) {
        for (thisStore in mapStoresSorted) {
            store = mapStoresSorted[thisStore];
            if (typeof (store.distanceFromHome) != 'undefined' && store.distanceFromHome <= 70000) {
                if (typeof (store.point) != 'undefined' && store.point.x != 0) {
                    if (firstPoint == null)
                        firstPoint = store.point;
                    else if (bounds == null)
                        bounds = new mapBounds(firstPoint, store.point);
                    else
                        bounds.extend(store.point);
                }
                i++;
            }
            if (i >= 4)
                break;
        }
    }
    else { // add all stores to the map
        for (thisStore in mapStoresSorted) {
            store = mapStoresSorted[thisStore];
            
            if (typeof (store.point) != 'undefined' && store.point.x != 0) {
                if (firstPoint == null)
                    firstPoint = store.point;
                else if (bounds == null)
                    bounds = new mapBounds(firstPoint, store.point);
                else
                    bounds.extend(store.point);
            }
        }
    }
    if (bounds != null) {
        bounds = mapBoundsExtend(bounds, 0.1);
        map.fitBounds(bounds);  
    }
    else if (home != null)
    {
        map.setCenter(new google.maps.LatLng(home.lat(), home.lng()));
    }

    google.maps.event.trigger(map, 'resize');
    map.setZoom(map.getZoom());
    
    if (home != null && !isCheckout)
        mapAddHome(home);
    mapAddStores ();
}

function firstStore()
{
    for (thisStore in mapStores)
        return mapStores[thisStore].distanceFromHome;
}

function sortAssoc(aInput) {
    var aTemp = [];
    for (var sKey in aInput)
        aTemp.push([sKey, aInput[sKey]]);
    aTemp.sort(mapStoreDistanceFromHomeCompare);

    var aOutput = new Array();
    for (var nIndex = aTemp.length - 1; nIndex >= 0; nIndex--)
    {
        tempObject = new Object();
        tempObject = aTemp[nIndex][1];
        aOutput.push(tempObject);
    }

    return aOutput;
}

function mapStatusTranslate (status)
{
    return ((status == 'unavailable') ? mapnotAvai : (status == 'exhausted') ? mapfewPie
        : (status == 'available') ? mapavail : mapnotDef);
}
function mapStore (id, name, address, streetNumber, zip, city, province, centre, hours, phones, email, longitude, latitude, thumbnail
    , image, productStatus, newStatus, secondHandStatus, availableForRopis)
    {
    this.id = id;
    this.name = name;
    this.address = address;
    this.streetNumber = streetNumber;
    this.zip    = zip;
    this.city   = city;
    this.province   = province;
    this.centre = centre;
    this.hours = hours;
    this.phones = phones;
    this.email = email;
    this.thumbnail  = thumbnail;
    this.image  = image;
    this.productStatus  = productStatus;
    this.newStatus  = newStatus;
    this.secondHandStatus = secondHandStatus;
    this.longitude = longitude;
    this.latitude = latitude;
    this.availableForRopis = availableForRopis;
    }
function mapStore2table (s)
{
    var t = document.getElementById('mapStores');
    var r = t.insertRow ();
    mapAppendCell (r, s.id);
    mapAppendCell (r, s.name);
    mapAppendCell (r, s.address);
    mapAppendCell (r, s.streetNumber);
    mapAppendCell (r, s.zip);
    mapAppendCell (r, s.city);
    mapAppendCell (r, s.province);
    mapAppendCell (r, s.centre);
    mapAppendCell (r, s.hours);
    mapAppendCell (r, s.phones);
    mapAppendCell (r, s.email);
    mapAppendCell (r, s.thumbnail);
    mapAppendCell (r, s.image);
    mapAppendCell (r, s.productStatus);
    mapAppendCell (r, s.newStatus);
    mapAppendCell (r, s.secondHandStatus);
    mapAppendCell (r, s.point.lng());
    mapAppendCell (r, s.point.lat());
}
function mapStores2table (s)
{
    for (thisStore in mapStores)
    {
        var s = mapStores[thisStore];
        mapStore2table (s);
    }
}
function mapStoreDistanceFromHomeCompare(store1, store2)
{
    store1 = mapStores[store1[0]];
    store2 = mapStores[store2[0]];
    var b1 = typeof (store1.distanceFromHome) == 'undefined', b2 = typeof (store2.distanceFromHome) == 'undefined';
    if (b1 || b2)
        if (b1 == b2)
            return (-1);
        else if (b1)
            return (0);
        else
            return (1);
    else if (store1.distanceFromHome < store2.distanceFromHome)
        return (1);
    else if (store1.distanceFromHome == store2.distanceFromHome)
        return (0);
    else
        return (-1);
}
function mapStoreGetLatLng (i, id)
{
    var s = mapStores[id];
    if (mapGeocoder && s.point.lng() == 0)
    {
        var str = s.address + ((typeof (s.streetNumber) == 'undefined') ? '' : ' ' + s.streetNumber)
            + ((typeof (s.zip) == 'undefined') ? '' : ' ' + s.zip) + ((typeof(s.city) == 'undefined') ? '' : ' ' + s.city)
            + ((typeof (s.province) == 'undefined') ? '' : ' ' + s.province + ' ' + mapDefaultCountry);
        mapGeocoder.getLatLng (str, function (point)
        {
            mapErrorAdd(i + ':' + point + ':' + str);
            if (point)
            {
                s.point = point;
                var r = document.getElementById('mapStores').rows[i+1];
                r.cells[r.cells.length - 2].innerText = point.lng();
                r.cells[r.cells.length - 1].innerText = point.lat();
            }
        });
    }
}
function mapStoresGetLatLng ()
{
    var i = 0
    for (thisStore in mapStores) {
        mapStoreGetLatLng(i, mapStores[thisStore].id);
        i++;
    }
}
function mapStoresSetPoint() 
{
    if (!mapStoresPointSet) 
    {
        if (typeof (google.maps) != 'undefined') {
            for (thisStore in mapStores) {
                var s = mapStores[thisStore];
                if (typeof (s.latitude) != 'undefined' && typeof (s.longitude) != 'undefined')
                    s.point = new google.maps.LatLng(s.latitude, s.longitude, 6371);
            }
            mapStoresPointSet = true;
        }
    }
}
function mapStoresUpdate ()
{
    var inp = document.getElementById('mapStoresPosition');
    inp.value = "";
    for (thisStore in mapStores)
    {
        var s = mapStores[thisStore];
        inp.value += s.id + "," + s.point.lng() + "," + s.point.lat() + ",";
    }
    __doPostBack(mapClientId + '$bUpdate','');
}

function mapZoomto (x, y)
{
    p = new google.maps.LatLng (y, x);
    map.panTo (p);
}

function removeMyStore()
{
    mapFavouriteStore = null;
}

