﻿// =============================================================================
// (c) 2008 MapJack.com
// Author: Bjorn Moren. bjorn@mapjack.com
// =============================================================================

google.load("search", "1");

var _displayedCity = -1;
var _searchText = "";
var _gSearcher = null;
var _searchExample = "";

var _citiesInfo = 
[
    [37.778716, -122.41994, "San Francisco, USA", "Pc7mWeY5bFZA", true, 
        ["Pier 39|BoGnWJZ8bFPA", "Jefferson St|MjGnWD96bFLF", "Maritime Park|XPGnWAm4bFHE", "Lombard st|3mEnW2f5bFiB", "The Embarcadero|ZgCnWdaDcFEF",
        "Broadway st|zWDnWPj9bFDF", "Filbert st|UaEnWnm8bFZE"],
        ["lombard st, sf", "bay st and powell st", "hotels near market st sf", "dining near pier 39"]
    ],
    
    [37.857197, -122.480988, "Sausalito, USA", "QkXnWEpjbF5F", true, 
        ["Bridgeway|nyWnWmPkbFnC"],
        ["571 bridgeway, sausalito", "johnson st and bonita st", "dining in sausalito"]
    ],

    [18.788522, 98.982559, "Chiang Mai, Thailand", "6fZyU2MbacZF", false, 
        ["Wat Phra Sing|6fZyU2MbacZF", "Three Kings Square|iGayUawcacQE", "Wat Mornthean|TpbyUmRbacUE", "Thanon Chang Lor|YUXyUS5ZaczF"],
        null
    ]
];

function contentLoad()
{
    var linkObj = document.getElementById("thisLocation");
    if (linkObj) linkObj.href = parent.location.href;
    
    var citySelectObj = document.getElementById("citySelect");
    if (citySelectObj)
    {
        for (var i = 0; i < _citiesInfo.length; i++)
        {
            var optionObj = new Option(_citiesInfo[i][2], _citiesInfo[i][2]);
            citySelectObj.options[citySelectObj.options.length] = optionObj;
        }
        citySelectObj.selectedIndex = 0;
    }
}

// Calls a function in any frame
function contentCall(name)
{
    var func = window[name];
    if (!func && parent)
    {
        for (var i = 0; i < parent.frames.length; i++)
        {
            func = parent.frames[i][name];
            if (func) break;
        }
    }
    if (func) return func(arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], arguments[6]);
    else return null;    
}

function changeCity()
{
    var index = document.getElementById("citySelect").selectedIndex;
    contentCall("navigateToEncoded", _citiesInfo[index][3]);
}

function updateCity()
{
    var latLon = contentCall("getLatLon");
    if (latLon == null || latLon.x == 0 || latLon.y == 0) return;
 
    // Find city and change the select box
    var citySelectObj = document.getElementById("citySelect");
    if (!citySelectObj) return;
    var closestIndex = -1;
    var minDistance = 100000;
    for (var i = 0; i < _citiesInfo.length; i++)
    {
        var distance = (_citiesInfo[i][0] - latLon.y) * (_citiesInfo[i][0] - latLon.y)  + 
            (_citiesInfo[i][1] - latLon.x) * (_citiesInfo[i][1] - latLon.x);
        if (distance < minDistance)
        {
            closestIndex = i;
            minDistance = distance;
        }
    }
    if (closestIndex < 0 || _displayedCity == closestIndex) return;
    hasHotspots = true;
    citySelectObj.selectedIndex = closestIndex;
        
    // Show/hide search field
    var searchBoxObj = document.getElementById("searchBox");
    var searchButtonObj = document.getElementById("searchButton");
    if (searchBoxObj && searchButtonObj)
    {
        _searchExamples = _citiesInfo[closestIndex][6];
        if (_searchExamples == null)
        {
            searchBoxObj.style.visibility = "hidden";
            searchButtonObj.style.visibility = "hidden";
        }
        else
        {
            searchBoxObj.style.visibility = "";
            searchButtonObj.style.visibility = "";
            _searchExample = _searchExamples[parseInt(Math.random() * 10000) % _searchExamples.length];
            searchBoxObj.value = _searchExample;
        }
    }

    // Show hot spots for the city
    var hotspotLinksObj = document.getElementById("hotspotLinks");
    if (hotspotLinksObj)
    {
        removeChildren(hotspotLinksObj);
        var hotspotList = _citiesInfo[closestIndex][5];
        for (var i = 0; i < hotspotList.length; i++)
        {
            var hotspotParts = hotspotList[i].split("|"); 
            hotspotLinksObj.appendChild(createDiv("<img src=\"Images/orangeDot.gif\" width=\"4\" height=\"4\" border=\"0\" align=\"absmiddle\" />&nbsp; " +
                "<a href=\"javascript:nav('" + hotspotParts[1] + "');\" class=\"locationLink\">" + hotspotParts[0] + "</a>"));
        }
    }
    
    _displayedCity = closestIndex;
}

function updateLocationLink(encPos)
{
    var linkObj = document.getElementById("thisLocation");
    if (!linkObj) return false;
    var urlParts = parent.location.href.split('?');
    urlParts = urlParts[0].split('#');
    linkObj.href = urlParts[0] + "?" + encPos;
    
    updateCity();
    return true;
}

function startSearch()
{
    var list = document.getElementById("resultList");
    _searchText = document.getElementById("searchBox").value;
    clearResults();
    list.appendChild(createDiv("&nbsp;"));
    list.appendChild(createDiv("Searching..."));
    list.appendChild(createDiv("&nbsp;"));
    
    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 clearForm()
{
    document.getElementById("searchBox").value = _searchExample;
    clearResults();
    contentCall("removeMarkers");
}

function searchComplete(searcher) 
{
    var list = document.getElementById("resultList");
    clearResults();
    contentCall("removeMarkers");
    
    var html = "<table cellpadding=0 cellspacing=0 border=0 width=100% style='margin:10px 0px 10px 0px'><tr>" +
        "<td><div class='normalTable'><a href='Help.html#Searching' target='_top'>Search tips</a></div></td>" +
        "<td align=right><input type='button' id='clearButton' name='clearButton' value='Clear list' onclick='clearForm();' /></td>" +
        "</tr></table>";
    
    list.appendChild(createDiv(html));
    if (searcher.results && searcher.results.length > 0) 
    {
       
        for (var i=0; i< searcher.results.length; i++)
        {
            var result = searcher.results[i];
            var hasPhone = (result.phoneNumbers && result.phoneNumbers.length > 0);

            var img = "<img src='Images/Marker" + i + ".gif' align='right' border='0'>";
            var url = "javascript:nav(" + result.lat + "," + result.lng + "," + (!hasPhone) + ");"
            
            list.appendChild(createDiv("<a href='" + url + "'>" + img + "</a><a href='" + url + "'>" + result.title + "</a>"));
            list.appendChild(createDiv(result.streetAddress));
            list.appendChild(createDiv(result.city + ", " + result.region ));
            if (hasPhone)
            {
                list.appendChild(createDiv(result.phoneNumbers[0].number));
                list.appendChild(createDiv("<a href='" + result.url + "' target='_blank'>Read more...</a>", "readLink"));
            }
            list.appendChild(createDiv("&nbsp;"));
            
            contentCall("addMarker", result.lat, result.lng, i);
        }
    }
    else
    {
        list.appendChild(createDiv("\"" + _searchText + "\" not found."));
        list.appendChild(createDiv("&nbsp;"));
    }
}

function clearResults() 
{
    removeChildren(document.getElementById("resultList"));
}

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);
}
