var timer;
var currTimestamp = new Date();
var total = 0.00;
var increment = 0.00;
var timestamp;
var timeDiff;
var rand = 1000;

function startIt()
{
    if (window.XMLHttpRequest)
       {// code for IE7+, Firefox, Chrome, Opera, Safari
       xmlhttp=new XMLHttpRequest();
       }
     else
       {// code for IE6, IE5
       xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
       }
     xmlhttp.open("GET","/scripts/CASHBACK_CLOCK.JSON",false);
	 xmlhttp.setRequestHeader("Cache-Control", "no-cache");

     xmlhttp.send();
     if(xmlhttp.status == 200) {
        var jsondata = eval('(' + xmlhttp.responseText + ')'); //retrieve result as a JavaScript object
        //alert(jsondata);return false;
        total = parseFloat(jsondata.total);
        increment = parseFloat(jsondata.increment).toFixed(2);
        timestamp = new Date(jsondata.timestamp.replace(/\-/g, "/"));
        //alert(timestamp); return false;

        timeDiff = (currTimestamp - timestamp)/1000;

        total += (increment * (timeDiff));
        timedCount();
     }
}

function timedCount()
{
    total += (increment * (rand/1000));

    var total2 = Math.round(total) + "";
    //var total4 = addCommas(total2);

    //replaceValues(total2);
	for (x = 0; x < 9; x++) {
		document.getElementById("counter_" + x).innerHTML = total2.charAt(x); 
	}
	
    var min = 0.5;
    var max = 2;
    rand = Math.floor(1000*((min + Math.random()) * (max-min)));
    timer = setTimeout("timedCount()",rand);
}

function addCommas(nStr)
{
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;

    while (rgx.test(x1))
    {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }

    return x1 + x2;
}

function replaceValues(total)
{
	alert(total);
    //document.getElementById('total').innerHTML = total;
	// add individual numbers to elements on page so they can be positioned on artwork properly
	for (x = 0; x < 9; x++) {
		document.getElementById("counter_" + x).innerHTML = total.charAt(x); 
	}
}
