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');
}
if (undefined == D.racer_name )
{
    D.racer_name = 'Name';
}
if (undefined == D.race_mile_name )
{
    D.race_mile_name = 'Race Mile';
}
if ( undefined == D.show_temp)
{
    D.show_temp = false;
}
if (undefined == D.show_altitude )
{
    D.show_altitude = true;
}
var course_loaded = false;
var clusterOptions = null;
// 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,D.start_tileset,false);
    clusterOptions = new VEClusteringOptions();
    clusterOptions.Callback = ClusteringCallback;
}
var flip_scratch = true;
var flip_finish = true;
function ToggleFinishers()
{
    // You should be reading this //
    jQuery('.show_hide_f_content').toggle();
    jQuery('.show_hide_f').click(function() {
        jQuery('.show_hide_f_content').toggle();
        if (flip_finish) {
            jQuery('.show_hide_f .plusminus').text('[-]');
        } else {
            jQuery('.show_hide_f .plusminus').text('[+]');
        }
        flip_finish = (!(flip_finish));
    } );
}
function ToggleScratchers()
{
    // You should be reading this //
    jQuery('.show_hide_sw_content').toggle();
    jQuery('.show_hide_sw').click(function() {
        jQuery('.show_hide_sw_content').toggle();
        if (flip_scratch) {
            jQuery('.show_hide_sw .plusminus').text('[-]');
        } else {
            jQuery('.show_hide_sw .plusminus').text('[+]');
        }
        flip_scratch = (!(flip_scratch));
    } );
}
function ClusteringCallback(clusters) {
    try {
        if (clusters != null) {
            for (var i = 0; i < clusters.length; i++) {
                var cluster = clusters[i];
                var clusterShape = clusters[i].GetClusterShape();
                clusterShape.SetCustomIcon( 'http://static.ionearth.com/images/mushers_camping.png' );
                var description = "<p>There are several " + D.racer_name +" at this location. Please select one below to see more details.</p>";
                description += '<div class="list_holder"><ul class="tightlist">';
                for (var s = 0; s < cluster.Shapes.length; s++) {
                    var shape = cluster.Shapes[s];

                    description += "<li><a href='javascript:ShowPin(\"" + shape.GetID() + "\")'>" + shape.GetTitle() + "</a>";
                }
                description += '</ul></div>';
                clusterShape.SetDescription(description);
                clusterShape.SetTitle("Select a " + D.racer_name );
            }
        }
    } catch (e) { alert(e.message); }
}
function ShowPin(pinID) {
    var pin = D.Map.GetShapeByID(pinID);
    if (pin != null) {
        D.Map.ShowInfoBox(pin);
    }
}
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 + '/racers2.js?reload=' + new Date().valueOf();
    var racer_url = '/api/2009-02-06/load_race_view/' + _view_id + '/racers2.js?reload=' + new Date().valueOf();
    jQuery.getJSON(racer_url,
        function(data) {
            D.racers = data;
            build_racers_table();
            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)
{
    if (knots > 25)
    {
        return Math.round(knots * 1.15077945,1);
    } else {
        return Math.round(knots * 1.15077945 * 10,1) / 10;
    }
}
function knotsToKPH(knots)
{
    if (knots > 25)
    {
        return Math.round(knots * 1.85200,1);
    } else {
        return Math.round(knots * 1.85200 * 10,1) / 10;
    }
}
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();
        var telem_url = '/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];
                    if (race_telem.rm != 'N/A')
                    {
                        jQuery('.rm' + race_telem.id).text(parseInt(race_telem.rm));
                    } else {
                    }
                    var speed_desc = knotsToMPH(race_telem.spd) + 'mph';
                    jQuery('.spd' + race_telem.id).text( knotsToMPH(race_telem.spd));
                    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;
                                D.racers[y].m = race_telem.m;
                            }
                            try {
                                var elev = 'unkown';
                                if (D.racers[y].m)
                                {
                                    elev = D.racers[y].m;
                                    if (elev > 65500)
                                    {
                                        elev = elev - 65535;
                                    }
                                }
                                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">Miles to Finish:</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>';
                                if ( D.show_altitude )
                                {
                                    desc += '<tr><th align="right">Altitude:</th><td>' + elev + ' meters</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>';
                                if ( D.show_temp )
                                {
                                    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>'; 
                                desc += '<div class="pop_desc">' + D.racers[y].htm + '</div>';
                                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 );
                                    var imgHeading = mod( Math.round( ( 360 + 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';
                                }
                                vec.ImageOffset = new VEPixel( 10,30);
                                s.SetCustomIcon( vec );
                                s.SetDescription( desc );
                                if (race_telem.lat != 0)
                                {
                                    allShapes.push(s);
                                    D.racers[y].shp = s;
                                }
                            } catch (euh) {
                            }
                        }
                    }
                    
                }
                D.racer_layer.DeleteAllShapes();
                D.racer_layer.AddShape( allShapes );
                if (first_map_view)
                {
                    first_map_view = false;
                    D.Map.SetMapView(allShapes);
                    // D.racer_layer.SetClusteringConfiguration(VEClusteringType.Grid, clusterOptions);

                }
                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';
    var checkpoint_url = '/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 zooom(ix)
{
    
    //alert( '  zoom to musher ' + D.racers[ix].n );
    zoomToPoint( D.racers[ix].lat, D.racers[ix].lon );
    setTimeout('showRacerInfoBox(' + ix + ');', 100);
}
function showRacerInfoBox(ix)
{
    D.Map.ShowInfoBox( D.racers[ix].shp );
    updateAge();
    //checkTop();
}
function checkTop()
{
    //alert(jQuery('#content').offset().top);
    //alert(jQuery('#sidebar').offset().top);
}
var i_hate_css = setInterval('stop_doing_that_shit',1000);
function stop_doing_that_shit()
{
    if ((jQuery('#content').offset().top - jQuery('#sidebar').offset().top) > 0)
    {
        // alert('resize boss');
        onPageResize();
    }
}
function build_racers_table()
{
    jQuery('#racer_list').empty();
    jQuery('#racer_list').prepend('<thead><tr><th></th><th>#</th><th>' + D.racer_name + '</th><th>Spd</th><th>'+ D.race_mile_name +'</th><th>Age</th></tr></thead><tbody>');

    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" onmouseover="highlight()" onmouseout="lolight()" onclick="zooom('+ x + ')"><td><input name="show_racers" checked type="checkbox" value="' + D.racers[x].id +'"></td><td align="right">' + D.racers[x].num + '</td><td>' + D.racers[x].n + '</td><td align="right" class="spd' + D.racers[x].id + '">0</td><td align="right" class="rm' + D.racers[x].id + '">0</td><td align="right" class="age' + D.racers[x].id + '"></td></tr>');
    }
    jQuery('#racer_list').append('</tbody>');
    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.6));
            shape.SetLineWidth(1);
            /**
            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 += ' NM';
    }
    // 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 );   
        course_loaded = 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() {
        ToggleFinishers();
        ToggleScratchers();
        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('sorton', [[[4,1]]] );
    jQuery('#racer_list').trigger('update' );
}

function sortRacersTableByRm_then_bib()
{
    jQuery('#racer_list').tablesorter(
        {
            headers:{
                1: { sorter: 'integer' },   // bib number
                2: { sorter: 'text'},       // name
                3: { sorter: 'digit' },     // speed
                4: { sorter: 'integer' },   // distance
                5: { sorter: 'time' }       // age
            },
            // sort by distance and bib number at first
            sortList: [[4,1],[1,0]]
        }
    );
}
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 s3 = setTimeout( 'updateAge()',1000 );
var s2 = setInterval( 'updateAge()',1000 );
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;
}


}
