/*---------------------------------------------------------------- 
 * The JavaScript written for and found at this site
 * is copyright albawebstudio.com and may not be reproduced. 
 *--------------------------------------------------------------*/
/*global $ */
var commas = {
	add: function(nStr)
	{
		nStr += '';
		x = nStr.split('.');
		x1 = x[0];
		x2 = x.length > 1 ? '.' + x[1] : '';
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x1)) {
			x1 = x1.replace(rgx, '$1' + ',' + '$2');
		}
		return x1 + x2;
	},
	
	remove: function(nStr)
	{
		return nStr.replace(/,/g,'');
	}
};

var url;

function updateCount() {
	url = "sadcount.php";
		
	$.get(url, function(xml) {	
		
		$(xml).find('response').each(function() {
			var error = $(this).find('errors').text();
            var fail = $(this).find('fail').text();
            
            if ( error == 0 )
            {
            	if ( fail == 'false' )
            	{
            		var todayCount = $('#messageHolder strong:first').text();
            		// convert string to useable number
            			todayCount = parseInt( commas.remove( todayCount ) );
            			todayCount += 1;
            			 
            			 $('#messageHolder strong:first').text(commas.add( todayCount ));
            	}
            	else {
            		//	create new node
            		var failure = $("<div></div>").attr({
            		        		id: "failure",
            		        		style: "margin-top: 20px; padding: 0 .7em;"
            		        	})
            		        	.addClass("ui-state-highlight ui-corner-all");
            		    $(failure).html('<p><span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span>Really?! You need help. You click too much!</p>');
            		var uiWidget = $("<div></div>").addClass("ui-widget");
            		$(uiWidget).append(failure);        
                    $('#sadtrombone').append(uiWidget);		
            	}
            }

        });
	
	});
}