﻿// =============================================================================
// (c) 2008 MapJack.com
// Author: Bjorn Moren. bjorn@mapjack.com
// =============================================================================

google.load("search", "1");

var _displayedCity = -1;
var _displayedPOICategory = null;   // Name of selected POI category
var _poiStartIndex = 0;
var _poiRowsPerDisplay = 8;
var _poiMaxListSize = 50;
var _poiList = [];
var _poiCategories = [];
var _cityPOIs = [];
var _searchPOIs = null;
var _poiMessage = null;
var _searchText = "";
var _gSearcher = null;
var _encodeChars = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789";

var _searchExample = "";
var _searchExamples = ["kings st", "queens st and kings st", "hotels near kings st", "dining"];
var _geoCodedAreas =
[
    {lat1:-90, lat2:90, lon1:-180, lon2:34}
];

function contentLoad()
{
    var citySelectObj = document.getElementById("citySelect");
    if (citySelectObj)
    {
        for (var i = 0; i < _cities.length; i++)
        {
            var optionObj = new Option(_cities[i].name, _cities[i].name);
            citySelectObj.options[citySelectObj.options.length] = optionObj;
        }
    }
    setTimeout("updateCity();", 3000);
}

// Calls a function in any frame
function contentCall(name)
{
    var appFrames = [];
    contentGetFrames(window.top, appFrames);
    for (var i = 0; i < appFrames.length; i++)
    {
        var func = appFrames[i][name];
        if (func) return func(arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], arguments[6]);
    }
    return null;    
}

function contentGetFrames(win, arr)
{
    arr.push(parent.frames["content"]);
    arr.push(parent.frames["map"]);
    arr.push(parent.frames["main"].frames["panorama"]);
    return;

    arr[arr.length] = win;
    for (var i = 0; i < win.frames.length; i++)
       contentGetFrames(win.frames[i], arr);
}

function changeCity()
{
    var index = document.getElementById("citySelect").selectedIndex;
    contentCall("navigateToEncoded", _cities[index].viewPoint);
}

function updateCity()
{
    var latLon = contentCall("getLatLon");
    if (latLon == null || latLon.x == 0 || latLon.y == 0) return false;
 
    // Find city and change the select box
    var citySelectObj = document.getElementById("citySelect");
    if (!citySelectObj) return;
    var foundIndex = -1;
    for (var i = 0; i < _cities.length; i++)
    {
		//alert(_cities[i].lat1 +"<="+ latLon.y +"&&"+ _cities[i].lat2 +">"+ latLon.y +"&&"+ _cities[i].lon1 +"<="+ latLon.x +"&&"+_cities[i].lon2 +">"+ latLon.x);
        if (_cities[i].lat1 <= latLon.y && _cities[i].lat2 > latLon.y && _cities[i].lon1 <= latLon.x &&_cities[i].lon2 > latLon.x)
        {
			
			//alert(_cities[i].lat1 <= latLon.y && _cities[i].lat2 > latLon.y && _cities[i].lon1 <= latLon.x &&_cities[i].lon2 > latLon.x);
            foundIndex = i;
            break;
        }
    }
    citySelectObj.selectedIndex = foundIndex;
    if (_displayedCity == foundIndex) return true;
    _displayedCity = foundIndex;
    if (foundIndex < 0)
    {
        var poiObj = document.getElementById("poiDiv");
        removeChildren(poiObj);
        return true;
    }
    
    // Show/hide search field
    var searchControlsObj = document.getElementById("searchControls");
    var searchBoxObj = document.getElementById("searchBox");
    if (searchControlsObj)
    {
        var isGeoCoded = false;
        for (var i = 0; i < _geoCodedAreas.length; i++)
        {
			//alert(_geoCodedAreas[i].lat1 +"<="+ latLon.y +"&&"+ _geoCodedAreas[i].lat2 +">"+ latLon.y +"&&"+ _geoCodedAreas[i].lon1 +"<="+ latLon.x +"&&"+_geoCodedAreas[i].lon2 +">"+ latLon.x);
			//alert(_geoCodedAreas[i].lat1 <= latLon.y && _geoCodedAreas[i].lat2 > latLon.y && _geoCodedAreas[i].lon1 <= latLon.x &&_geoCodedAreas[i].lon2 > latLon.x);
			
            if (_geoCodedAreas[i].lat1 <= latLon.y && _geoCodedAreas[i].lat2 > latLon.y && _geoCodedAreas[i].lon1 <= latLon.x &&_geoCodedAreas[i].lon2 > latLon.x)
  				
				isGeoCoded = true;
        }
        if (isGeoCoded)
        {
            searchControlsObj.style.display = "";
            _searchExample = _searchExamples[parseInt(Math.random() * 10000) % _searchExamples.length];
            searchBoxObj.value = _searchExample;
        }
        else
        {
            searchControlsObj.style.display = "none";
        }
    }
    
    _displayedPOICategory = null;
    _poiStartIndex = 0;
    _poiMessage = null;
    updatePOIList();
    return true;
}

function changePOICategory(name)
{
    _displayedPOICategory = name;
    _poiStartIndex = 0;
    _poiMessage = null;
    updatePOIList();
}

function updatePOIList()
{
    var poiObj = document.getElementById("poiDiv");
    if (!poiObj || _displayedCity < 0) return;

    removeChildren(poiObj);
    if (!_cities[_displayedCity].pois || _cities[_displayedCity].pois.length == 0) return;
    
    // Extract valid POIs
    var cityPOIs = _cities[_displayedCity].pois;
    _poiCategories = [];
    _poiList = [];
    for (var i = 0; i < cityPOIs.length; i++)
    {
        if (_displayedPOICategory == null) _displayedPOICategory = cityPOIs[i].category;
        var foundCategory = false;
        for (var j = 0; j < _poiCategories.length; j++)
        {
            if (_poiCategories[j] == cityPOIs[i].category)
            {
                foundCategory = true;
                if (_poiCategories[j] == _displayedPOICategory && _poiList.length < _poiMaxListSize) _poiList[_poiList.length] = cityPOIs[i];
            }
        }
        if (!foundCategory) 
        {
            if (cityPOIs[i].category == _displayedPOICategory && _poiList.length < _poiMaxListSize) _poiList[_poiList.length] = cityPOIs[i];
            _poiCategories[_poiCategories.length] = cityPOIs[i].category;
        }
    }
    
    // Display POI menu
    var menuHTML = "";
    for (var i = 0; i < _poiCategories.length; i++)
    {
        var url = "javascript:changePOICategory('" + _poiCategories[i] + "');";
        var name = _poiCategories[i].replace(" ", "&nbsp;");
        if (_poiCategories[i] == _displayedPOICategory) menuHTML += '<a href="' + url + '"><b>' + name + '</b></a>';
        else menuHTML += '<a href="' + url + '">' + name + '</a>';
        if (i != _poiCategories.length - 1) menuHTML += "&nbsp;| ";
    }
    poiObj.appendChild(createDiv(menuHTML, "poiMenu"));

    // Display POI list
    poiObj.appendChild(createDiv(_displayedPOICategory, "heading2"));
    if (_poiMessage)
    {
        poiObj.appendChild(createDiv("<br><b>" + _poiMessage + "</b><br>&nbsp;", "poiList"));
    }
    else
    {
        for (var i = 0; i < _poiList.length; i++)
        {
            var poi = _poiList[i];
            poi.tooltip = "";
            if (poi.name) poi.tooltip = poi.name;
            if (poi.text)
            {
                if (poi.tooltip != "") poi.tooltip += " -- ";
                poi.tooltip += poi.text;
            }
            if (poi.tooltip.length > 175) poi.tooltip = poi.tooltip.substring(0, 170) + "...";
            
            if (i < _poiStartIndex || i >= _poiStartIndex + _poiRowsPerDisplay) continue;

            var url = "#";
            if (poi.viewPoint) url = "javascript:nav('" + poi.viewPoint + "');";
            else if (poi.lat) url = "javascript:nav(" + poi.lat + "," + poi.lon + ");";
            var img = "<img src=\"Images/Marker" + (i + 1) + ".gif\" align=\"left\" border=\"0\" width=\"23\" height=\"16\">";
            var html = "<a href=\"" + url + "\" title=\"" + poi.tooltip + "\">" + img + poi.name + "</a>";
            if (poi.link)
                html += "&nbsp;&nbsp;<a href=\"" + poi.link + "\" target=\"_blank\" title=\"" + poi.link + "\">[info]</a>";
            
            poiObj.appendChild(createDiv(html, "poiList"));
        }

        // Add markers to the map
        addMapMarkers();

        // List navigation
        var navHTML = "";
        if (_poiStartIndex > 0) navHTML += "<a href='javascript:navBack();'>&lt;&nbsp;Back</a> ";
        if (_poiStartIndex + _poiRowsPerDisplay < _poiList.length) navHTML += "<a href='javascript:navMore();'>More&nbsp;&gt;</a>";
        poiObj.appendChild(createDiv(navHTML, "poiListNav"));
        
        // Show POIs inside panorama
        updatePOIs();
    }
}

function updatePOIs()
{
    if (!contentCall("setPOIs", _poiList))
    {
        setTimeout("updatePOIs();", 1000);
    }
}

function addMapMarkers()
{
    if (!contentCall("removeMarkers"))
    {
        setTimeout("addMapMarkers();", 1000);
    }
    for (var i = 0; i < _poiList.length; i++)
    {
        var viewPoint = null;
        if (_poiList[i].viewPoint) viewPoint = _poiList[i].viewPoint;
    
        if (_poiList[i].lat && _poiList[i].lon)
        {
            contentCall("addMarker", _poiList[i].lat, _poiList[i].lon, (i + 1), viewPoint, _poiList[i].tooltip);
        }
        else if (viewPoint)
        {
            var pos = decodePosition(viewPoint);
            contentCall("addMarker", pos.lat, pos.lon, (i + 1), viewPoint, _poiList[i].tooltip);
        }
    }
    contentCall("zoomPanOnMarkers");
}

function navMore()
{
    _poiStartIndex += _poiRowsPerDisplay;
    _poiMessage = null;
    updatePOIList();
}

function navBack()
{
    _poiStartIndex -= _poiRowsPerDisplay;
    _poiMessage = null;
    updatePOIList();
}

function startSearch()
{
    _displayedPOICategory = "Search result";
    _poiMessage = "Searching...";
    updatePOIList();

    _searchText = document.getElementById("searchBox").value + " " + _cities[_displayedCity].name;
    var pos = contentCall("getLatLon");
    if (pos == null) pos = "94111";
    
    _gSearcher = new GlocalSearch();
    _gSearcher.setNoHtmlGeneration();
    _gSearcher.setCenterPoint(pos);
    _gSearcher.setResultSetSize(GSearch.LARGE_RESULTSET);
    _gSearcher.setSearchCompleteCallback(window, searchComplete, [_gSearcher]);
    _gSearcher.execute(_searchText);
    return false;
}

function searchComplete(searcher) 
{
    // Clear previous search (if any)
    var poiList = _cities[_displayedCity].pois;
    if (!poiList)
    {
        _cities[_displayedCity].pois = [];
        poiList = _cities[_displayedCity].pois;
    }
    for (var i = poiList.length - 1; i >= 0; i--)
    if (poiList[i].category == "Search result") poiList.length--;

    if (searcher.results && searcher.results.length > 0) 
    {
        for (var i = 0; i < searcher.results.length; i++)
        {
            var result = searcher.results[i];
            var name = result.title;
            for (var r= 0; r < 4; r++) name = name.replace("<b>", "").replace("</b>", "");
            if (name.length > 35) name = name.substring(0, 35) + "...";
            var poi = {name:name, category:"Search result", lat:result.lat, lon:result.lng};
            poi.text = result.streetAddress + ", " + result.city + ", " + result.region;
            if (result.phoneNumbers && result.phoneNumbers.length > 0)
            {
                poi.text += ", phone " + result.phoneNumbers[0].number;
                poi.link = result.url;
            }
            
            poiList[poiList.length] = poi;
        }
        _poiMessage = null;
    }
    else
    {
        _poiMessage = "Could not find '" + _searchText + "'.";
    }
    updatePOIList();
}

function removeChildren(parent) 
{
    while (parent.firstChild) parent.removeChild(parent.firstChild);
}

function createDiv(opt_text, opt_className) 
{
    var el = document.createElement("div");
    if (opt_text) el.innerHTML = opt_text;
    if (opt_className) { el.className = opt_className; }
    return el;
}

function nav(lat, lon, turn)
{
    if (!lon) contentCall("navigateToEncoded", lat);
    else contentCall("navigateTo", lat, lon, turn);
}

function decodePosition(code)
{
    if (code == null || code.length < 10) return null;
	var result = new Object();
	
	var latVal = decodeInt(code.substr(0, 5));
	result.lat = (latVal / 1000000.0) - 180.0;

	var lonVal = decodeInt(code.substr(5, 5));
	result.lon = (lonVal / 1000000.0) - 180.0;

	return result;
}

function decodeInt(code)
{
	var result = 0;
	for (var i = code.length - 1; i >= 0; i--)
	{
		var charNo = _encodeChars.indexOf(code.substr(i, 1));
		if (charNo < 0 || charNo >= _encodeChars.length) return 0;
		result = result * _encodeChars.length + charNo;
	}
	return result;
} 



