﻿$( document ).ready( function () {
    function latestBranch() {
        $.getJSON( "/Home/LatestInformation", null, function ( html ) {
            var showHideSpeed = 1000;

            var firstLI = $( "#recentBranches ul li" ).first();
            var metricWristbands = $( "#metric_TotalWristband" );
            var metricCountries = $( "#metric_TotalCountriesIn" );
            var metricUsers = $( "#metric_TotalRegisteredUsers" );
            var metricTotalClaims = $( "#metric_TotalClaims" );
            var metricClaimsToday = $( "#metric_TotalClaimsToday" );
            var metricTotalPayforwards = $( ".metric_TotalPayforwards" );

            if ( cleanupCompare( firstLI, html.MostRecentBranchText ) ) {
                firstLI.before( '<li>' + html.MostRecentBranchText + '</li>' );
                $( "#recentBranches ul li" ).first().hide().show( showHideSpeed );
                if ( $( "#recentBranches ul li" ).length >= 6 ) {
                    $( "#recentBranches ul li" ).last().hide( showHideSpeed,
                            function () {
                                $( "#recentBranches ul li" ).last().remove();
                            } );
                }
            }

            updateIfNew( metricWristbands, html.TotalWristbands );
            updateIfNew( metricCountries, html.TotalCountriesIn );
            updateIfNew( metricUsers, html.TotalRegisteredUsers );
            updateIfNew( metricTotalClaims, html.TotalClaimsInSystem );
            updateIfNew( metricClaimsToday, html.TotalClaimsToday );
            updateIfNew( metricTotalPayforwards, html.TotalPayforwards );
        } );
    };

    function updateIfNew( currentElement, updatedContent ) {
        if ( cleanupCompare( currentElement, updatedContent ) ) {
            currentElement.text( updatedContent );
            currentElement.show();
        }
    }

    function cleanupCompare( currentElement, updatedString ) {
        if ( currentElement.toArray()[0] != null ) {
            return $.trim( currentElement.toArray()[0].innerHTML.toLowerCase().replace( /(\r\n|\n|\r| )/gm, '' ) ) != updatedString.toString().toLowerCase().replace( /(\r\n|\n|\r| )/g, '' );
        }
        return true;
    }

    setInterval( latestBranch, 5000 );
} );
