﻿// locationMapping.js

var indepentpharmaciesname = 'Independent Pharmacies';

function ShowMap(name, chainCode, mapDiv, width, height, key) {
    debugText('ShowMap name:[' + name + '] width:[' + width.toString() + '] height: [' + height.toString() + '] key: [' + key + ']');

    if (mapDiv == undefined) { var mapDiv = document.getElementById('mapDiv'); }

    debugText('ShowMap2 name:[' + name + '] width:[' + width.toString() + '] height: [' + height.toString() + '] key: [' + key + ']');

    if (mapDiv) {
        mapDiv.innerHTML = GetMapImageHTML(name, chainCode, width, height, key);
    }
}

function GetMapImageHTML(name, chainCode, width, height, key) {
    var imageElement = 'mapping error';

    if (pharmacies2 != undefined) {
        var markerstring = pharmacies2.MarkersString(name, chainCode);
        var zoomstring = '';

        if (pharmacies2.ChainByChainCode(chainCode).locations.length < 2) {
            zoomstring = '&zoom=13';
        }
        
        if (markerstring.length > 0) {
            imageElement = new String('<img src="http://maps.google.com/staticmap?size=' + width.toString() + 'x' + height.toString() + markerstring + zoomstring + '&key=' + key + '" alt="Map" />');
        } else {
            var paddingSides = parseInt(width / 3);
            var paddingTopBottom = parseInt(height / 2.2);
            imageElement = new String('<div style="padding: ' + paddingTopBottom.toString() + 'px ' + paddingSides.toString() + 'px; background-color: White; ">Map Unavailable</div>');
        }
    }

    return imageElement;
}

// **********************************  Pharmacy methods  **********************************


function ToAddressString(includeName, includeLegend, includeKey) {
    var legend = "";
    var name = "";
    var key = "";
    var keyPrefix = "";
    var address = this.address1 + "<br />" +
                  this.city + ", " + this.state + " " + this.zip + "<br />" +
                  //"lat:" + this.latitude.toString() + "<br />" +
                  //"long:" + this.longitude.toString() + "<br />" +
                  this.phone;

    if (includeName) { name = "<b>" + this.chain.name + "</b><br />"; }
    if (includeLegend) { name = "<span class='legend' >" + this.legend + ")</span>&nbsp;&nbsp;" + name; }
    if (includeKey) {
        var drivethrough = "";
        if (this.driveThru) { drivethrough = "Drive Thru"; }

        var twenty47 = "";
        if (this.twentyFourSeven) { twenty47 = "24 Hour"; }
        
        var mapPin = '';
        if (this.latitude == 0.00 || this.longitude == 0.00) {
            mapPin = '<br />Map Pin Unavailable';
        }

        keyPrefix = '<div style="float: left;padding: 4px; " >';
        key = '&nbsp;&nbsp;<span style="width: 60; color: #008000;" >' + twenty47 + '</span>&nbsp;&nbsp;<span style="width: 60; color: #800000;" >' + drivethrough + '</span>' + mapPin + '</div><div class="clear"></div>';
    }
    
    return keyPrefix + name + address + key;
}

// **********************************  Pharmacy Collection methods  **********************************


function AllLocationsIncludeName() {
    var pharmacyList = new String();


    for (var chainIndex = 0; chainIndex < pharmacies2.chains.length; chainIndex++) {
        var pharmacyChain = pharmacies2.chains[chainIndex];
        for (var locationIndex = 0; locationIndex < pharmacyChain.locations.length; locationIndex++) {
            var pharmacyLocation = pharmacyChain.locations[locationIndex];

            if (pharmacyLocation) {
                if (pharmacyList.length != 0) {
                    pharmacyList += "<br /><br />";
                }

//                pharmacyList += pharmacyLocation.toAddressStringWithCustomLegend(pharmacyLocation.legend);
                pharmacyList += pharmacyLocation.ToAddressString(true, true, true);
                if (pharmacyLocation.latitude == 0.00 || pharmacyLocation.longitude == 0.00) {
                    pharmacyList += "<br />Map pin unavailable";
                }
            }
        }
    }

    return pharmacyList;
}

function PharmacyById(id) {
    for (var chainIndex = 0; chainIndex < pharmacies2.chains.length; chainIndex++) {
        var pharmacyChain = pharmacies2.chains[chainIndex];
        for (var locationIndex = 0; locationIndex < pharmacyChain.locations.length; locationIndex++) {
            var pharmacyLocation = pharmacyChain.locations[locationIndex];

            if (pharmacyLocation.id == id) {
                return pharmacyLocation;
            }
        }
    }

    return null;        // PharmacyId not found
}

function PharmacyByAddress(address) {
    var Address = new String(address).toLowerCase();
    for (var chainIndex = 0; chainIndex < pharmacies2.chains.length; chainIndex++) {
        var pharmacyChain = pharmacies2.chains[chainIndex];
        for (var locationIndex = 0; locationIndex < pharmacyChain.locations.length; locationIndex++) {
            var pharmacyLocation = pharmacyChain.locations[locationIndex];
            var locationAddress = new String(pharmacyLocation.address1 + ', ' + pharmacyLocation.city + ', ' + pharmacyLocation.state + ', ' + pharmacyLocation.zip + ', USA').toLowerCase();

            if (locationAddress == Address) {
                return pharmacyLocation;
            }
        }
    }

    return null;        // PharmacyId not found
}

// **********************************  Pharmacy methods  **********************************

var geoCodeChainIndex = 0;
var geoCodeLocationIndex = -1;
var geoCodeAttempts = 1;
var geoCodeTimeout = null;

function GeoCodePharmacyLocations() {
    if (geoCodeTimeout != null) {
        window.clearTimeout(geoCodeTimeout);
        geoCodeTimeout = null;
    }

    var pharmacyLocation = null;
    do {
        var pharmacyChain = pharmacies2.chains[geoCodeChainIndex];
        if (pharmacyChain) {
            geoCodeLocationIndex++;

            if (geoCodeLocationIndex < pharmacyChain.locations.length) {
                if (pharmacyChain.locations[geoCodeLocationIndex].latitude == 0.00 || pharmacyChain.locations[geoCodeLocationIndex].longitude == 0.00) {
                    pharmacyLocation = pharmacyChain.locations[geoCodeLocationIndex];
                }
            } else {
                geoCodeLocationIndex = -1;
                geoCodeChainIndex++;
                if (geoCodeChainIndex >= pharmacies2.chains.length) {
                    geoCodeChainIndex = 0;
                    geoCodeAttempts++;
                }
            }
        } else {
            geoCodeAttempts = 11;
        }
    } while (pharmacyLocation == null && geoCodeAttempts < 10);

    if (pharmacyLocation != null) {
        var address = new String(pharmacyLocation.address1 + ', ' + pharmacyLocation.city + ', ' + pharmacyLocation.state + ', ' + pharmacyLocation.zip + ', USA');
        geocoder.getLocations(address, function(response) { SetLatLong(response); });

        geoCodeTimeout = window.setTimeout(GeoCodePharmacyLocations, 100 * geoCodeAttempts);
    }

    if (geoCodeAttempts > 9 && pharmacyLocatorPage) {
        pharmacies2.CalculateZoomInfo();
        GeoCodingCompletePharmacyLocator();
    }
}

function SetLatLong(response) {
    if (response && response.Status.code == 200) {
        var place = response.Placemark[0];
        var pharmacy = pharmacies2.PharmacyByAddress(response.name);

        if (pharmacy != undefined) {
            pharmacy.latitude = place.Point.coordinates[1];
            pharmacy.longitude = place.Point.coordinates[0];
        }
    }
}


// This will be set to true when appropriate
var pharmacyLocatorPage = false;

function GeoCodingCompletePharmacyLocator() {
    if (divPharmacyList == undefined) { var divPharmacyList = document.getElementById('divPharmacyList'); }
    
    if ((pharmacies2 != undefined) && (divPharmacyList != undefined)) {
        var html = pharmacies2.allLocationsIncludeName();

        if (showPharmaciesList != undefined) { showPharmaciesList(); }
        
        divPharmacyList.innerHTML = html;
    }

    if (initMap != undefined) {
        initMap();
    }

    showWorking(false);
}

function LocationsFound() {
    if (pharmacies2.chains.length < 1) return false;
    for (var chainIndex = 0; chainIndex < pharmacies2.chains.length; chainIndex++) {
        var pharmacyChain = pharmacies2.chains[chainIndex];
        for (var locationIndex = 0; locationIndex < pharmacies2.chains[chainIndex].locations.length; locationIndex++) {
            if (pharmacies2.chains[chainIndex].locations[locationIndex] != null) return true;
        }
    }

    return false;
}

function CalculateZoomInfo() {
    var minLat = 90.0;
    var maxLat = 0.00;
    var minLon = 180.0;
    var maxLon = -180.00;

    for (var chainIndex = 0; chainIndex < pharmacies2.chains.length; chainIndex++) {
        var pharmacyChain = pharmacies2.chains[chainIndex];
        for (var locationIndex = 0; locationIndex < pharmacyChain.locations.length; locationIndex++) {
            var pharmacyLocation = pharmacyChain.locations[locationIndex];

            if (pharmacyLocation.latitude != 0.00) {
                if (pharmacyLocation.latitude > maxLat) { maxLat = pharmacyLocation.latitude; }
                if (pharmacyLocation.latitude < minLat) { minLat = pharmacyLocation.latitude; }
            }

            if (pharmacyLocation.longitude != 0.00) {
                if (pharmacyLocation.longitude > maxLon) { maxLon = pharmacyLocation.longitude; }
                if (pharmacyLocation.longitude < minLon) { minLon = pharmacyLocation.longitude; }
            }
        }
    }

    this.centerLatitude = (maxLat + minLat) / 2;
    this.centerLongitude = (maxLon + minLon) / 2;

    this.eastWestDistance = (maxLon - minLon) * 70;  // using 70 mi per degree as a simple approximation
    this.northSouthDistance = (maxLat - minLat) * 70;  // using 70 mi per degree as a simple approximation
}


function ChainByChainCode(chainCode) {
    for (var chainIndex = 0; chainIndex < pharmacies2.chains.length; chainIndex++) {
        var pharmacyChain = pharmacies2.chains[chainIndex];

        if (pharmacyChain.chainCode == chainCode) {
            return pharmacyChain;
        }
    }

    return null;        // chainCode not found
}

function AllLocationsForChain(chainCode) {
    var pharmacyList = new String();

    var pharmacyChain = pharmacies2.ChainByChainCode(chainCode);
    if (pharmacyChain) {
        for (var locationIndex = 0; locationIndex < pharmacyChain.locations.length; locationIndex++) {
            if (pharmacyChain.isPseudoChainCode) {
                pharmacyList += pharmacyChain.locations[locationIndex].ToAddressString(true, false, false) /*.toAddressStringWithName()*/ + '<br /><br />';
            } else {
                pharmacyList += pharmacyChain.locations[locationIndex].ToAddressString(true, true, true);  /*.toAddressString(true);*/
            }
        }
    }

    return pharmacyList;
}

function GetMarkersString(name, chainCode) {
    var ms = '';

    var pharmacyChain = pharmacies2.ChainByChainCode(chainCode);
    if (pharmacyChain) {
        var firstPoint = true;
        for (var locationIndex = 0; locationIndex < pharmacyChain.locations.length; locationIndex++) {
            var pharmacyLocation = pharmacyChain.locations[locationIndex];
            if ((pharmacyLocation.latitude != 0.00) && (pharmacyLocation.longitude != 0.00)) {
                if (!firstPoint) { ms = ms + '%7C'; } else { firstPoint = false; }

                ms = ms + pharmacyLocation.latitude.toString() + ',' + pharmacyLocation.longitude.toString() + ',blue' + new String(pharmacyLocation.legend).toLowerCase();
            }
        }

        if (ms.length > 0) {
            ms = '&markers=' + ms;
        }
    }

    return ms;
}

// **********************************  Page Load methods  **********************************


function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            oldonload();
            func();
        }
    }
}

function addUnloadEvent(func) {
    var oldonunload = window.onunload;
    if (typeof window.onunload != 'function') {
        window.onunload = func;
    } else {
        window.onunload = function() {
            oldonunload();
            func();
        }
    }
}

// **********************************  Mouse Location methods  **********************************


function getMouseXY2(e) {
    if (window.event) {
        var e = window.event; 
    }

    mouseX2 = mouseX(e);
    mouseY2 = mouseY(e);
}

function mouseX(evt) {
    if (evt.pageX) return evt.pageX;
    else if (evt.clientX)
        return evt.clientX + (document.documentElement.scrollLeft ?
                                       document.documentElement.scrollLeft :
                                       document.body.scrollLeft);
    else return null;
}
function mouseY(evt) {
    if (evt.pageY) return evt.pageY;
    else if (evt.clientY)
        return evt.clientY + (document.documentElement.scrollTop ?
                                       document.documentElement.scrollTop :
                                       document.body.scrollTop);
    else return null;
}

var clientWindowWidth = 0;
var clientWindowHeight = 0;
var clientScrollX = 0;
var clientScrollY = 0;

function getWindowSize() {
    if (typeof (window.innerWidth) == 'number') {
        //Non-IE
        clientWindowWidth = window.innerWidth;
        clientWindowHeight = window.innerHeight;
    } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        //IE 6+ in 'standards compliant mode'
    clientWindowWidth = document.documentElement.clientWidth;
    clientWindowHeight = document.documentElement.clientHeight;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        //IE 4 compatible
    clientWindowWidth = document.body.clientWidth;
    clientWindowHeight = document.body.clientHeight;
    }

    if (typeof (window.pageYOffset) == 'number') {
        //Netscape compliant
        clientScrollY = window.pageYOffset;
        clientScrollX = window.pageXOffset;
    } else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
        //DOM compliant
        clientScrollY = document.body.scrollTop;
        clientScrollX = document.body.scrollLeft;
    } else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
        //IE6 standards compliant mode
        clientScrollY = document.documentElement.scrollTop;
        clientScrollX = document.documentElement.scrollLeft;
    }
//    return [scrOfX, scrOfY];
}
