jQuery.noConflict();
var ie_debug = (document.location.search == '?ryba=true');
if (ie_debug)
{
    jQuery('#page_header').append('<div id="debug"></div>');
    alert('debug mode = on');
}
var course_loaded = false;
// jQuery.getScript('http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2',ve_loaded);
function initMap()
{
    D.Map = new VEMap('content');
    D.Map.onLoadMap = onMapLoaded;
    D.Map.LoadMap( new VELatLong(D.start_lat, D.start_lon),D.start_zoom,VEMapStyle.Shaded,false);
}
function onMapStyleChanged(mapEvt)
{
    if (mapEvt.mapStyle == VEMapStyle.Road)
    {
        D.Map.SetMapStyle(VEMapStyle.Shaded);
    }
}
function onMapLoaded()
{
    if (ie_debug) { alert('map is loaded'); };
    D.racer_layer = new VEShapeLayer();
    // D.racer_layer.SetClusteringConfiguration(VEClusteringType.Grid);
    D.Map.AddShapeLayer(D.racer_layer);
    D.Map.AttachEvent('onchangemapstyle',onMapStyleChanged);
    loadCourse(D.course_url);
}
function goGetElementById( pId )
{
    if ( document.layers )
    {
        return document.layers[pId];
    } else if ( document.all )
    {
        return document.all[pId];
    } else if ( document.getElementById )
    {
        return document.getElementById( pId );
    }
}

function loadRacers()
{
    var racer_url = 'http://race.ionearth.com/api/2009-02-06/load_race_view/' + _view_id + '/racers.js?reload=' + new Date().valueOf();
    jQuery.getJSON(racer_url,
        function(data) {
            D.racers = data;
            show_racers();
            var utct = Math.round(new Date().valueOf()  / 1000,1);
            if ((utct >= D.start_time) && (utct <= D.stop_time))
                setTimeout('get_telemetry()', 2000);
        }
    );
}
D.telem_interval_id  = setInterval('get_telemetry()', 60000);
function getChecked_ids()
{
    output = [];
    jQuery('input[@name="show_racers"][type="checkbox"]').each(function() { if (this.checked) { output.push(this.value); } } );
    output.sort();
    output = output.join('');
    return output;

}
function updateAge()
{
    try {
    var rs = D.racers.length;
    for (var rx = 0; rx < rs; rx++)
    {
        if (D.racers[rx].time)
        {
            var age = (new Date().valueOf() / 1000 ) - D.racers[rx].time ;
            jQuery('.age' + D.racers[rx].id).text( sa( age ) );
        }
    }
    } catch (eua) {
    }
}
function knotsToMPH(knots)
{
    return Math.round(knots * 1.15077945,1);
}
function knotsToKPH(knots)
{
    return Math.round(knots * 1.85200,1);
}
var rose = ['N','NE','E','SE','S','SW','W','NW'];
function formatHeading( degrees )
{
    var seg = 360/rose.length;
    var deg = degrees + seg/2;
    var deg360 = Mod(deg,360);
    var dir = deg360 / seg;
    dir = Math.round(dir-0.5,0);
    return rose[dir];
};
function Mod(X, Y) {
    return X - Math.floor(X / Y) * Y;
}

function mod(X, Y) {
    var t;
    t = X % Y;
    return t < 0 ? t + Y : t;
}
function C2F( tempC )
{
    return Math.round((212 - 32) / 100 * tempC + 32, 2);
}

function get_telemetry()
{
    var utct = Math.round(new Date().valueOf()  / 1000,1);
    if ((utct < D.start_time) || (utct >= D.stop_time))
    {
        clearInterval(D.telem_interval_id);
    }

    idlist = getChecked_ids();
    if (idlist != '')
    {
        var telem_url = 'http://race.ionearth.com/api/2009-02-06/telem/' + _view_id + '/' + idlist + '.js?reload=' + new Date().valueOf();
        jQuery.getJSON(telem_url,
            function(data) {
                ds = data.length;
                var allShapes = [];
                for (x = 0; x < ds; x++)
                {
                    race_telem = data[x];
                    jQuery('.rm' + race_telem.id).text(race_telem.rm);
                    var found = false;
                    var rix = 0;
                    for (y = 0; y < D.racers.length && ! found; y++)
                    {
                        rix = y;
                        if (D.racers[y].id == race_telem.id)
                        {
                            found = true;
                            D.racers[y].time = race_telem.t;
                            if (race_telem.lat != 0)
                            { 
                                D.racers[y].lat = race_telem.lat;
                                D.racers[y].lon = race_telem.lon;
                                D.racers[y].rm = race_telem.rm;
                                D.racers[y].spd = race_telem.spd;
                                D.racers[y].hd = race_telem.hd;
                            }
                            try {
                                var p = new VELatLong(D.racers[y].lat, D.racers[y].lon);
                                var s = new VEShape(VEShapeType.Pushpin,p);
                                var vec = new VECustomIconSpecification();
                                s.SetTitle( '#' + D.racers[y].num + ' ' + D.racers[y].n );
                                var desc = '<table>';
                                desc += '<tr><th align="right">Race Mile:</th><td class="rm' + race_telem.id + '">' + D.racers[y].rm + '</td></tr>';
                                desc += '<tr><th align="right">Latitude:</th><td>' + getLatitudeInDecimalMinutes(D.racers[y].lat) + '</td></tr>';
                                desc += '<tr><th align="right">Longitude:</th><td>' + getLongitudeInDecimalMinutes(D.racers[y].lon) + '</td></tr>';
                                desc += '<tr><th align="right">Speed:</th><td>' + knotsToMPH(D.racers[y].spd) + 'MPH / ' + knotsToKPH(D.racers[y].spd) + 'KPH</td></tr>';
                                desc += '<tr><th align="right">Heading</th><td>' +  D.racers[y].hd + '&deg; ' + formatHeading(  D.racers[y].hd ) + '</td></tr>';
                                desc += '<tr><th align="right">Temperature</th><td>' + C2F( race_telem.c) + '&deg;F / ' + race_telem.c  + '&deg;C</td></tr>';

                                desc += '<tr><th align="right">Time since Report:</th><td class="age' + race_telem.id + '"></td></tr>';
                                desc += '<tr><th align="right">Status:</th><td>' + race_telem.st + '</td></tr>';


                                desc += '</table>'; 
                                if (D.racers[y].rot == 'False')
                                {
                                    vec.Image = D.racers[y].i;
                                } else {
                                    var imgHeading = mod( Math.round( ( 360 + -1 * D.racers[y].hd ) / 10 ) * 10, 360 );
                                    imgHeading = imgHeading.toString();
                                    while (imgHeading.length < 3)
                                    {
                                        imgHeading = '0' + imgHeading;
                                    }
                                    vec.Image = D.racers[y].i + imgHeading + '.png';
                                }
                                s.SetCustomIcon( vec );
                                s.SetDescription( desc );
                                if (race_telem.lat != 0)
                                    allShapes.push(s);
                            } catch (euh) {
                            }
                        }
                    }
                    
                }
                D.racer_layer.DeleteAllShapes();
                D.racer_layer.AddShape( allShapes );
                if (first_map_view)
                {
                    first_map_view = false;
                    D.Map.SetMapView(allShapes);
                }
                resort_table();
            }
        );
    }
}
var first_map_view = true;
function repositionRacers()
{
    var ds = D.racers.length;
    for (var rx = 0; rx < ds; rx++)
    {
    }
}
function loadCheckpoints()
{
    var checkpoint_url = 'http://race.ionearth.com/api/2009-02-06/load_race_view/' + _view_id + '/checkpoints.js';
    jQuery.getJSON(checkpoint_url,
        function(data) {
            D.checkpoints = data;
            show_checkpoints();
        }
    );

}
function sortOrder(a,b)
{
    try { return a._order_by - b._order_by; } catch(e) { };
}
function highlight()
{
    this.lastclass = this.className;
    this.className = "hirow";
}
function lolight()
{
    this.className = this.lastclass;
}
function zoomToCheckpoint()
{
    zoomToPoint(this.lat,this.lon);
}
function onCheckpointClicked(cp_id)
{
    zoomToPoint(D.checkpoints[cp_id].Latitude,D.checkpoints[cp_id].Longitude);
    D.Map.ShowInfoBox(D.checkpoints[cp_id]);
}
function zoomToPoint(lat,lon)
{
    if (D.Map)
    {
        if (D.Map.SetCenterAndZoom)
        {
            D.Map.SetCenterAndZoom(new VELatLong(lat,lon),13);
        }
    }
}
var racer_table_created = false;
function createRacerTable()
{
    if (racer_table_created)
    {
        return false;
    }
    racer_table_created = true;
    if (D.racers.length > 0 )
    {
        D.racers.sort(raceMile);
    }
}
var checkpoint_table_created = false;
function createCheckpointTable()
{   
    if (checkpoint_table_created) 
    {
        return false;
    }
    checkpoint_table_created = true;
    if (D.checkpoints.length>0)
    {
        D.checkpoints.sort(sortOrder);
        var t = goGetElementById('checkpoint_table');
        t.deleteRow(2);
        var styles = ['evenrow','oddrow'];
        var stylecount = styles.length;
        var rowcount = 0;
        for(x=0;x<D.checkpoints.length;x++)
        {
            rowcount += 1;
            var shp = D.checkpoints[x];
            // console.log(shp._order_by + ':' + shp.Title + ' ' + shp.GetPoints()[0].Latitude + ', ' + shp.GetPoints()[0].Longitude );
            var tr = t.insertRow(-1);
            var lat = shp.Latitude;
            var lon = shp.Longitude;
            var style = styles[rowcount % stylecount];
            tr.className = style;
            tr.lat = lat;
            tr.lon = lon;
            var td_name = document.createElement('td');
            var a_name = document.createElement('a');
            var txt_name = document.createTextNode(shp.Title);
            a_name.href="#";
            // a_name.href='javascript:zoomToPoint('+lat+','+lon+')';
            a_name.href='javascript:onCheckpointClicked(' + x + ')';
            //a_name.setAttribute('onClick','return D.Map.SetCenterAndZoom(new VELatLong(' + lat + ','+lon+'),11);');
            //a_name.href='javascript:l=D.Map.SetCenterAndZoom(new VELatLong(' + lat + ','+lon+'),11);#;';
            tr.onmouseover = highlight;
            tr.onmouseout = lolight;
            tr.onmousedown = zoomToCheckpoint;

            //tr.setAttribute('onmouseover', 'this.className="hirow";');
            //tr.setAttribute('onmouseout', 'this.className="'+style+'";');
            td_name.id =  "checkpoint" + x  + "name";
            a_name.appendChild(txt_name);
            td_name.appendChild(a_name);
            tr.appendChild(td_name);

            var td_rm = document.createElement('td');
            var txt_rm = document.createTextNode(shp._mileage);
            td_rm.setAttribute('align','right');
            td_rm.appendChild(txt_rm);
            tr.appendChild(td_rm);

            if ("1" == shp._order_by)
            {
                // Add blank row
                rowcount += 1;
                tr = t.insertRow(-1);
                var td1 = document.createElement('td');
                var txt1 = document.createTextNode('\u00a0');
                var td2 = document.createElement('td');
                var txt2 = document.createTextNode('\u00a0');
                style = styles[rowcount % stylecount];
                tr.className = style;
                tr.onmouseover = highlight;
                tr.onmouseout = lolight;
                td1.appendChild(txt1);
                td2.appendChild(txt2);
                tr.appendChild(td1);
                tr.appendChild(td2);

            }

            // r.innerHTML = '<td><a href="#" onclick="return D.Map.PanToLatLong(new VELatLong(' + lat + ','+ lon + '));">' + shp.Title + '</a></td>';
        }
    }
}

function show_checkpoints()
{
    jQuery('#checkpoint_list').empty();
    c = D.checkpoints.length;
    for (x = 0; x < c; x++)
    {
        jQuery('#checkpoint_list').append('<li><input type="checkbox" id="'+ D.checkpoints[x].id +'">' + D.checkpoints[x].n + '</li>');
    }
}

function show_racers()
{
    jQuery('#racer_list').empty();
    jQuery('#racer_list').append('<thead><tr><th></th><th>#</th><th>Musher</th><th>Age</th><th>RM</th></tr></thead>');

    c = D.racers.length;
    for (x = 0; x < c; x++)
    {
        //jQuery('#racer_list').append('<li><input type="checkbox" class="select_racer" id="select_racer_' + D.racers[x].id + '">' + D.racers[x].n + '</li>');
        jQuery('#racer_list').append('<tr class="racer_row"><td><input name="show_racers" checked type="checkbox" value="' + D.racers[x].id +'"></td><td>'+ D.racers[x].num+'</td><td>' + D.racers[x].n + '</td><td class="age' + D.racers[x].id + '">00:00</td><td class="rm' + D.racers[x].id + '">0</td></tr>');
    }
    sortRacersTableByRm_then_bib();
}
function getLatitudeInDecimalMinutes(degree)
{
    var direction = 'N';
    if (degree < 0)
       {
        direction = 'S';
        degree = degree * -1;
        }
    var deg = Math.round(degree - 0.5);
    var min = (degree - deg) * 60;
        min = Math.round( min * 1000 ) / 1000;
    var result = direction + ' ' + deg + '&deg;' + min + "'";
    return result;
}
function getLongitudeInDecimalMinutes(degree)
{
    var direction = 'E';
    if (degree < 0)
       {
        direction = 'W';
        degree = degree * -1;
        }
    var deg = Math.round(degree - 0.5);
    var min = (degree - deg) * 60;
        min = Math.round( min * 1000 ) / 1000;
    var result = direction + ' ' + deg + '&deg;' + min + "'";
    return result;
}

function onCourseLoaded( rssLayer )
{
    if (ie_debug)
    {
        jQuery('#page_header').append('course is loaded');
    }
    var numShapes = rssLayer.GetShapeCount();
    var courseLayer = rssLayer;
    var minLat = 90;
    var minLon = 180;
    var maxLat = -90;
    var maxLon = -180;
    var lat = 0;
    var lon = 0;
    for ( var ixs = 0; ixs < numShapes; ixs++ )
    {
        var shape = rssLayer.GetShapeByIndex( ixs );

        pt =shape.GetPoints();
        pointCount = pt.length;
        if ( pointCount > 1 )
        {
            // this is a line
            shape.HideIcon();
            shape.SetLineColor(new VEColor(255, 0, 0, 0.8));
            shape.SetLineWidth(3);
            for ( var pix = 0; pix < pointCount; pix++)
            {
                lat = pt[pix].Latitude;
                lon = pt[pix].Longitude;
                if ( minLat > lat ) minLat = lat;
                if ( minLon > lon ) minLon = lon;
                if ( maxLat < lat ) maxLat = lat;
                if ( maxLon < lon ) maxLon = lon;
            }
        } else {
            updateCheckpoint(shape);
        }
    }
    createCheckpointTable();
    // console.log( 'min = ' + minLat );
    D.boundaryPoints = [
        new VELatLong( minLat, minLon ),
        new VELatLong( maxLat, maxLon )
    ];
    D.Map.SetMapView( D.boundaryPoints );
}
function updateCheckpoint(shape)
{
    // Set the correct image for this icon instead of pushpin icon
    var vec = new VECustomIconSpecification();
    vec.Image = D.checkpoint_image;
    //vec.ImageOffset = offset;
    var titleRay = shape.Title.split('|');
    var order = titleRay[0];
    var mileage = titleRay[1];
    var title = titleRay[2];
    shape.Title = title;
    var distance = mileage;
    if (distance != '')
    {
        distance += ' Mi';
    }
    // shape.Notes = latlonString + shape.Notes;
    var latlonString = '<div><style type="text/css">th { text-align: right; }; </style>'
    latlonString += '<table><tr><th>Course Distance</th><td>' + distance + '</td></tr>';
    latlonString += '<tr><th>Latitude</th><td>' + getLatitudeInDecimalMinutes(pt[0].Latitude) + '</td></tr>';
    latlonString += '<tr><th>Longitude</th><td>' + getLongitudeInDecimalMinutes(pt[0].Longitude) + '</td></tr>';
    latlonString += '</table>';
    latlonString += '<p class="checkpoint_desc">' + shape.Notes + '</p>'
    latlonString += '</div>'
    shape.Notes = latlonString;
    shape._order_by = order;
    shape._mileage = mileage;
    vec.TextContent = ' ';

    shape.SetCustomIcon(vec);

    // Store this checkpoint
    D.checkpoints.push(shape);
}


function loadCourse()
{
    if (!course_loaded)
    {
        loadRssLayer( D.course_url, onCourseLoaded, true );   
    }
}

function loadRssLayer( feedURL, callBack, stayVisible )
{
    if ( null == stayVisible ) stayVisible = false;
    var rssLayer = new VEShapeLayer();
    feedURL += '?' + new Date().valueOf();
    var layerData = new VEShapeSourceSpecification( VEDataType.GeoRSS, feedURL, rssLayer );
    D.Map.ImportShapeLayerData( layerData, callBack, stayVisible );
}

function setupSidebarController()
{
    jQuery('#sidebar_mode').css('width',99);
    jQuery('#sidebar_mode').css('height',29);
    jQuery('#sidebar_mode').css('background-url','/images/sidebar_mode.png');
}

jQuery(document).ready(
    function() {
        jQuery('#race_tabs').tabs();
        try {
            var now = new Date().valueOf();
            var ticks = 1235847600 - Math.round(now / 1000);
            jQuery('#countdown').countdown(
                {alwaysExpire: true, onExpiry: function() { jQuery('#countdown').hide(); }, until: '+' + ticks.toString() + 's', description: 'Time until Start'}
            );

        } catch(e) {
        }

        initMap();
        loadRacers();
        loadCourse();
    }
);

function resort_table()
{
    jQuery('#racer_list').trigger('update');
}

function sortRacersTableByRm_then_bib()
{
    try {

        jQuery('#racer_list').tablesorter(
            {
                headers:{
                1: { sorter: 'integer' },   // bib number
                2: { sorter: 'text'},       // name
                3: { sorter: 'time' },     // age
                4: { sorter: 'integer' }   // distance
            },

                sortList: [[1,0]],
                sortForce: [[4,1]]
            }
        );
    } catch (tex) {
    }
}
function updateRaceTime()
{
    var d = new Date();
    var local_utc_off = d.getTimezoneOffset();
    var race_utc_off = D.race_utc_minutes_offset; // 540;
    var race_tz_string = D.race_timezone_name;  // 'AK/HST'
    var race_time = new Date( d.valueOf() + (local_utc_off - race_utc_off) * 60 * 1000 );
    jQuery('#ltime').text( dateFormat( d, "mmm dd h:MM:ss TT Z" ) );
    jQuery('#rtime').text( dateFormat( race_time, "mmm dd h:MM:ss TT" ) + " " + race_tz_string );
    updateAge()
}
var s = setInterval('updateRaceTime()', 1000);
function sa(s){
s = Math.floor(s,1);
p = {};
var times = [{'a':2073600,'b':'w'},{'a':86400,'b':'d'},{'a':3600,'b':'h'},{'a':60,'b':'m'}];
var o = '';  var lc = 0; 
for (x=0;x<times.length;x++){ 
    v=times[x]['a'];
    if (s >= v) { 
        var y = times[x]['b'];
        var t = Math.floor(s/v,1);
        s -= t * v;
        o += t.toString() + y + ' ';
        lc += 1;
        p[y] = t;
    } else {
        p[times[x]['b']] = 0;
    }
}
p['s'] = s;
var h = p['h'];
if (h < 10) h = '0' + h.toString();
var m = p['m'];
if (m < 10) m = '0' + m.toString();
var s = p['s'];
if (s < 10) s = '0' + s.toString();
if (h == '00') 
{
    return m + ':' + s;
} else {
    return h + ':' + m + ':' + s;
}

}
