// MapUtil.js
var currentMarkerIcon = "http://www.mvdirona.com/Maps/Icons/SmallRedMarkerWithCircle.png";
var normalMarkerIcon = "http://www.mvdirona.com/Maps/Icons/SmallBlueMarkerWithCircle.png";

// Define the ES5 String.trim() method if one does not already exist.
String.prototype.trim = String.prototype.trim || function ()
{
    if (!this) return this; // Don't alter the empty string
    return this.replace(/^\s+|\s+$/g, ""); // Regular expression magic
};

// Define ES5 Date.now() if doesn't already exist
Date.now = Date.now || function() 
{    
    return +new Date();   
};

function showLocationMap(navList)
{
    placeMap = createMap(navList[0]);
    var maxNav = (this.maxLocation == undefined || maxLocation > navList.length) ? navList.length : maxLocation;

    var placeListElements = "";
    var subListDate = 0;
    for (i = 0; i < maxNav; i++)
    {
        var placeListName = navList[i].placeNameOnly;
        if (isLargeMap && navList[i].date && navList[i].date.valueOf() != subListDate)
        {
            if (subListDate != 0) placeListElements += "</ul>";
            var curDate = navList[i].date;
            if (i + 1 == maxNav || navList[i].date.valueOf() != navList[i + 1].date.valueOf())
            {
                // end previout list
                subListDate = 0;
                placeListName = isLargeMap ? curDate.mmddyyyy() + ": " : "";
                placeListName += navList[i].placeNameOnly;
            }
            else
            {
                //start new sublist
                placeListElements += "<li class='mapPlaceListEntryDateOnly'>" + curDate.mmddyyyy() + "</li>";
                placeListElements += "<ul class='mapPlaceList'>";
                subListDate = navList[i].date.valueOf();
            }
        }
        placeListElements += "<li id=placeList_" + i + " class='mapPlaceListEntry'>" + placeListName + "</li>";
        createMarker(navList[i]);
    }
    if (subListDate != 0) placeListElements += "</ul>"

    $("#placeList").append(placeListElements);

    for (i = 0; i < maxNav; i++)
    {
        var placeListElement = document.getElementById("placeList_" + i);
        navList[i].placeListElement = placeListElement;
        placeListElement.nav = navList[i];
        placeListElement.onclick = function () { onSelectPlace(this.nav); };
    }
    onSelectPlace(navList[0]);
}

function setLocation(nav)
{
    if (placeMap.prevNav)
    {
        var prevNav = placeMap.prevNav;
        prevNav.placeListElement.style.color = placeMap.prevListItemColor
        if (!offline)
        {
            prevNav.marker.setIcon(normalMarkerIcon);
            prevNav.marker.zIndex = placeMap.prevZIndex;
        }
    }
    placeMap.prevListItemColor = nav.placeListElement.style.color;
    nav.placeListElement.style.color = 'red';
    if (!offline)
    {
        placeMap.prevZIndex = nav.marker.zIndex;
        nav.marker.zIndex = google.maps.Marker.MAX_ZINDEX;
        nav.marker.setIcon(currentMarkerIcon);
    }
    placeMap.prevNav = nav;
}

function panTo(nav)
{
    setLocation(nav);
    if (placeMap.panTo) placeMap.panTo(new google.maps.LatLng(nav.lng, nav.lat));
}

function showLocationWithWindow(nav)
{
    setLocation(nav);
    if (nav.marker) openInfoWindow(nav.marker);
}

function openInfoWindow(marker)
{
    if (placeMap.prevInfoWindow) placeMap.prevInfoWindow.close();
    var nav = marker.nav;
    var windowContent =
                    "<div class='infoWindowContainer'>" +
                    "<div class='infoWindowTitle'>" + nav.name + "<\div>" +
                    nav.img +
                    "<div class='infoWindowText'>" + nav.description + "<\div>" +
                    "</div>";
    var infoWindow = new google.maps.InfoWindow({ content: windowContent });
    infoWindow.open(placeMap, marker);
    placeMap.prevInfoWindow = infoWindow;
}

function createMarker(curNav)
{
    if (offline) return;
    var latLng = new google.maps.LatLng(curNav.lng, curNav.lat);
    var image = normalMarkerIcon;
    var marker = new google.maps.Marker({
        position: latLng,
        title: curNav.name,
        map: placeMap,
        icon: image,
        zIndex: google.maps.Marker.MAX_ZINDEX - curNav.index,
        nav: curNav
    });
    curNav.marker = marker;
    google.maps.event.addListener(marker, "click", function (thisMarker)
    {
        return function ()
        {
            onSelectPlace(thisMarker.nav);
        };
    } (marker));
}

function createMap(curNav)
{
    if (offline) return {};
    var latlng = new google.maps.LatLng(curNav.lng, curNav.lat);
    var myOptions = {
        zoom: 10,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var mapElement = document.getElementById("map");
    return new google.maps.Map(mapElement, myOptions);
}

function parseKmlFile(kmlFile, processNavs)
{
    var nav = [];
    $.get(kmlCurrentLocationFile, function (data)
    {
        //loop through placemarks tags
        $(data).find("Placemark").each(function (index, value)
        {
            var coords = $(this).find("coordinates").text();
            var c = coords.split(",")
            var lat = c[0];
            var lng = c[1];

            var curNav = {
                "lat": lat,
                "lng": lng,
                "index": nav.length
            }
            parseName($(this).find("name").text(), curNav);
            parseDescription($(this).find("description"), curNav);
            (window.logOrder!= undefined && logOrder == "ascending") ? nav.unshift(curNav) : nav.push(curNav);
        });
        $(document).ready(function ()
        {
            processNavs(nav);
        });
    });
}

function parseName(name, curNav)
{
    curNav.name = curNav.placeNameOnly = name;
    var match = name.match(/(\d{1,2})\/(\d{1,2})\/(\d{1,2})[:,](.*)/)
    if (!match) return;
    curNav.date = new Date(/*yyyy*/2000 + Number(match[3]), /*mm*/match[1] - 1, /*dd*/match[2]);
    curNav.date.mmdd = function ()
    {
        return this.getMonth() + 1 + "/" + this.getDate();
    }
    curNav.date.mmddyyyy = function ()
    {
        return this.mmdd() + "/" + this.getFullYear();
    }
    curNav.placeNameOnly = match[4].trim();
}

function parseDescription(descripElem, curNav)
{
    description = "";
    img = "";
    var htmlIn = descripElem.text();
    var hasCDATA = false;
    var parseComplete = false;
    try
    {
        // Seem to get different behavior when run locally--text() returns stripped of html so need to use html(), but
        // is has CDATA still there. But can't use html() except locally. :(
        htmlIn = descripElem.html();
        hasCDATA = htmlIn.match(/.*?!(--)?\[CDATA\[/);
    }
    catch (e)
    { }

    while (htmlIn && htmlIn != "")
    {
        htmlIn = htmlIn.replace(/[\r\n]+/g, ' ');
        description = htmlIn;
        if (hasCDATA)
        {
            // Chrome adds -- after ! and before first >, so strip those out if there
            var match = htmlIn.match(/.*?!(--)?\[CDATA\[\s*(.*?)(\1>)(.*?)\]\].*/);
            if (match != null && match.length > 1)
            {
                description = match[2] + ">" + match[4];
            }
            else
            {
                // try without ">"
                var match = htmlIn.match(/.*?!(--)?\[CDATA\[\s*(.*?)(.*?)\]\].*/);
                if (match != null && match.length > 1)
                {
                    description = match[3];
                }
                else
                {
                    // no HTML in the description, so just return whatever might be there
                    description = descripElem.text();
                    break;
                }
            }
        }
        var descripMatch = description.match(/(.*?)<img src=["'](.*?)["']\/?>(.*)/i);
        if (descripMatch == null) break;
        var img = "<a href='";
        var hrefMatch = descripMatch[1].match(/.*?href=["'](.*?)["']/i);
        img += (hrefMatch != null ? hrefMatch[1] : descripMatch[2]) + "' target='_blank'>";
        if (this.thumbnailSize == undefined) thumbnailSize = 200;
        img += "<img src='" + descripMatch[2] + "' height='" + thumbnailSize + "'></a>";
        description = descripMatch[3];
        break;
    }
    curNav.img = img;
    curNav.description = description;
}

