jQuery(function( $ )
{
    // when the applet finishes loading, set any attributes to any hash values.
	var $applet = $('#counter');
	
	count = getHash("count");
    if(count == "")
        count = 11;
    
    colour = getHash("colour");
    if(colour == "")
        colour = 0;
        
	//this mode doesn't require any setting, can have though
	$.preload( $applet, {
	    onFinish:function(){
			setColour(colour);
			setCount(count);
		}
	});
});


function incrementIt()
{
    count = document.getElementById("counter").incrementIt();
    setHash("count", count);
}

function decrementIt()
{
    count = document.getElementById("counter").decrementIt();
    setHash("count", count);
}

function setCount(count)
{
    document.getElementById("counter").setCount(count);
    setHash("count", count);
}

function setColour(c)
{
    document.getElementById("counter").setColour(c);
    setHash("colour", c);
}

function toggleBG()
{
    colour = document.getElementById("counter").toggleBG();
    setHash("colour", colour);
}

function setHash(attribute, value)
{
    // go through all the hashes,
    // if one of them matches, we'll have to replace the value, otherwise, leave it.
    
    currentHash = window.location.hash;
    newHashes = attribute + "=" + value;
    
    // if there's already an existing hash attribute and value,
    // replace it
    if (getHash(attribute) != "")
    {
        newHashes = currentHash.replace(attribute + "=" + getHash(attribute), newHashes);
    }
    // otherwise, add it
    else
    {
        if(currentHash == "")
            newHashes = newHashes;
        else
            newHashes = currentHash + "&" + newHashes;
    }
    
    window.location.hash = newHashes;
}

function getHash(attribute)
{
    hash = window.location.hash;
	hashes = hash.replace("#", "").split("&");
	
	for (i = 0 ; i < hashes.length ; i++)
	{
	    hashKeyValue = hashes[i].split("=");
	    
	    if(hashKeyValue[0] == attribute)
	    {
	        return hashKeyValue[1];
        }
    }
    
    return "";
}

function message(message)
{
    mes = document.getElementById("messages");
    mes.innerHTML = message;
}