/* (c) Sam Gratrix */


// ===========================================================================================================
// Some global data to determine menus, providing a function to test if a castle belongs to a given menu.

var global_nav_data = new Array(
["All",      "All Castles",      function(castle) { return true; } ],
["England",  "English Castles",  function(castle) { return castle.country == 'ENG'; }],
["Wales",    "Welsh Castles",    function(castle) { return castle.country == 'WAL'; }],
["Scotland", "Scottish Castles", function(castle) { return castle.country == 'SCO'; }],
["Other",    "Other Castles",    function(castle) { return castle.country != 'ENG' &&
                                                           castle.country != 'WAL' &&
                                                           castle.country != 'SCO'; }]
);


// ===========================================================================================================
// Some castle stats, assumes data has been loaded.

function compute_castle_stats()
{
    this.total = new Array();

    for(var option=0; option<global_nav_data.length; option++)
    {
        this.total[option] = 0;

        var testfn = global_nav_data[option][2];

        for(var i=0; i<global_castle_data.length; i++)
        {
           var castle = global_castle_data[i];

           if(testfn(castle))
           {
               this.total[option]++;
           }
        }
    }
}

global_castle_stats = new compute_castle_stats();


// ===========================================================================================================
// Start over function.

function castle_home()
{
    show_maps(0);

    var html = '<p class="firstletter">';

    html += "Welcome to my (forever in progress) castle page. Here I present my best photograph from each of ";
    html += "the castles I have visited; along with some very brief notes pinched from guide books and ";
    html += "plaques (relevant references are given). "
    html += "To get started, just choose an item from the navigation menu.";
    html += "</p>";

    html += "<h3>Recent Updates</h3><p>Spring 2011</p>";
    html += castle_index(2);
    html += castle_index(15);
    html += castle_index(34);
    html += castle_index(35);
    html += castle_index(50);
    html += castle_index(53);
    html += castle_index(55);
    html += castle_index(68);
    html += castle_index(81);
    html += castle_index(82);
    html += castle_index(85);
    html += castle_index(88);
    html += castle_index(92);
    html += castle_index(103);
    html += castle_index(104);
    html += castle_index(108);
    html += castle_index(110);
    html += castle_index(119);

    html += '<h3>Castle Map</h3><p><a href="map/images/map.png">Click for an OS map showing the castles in Great Britain.</a></p>';
    html += '<p><i>OS maps reproduced from Ordnance Survey map data by permission of the Ordnance Survey, &copy; Crown copyright 2001.</i></p>'

    document.getElementById('titletext').innerHTML = "Gratrix.net Castles";
    document.getElementById('titleflag').src       = "flags/void.gif";
    document.getElementById('maintext').innerHTML  = html;

    castle_nav();
    castle_left();
}


// ===========================================================================================================
// This code generally covers top level menus.

function castle_nav()
{
    var html = '';

    html += '<p>'
    html += '<a href="#" onclick="castle_home();">Home</a> --- '

    for(var i=0; i<global_nav_data.length; i++)
    {
        if(i) html += ' - ';

        html += '<a href="#" onclick="castle_list(' + i + ');">' + global_nav_data[i][0] + '</a>'
    }

    html += '</p>';

    document.getElementById('nav2').innerHTML = html;
}

function castle_left()
{
    var html = '';

    for(var i=0; i<global_nav_data.length; i++)
    {
        html += '<div class="menu" onclick="castle_list(' + i + ')">';
        html += '<img width="100" height="60" src="nav/' + i + '.jpg" />';
        html += '<h1>' + global_nav_data[i][1] + '</h1>'
        html += '<p>' + global_castle_stats.total[i] + '</p>';
        html += '<div class="clean"></div>'
        html += '</div>';
    }

    document.getElementById('left2').innerHTML = html;
}


// ===========================================================================================================
// This code generally covers the left menu when it lists castles.

function castle_index(i)
{
    var castle = global_castle_data[i];

    if(castle.hist_cty.length && global_uk_historic_county_names[castle.hist_cty] != castle.county)
      var hist_cty =  ' (' + global_uk_historic_county_names[castle.hist_cty] + ')';
    else
      var hist_cty = '';

    if(castle.country == 'ENG' || castle.country == 'WAL' || castle.country == 'SCO')
      var location = castle.county + hist_cty;
    else
      var location = global_country_names[castle.country];

    var html  = '<div class="menu" onclick="update_body(' + i + ')">';

    html += '<img width="60" height="45" src="thumbs/' + castle.name + '.jpg" />';
    html += '<h2>' + castle.name + '</h2>'
    html += '<p>' + location + '</p>';
    html += '<div class="clean"></div>'

    return html + '</div>';
}

function castle_list(option)
{
    var html = '';

    for(var i=0; i<global_castle_data.length; i++)
    {
        var castle = global_castle_data[i];
        var testfn = global_nav_data[option][2];

        if(testfn(castle))
        {
            html += castle_index(i);
        }
    }

    document.getElementById('left2').innerHTML = html;
}


// ===========================================================================================================

function castle_body(castle)
{
    var text = '';
    var refs = '';

    if (global_castle_text[castle.name] != undefined)
    {
        text = global_castle_text[castle.name][0];
        refs = global_castle_text[castle.name][1];
    }

    // titles etc

    var flag_src = 'flags/' + castle.country + '.gif';
    var hist_cty = '';

    if(castle.hist_cty.length && global_uk_historic_county_names[castle.hist_cty] != castle.county)
    {
        var hist_cty =  ' (' + global_uk_historic_county_names[castle.hist_cty] + ')';
    }

    // pic box

    var pic_html = '';

    pic_html += (castle.info.length) ? '<h3>' + castle.info + '</h3>' : '<h3>' + castle.name + '</h3>';
    pic_html += '<img width="400" height="300" src="images/' + castle.name + '.jpg" />';
    pic_html += '<p>Location: ' + castle.county + hist_cty + ', ' + global_country_names[castle.country] + '</p>';

	if (castle.built.length)
	{
		pic_html += '<p>Built: ';
		pic_html += castle.build_key[castle.built[0]];
		for (var i=1; i<castle.built.length; ++i)
		{
			pic_html += ' - ' + castle.build_key[castle.built[i]];
		}
		pic_html += '</p>';
	}

	if (castle.type.length)
	{
		pic_html += '<p>Type: ';
		pic_html += castle.type_key[castle.type[0]];
		for (var i=1; i<castle.type.length; ++i)
		{
			pic_html += ', ' + castle.type_key[castle.type[i]];
		}
		pic_html += '</p>';
	}

    // small map info

    var map_html = globalCastleMarkerSet.display();

    // main text

    var txt_html = '';

    for(var i=0; i<text.length; i++)
    {
      txt_html += (i ? '<p>' : '<p class="firstletter">') + text[i] + '</p>';
    }

    for(var i=0; i<refs.length; i++)
    {
      txt_html += '<p>Ref: ';

      for(var j=0; j<refs[i].length; j++)
      {
        if(j) txt_html += ', ';

        txt_html += refs[i][j];

      }

      txt_html += '.</p>';
    }

    if(txt_html.length == 0) txt_html = '<p><i>Sorry there is no text for ' + castle.name + ' yet.</i></p>';

    // update page

    document.getElementById('titletext').innerHTML  = castle.name;
    document.getElementById('titleflag').src        = flag_src;
    document.getElementById('picture').innerHTML    = pic_html;
    document.getElementById('googletxt2').innerHTML = map_html;
    document.getElementById('maintext').innerHTML   = txt_html;
}


// ===========================================================================================================
// Class this will create and attach a marker for a map from a castle object. It also provides a kind of
// destructor that will remove it from the map.

function CastleMarker(map, castle, color)
{
    this.map    = map;
    this.castle = castle;
    this.color  = color;

    this.icon = new GIcon();
    this.icon.image  = 'http://labs.google.com/ridefinder/images/mm_20_' + this.color +'.png';
    this.icon.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
    this.icon.iconSize   = new GSize(12, 20);
    this.icon.shadowSize = new GSize(22, 20);
    this.icon.iconAnchor       = new GPoint(6, 20);
    this.icon.infoWindowAnchor = new GPoint(5,  1);

    var options = {title: this.castle.name, icon: this.icon};

    this.point  = new GLatLng(castle.lat, castle.long);
    this.marker = new GMarker(this.point, options);

    map.addOverlay(this.marker);
}

CastleMarker.prototype.destroy = function()
{
    this.map.removeOverlay(this.marker);

    this.marker = null;
    this.point  = null;
    this.icon   = null;

    return null;
}


// ===========================================================================================================
// A container for castle markers. Castle markers could be added to a global castle marker container when
// created so as to provide some simple managment. Calling clobber on the container will cleanly remove all
// markers from the maps, hopefuly.

function CastleMarkerSet()
{
    this.colors  = new Array('red', 'green', 'yellow', 'blue', 'brown', 'purple', 'gray', 'white');
    this.index   = -1;
    this.markers = new Array();
    this.current = null;
}

CastleMarkerSet.prototype.append = function(map, castle)
{
    // Ensure that for the given map, we do not already have this castle and record the splice point so that
    // if we add we keep elements in lat order.

    var idx;

    for(idx=0; idx<this.markers.length; idx++)
    {
        cm = this.markers[idx];

        if(cm.map == map)
        {
            if(cm.castle == castle)
            {
                this.current = cm;
                idx = -1;
                break;
            }
            else if(cm.castle.lat < castle.lat)
            {
                break;
            }
        }
    }

    // Add a new marker if needed.

    if(idx >= 0)
    {
        this.index = (this.index + 1) % this.colors.length;

        this.current = new CastleMarker(map, castle, this.colors[this.index]);

        this.markers.splice(idx, 0, this.current);
    }

    // Return the current marker.

    return this.current;
}

CastleMarkerSet.prototype.clobber = function()
{
    while(this.markers.length)
    {
        this.markers.pop().destroy();
    }

    document.getElementById('googletxt2').innerHTML = '';
}

CastleMarkerSet.prototype.display = function()
{
    var limit = 7;

    // Sort castles into nearest (this a bit poor)

    var data = new Array()

    for(m in this.markers)
    {
        var marker = this.markers[m];

        var dist = LatLon.distHaversine(
                              this.current.castle.lat, this.current.castle.long,
                              marker.castle.lat, marker.castle.long);

        var bear = LatLon.bearing(
                              this.current.castle.lat, this.current.castle.long,
                              marker.castle.lat, marker.castle.long);

        for(var d=0; d<data.length; d++)
        {
            if(dist < data[d].dist)
            {
                break;
            }
        }

        data.splice(d, 0, {marker: marker, dist: dist, bear: bear});
    }

    // Display

    var html = '<p>';

    if(limit > data.length) limit = data.length;

    for(var d=0; d<limit; d++)
    {
        var marker = data[d].marker;
        var dist   = data[d].dist.toFixed(1);
        var bear   = data[d].bear.toFixed(1);

        if(this.current != marker)
        {
            // Hack
            html += '<span class="hov" onclick="update_body(' + marker.castle.index + ')">';
            html += '<img src="' + marker.icon.image + '" /> ';
            html += '<i>' + marker.castle.name + ' : ' + dist + 'km, ' + bear + '°</i>';
            html += '</span>';
        }
        else
        {
            html += '<img src="' + marker.icon.image + '" /> '+ marker.castle.name;
        }

        html += '<br/>';
    }

    return html += '</p>';
}


var globalCastleMarkerSet = new CastleMarkerSet();


// ===========================================================================================================
// Main update function.

function update_body(i)
{
    var castle = global_castle_data[i];

    var cm2 = globalCastleMarkerSet.append(google_map2, castle);

    GEvent.addListener(cm2.marker, "click",

        function()
        {
            google_map1.setCenter(cm2.point, castle.zoom);

            castle_body(castle);

            show_maps(1); // this is a bit iffy
        }
    );

    show_maps(1); // this is a bit iffy

    google_map1.setCenter(cm2.point, castle.zoom);
    google_map2.setCenter(cm2.point, 5);

    castle_body(castle);

    show_maps(1); // this is a bit iffy
}

function show_maps(state)
{
    document.getElementById("hide1").style.display = ((state) ? 'block' : 'none');
    document.getElementById("hide2").style.display = ((state) ? 'block' : 'none');

    if(state == 0) globalCastleMarkerSet.clobber();

    document.getElementById("main").style.backgroundImage = ((state) ? "url(flags/void.gif)" : "url(knight.gif)");

    google_map1.checkResize();
    google_map2.checkResize();
}


