function makeJSElementsVisible() {
	// Make the elements which rely on javascript visible
	// (No point having them around if JS isn't enabled)
	document.getElementById('openPicker').style.visibility = "visible";
	document.getElementById('rightsidecircles').style.visibility = "visible";
	document.getElementById('rightsideimage').style.visibility = "visible";
	return (true);
}

/**
 * A class to parse color values
 * @author Stoyan Stefanov <sstoo@gmail.com>
 * @link   http://www.phpied.com/rgb-color-parser-in-javascript/
 * @license Use it if you like it
 */
/**
 * Hacked around by Oliver Humpage to strip out the bits he didn't need.
 * Don't copy this from here, go get the original!
*/
function RGBColor(color_string)
{
    this.ok = false;

    // strip any leading #
    if (color_string.charAt(0) == '#') { // remove # if any
        color_string = color_string.substr(1,6);
    }

    color_string = color_string.replace(/ /g,'');
    color_string = color_string.toLowerCase();


    // array of color definition objects
    var color_defs = [
        {
            re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,
            example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'],
            process: function (bits){
                return [
                    parseInt(bits[1]),
                    parseInt(bits[2]),
                    parseInt(bits[3])
                ];
            }
        },
        {
            re: /^(\w{2})(\w{2})(\w{2})$/,
            example: ['#00ff00', '336699'],
            process: function (bits){
                return [
                    parseInt(bits[1], 16),
                    parseInt(bits[2], 16),
                    parseInt(bits[3], 16)
                ];
            }
        },
        {
            re: /^(\w{1})(\w{1})(\w{1})$/,
            example: ['#fb0', 'f0f'],
            process: function (bits){
                return [
                    parseInt(bits[1] + bits[1], 16),
                    parseInt(bits[2] + bits[2], 16),
                    parseInt(bits[3] + bits[3], 16)
                ];
            }
        }
    ];

    // search through the definitions to find a match
    for (var i = 0; i < color_defs.length; i++) {
        var re = color_defs[i].re;
        var processor = color_defs[i].process;
        var bits = re.exec(color_string);
        if (bits) {
            channels = processor(bits);
            this.r = channels[0];
            this.g = channels[1];
            this.b = channels[2];
            this.ok = true;
        }

    }

    // validate/cleanup values
    this.r = (this.r < 0 || isNaN(this.r)) ? 0 : ((this.r > 255) ? 255 : this.r);
    this.g = (this.g < 0 || isNaN(this.g)) ? 0 : ((this.g > 255) ? 255 : this.g);
    this.b = (this.b < 0 || isNaN(this.b)) ? 0 : ((this.b > 255) ? 255 : this.b);

    // some getters
    this.toRGB = function () {
        return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')';
    }
    this.toHex = function () {
        var r = this.r.toString(16);
        var g = this.g.toString(16);
        var b = this.b.toString(16);
        if (r.length == 1) r = '0' + r;
        if (g.length == 1) g = '0' + g;
        if (b.length == 1) b = '0' + b;
        return '#' + r + g + b;
    }
}



/* 
 * Main colour and images section... 
 */


function colourImagesOnLoad() {

	var colourRaw = getCookie("imageColour");
/*
	// Cookie can be stored as "#nnnnnn" or "rgb(dd, dd, dd)", depending on browser:
	if (colourRaw && colourRaw.match(/^rgb\(\d+, ?\d+, ?\d+\)/)) {
		var colours = new RegExp(/^rgb\((\d+), ?(\d+), ?(\d+)/).exec(colourRaw);
		colour = "#"+parseInt(colours[1]).toString(16)+parseInt(colours[2]).toString(16)+parseInt(colours[3]).toString(16);
		//alert(colour+": "+parseInt(colours[1]).toString(16)+" "+colours[2]+" "+colours[3]);
	}
	else if (colourRaw && colourRaw.match(/^#[0-9a-f]{6}$/i)) {
		colour = colourRaw;
	}
*/
	if (colourRaw && colourRaw.match(/^#[0-9a-f]{6}$/i)) {
		colour = colourRaw;
	}
	else {
		colourCurrent = new RGBColor(document.getElementById('top-image-bg').style.backgroundColor);
		colour=colourCurrent.toHex()
	}

	if (myColourPicker) {
		myColourPicker.setColor(colour);
	}

	colourImages(colour);
}

function colourImages(colour) {

	//colour = document.getElementById('colourForm').value;

	colour = colour || "#000000";

	document.getElementById('top-image-bg').style.background = colour;
	document.getElementById('footer-left-bg').style.background = colour;
	document.getElementById('footer-right-bg').style.background = colour;

	return true;

	red = parseInt(colour.substring(0,2),16);
	green = parseInt(colour.substring(2,4),16);
	blue = parseInt(colour.substring(4,6),16);

	luminosity = (Math.max(Math.max(red, green), Math.max(red, blue)) + Math.min(Math.min(red, green), Math.min(red, blue)) ) / (2 * 255);

	document.getElementById('luminosity').innerHTML = red+" "+green+" "+blue+" "+luminosity;

	

}

function saveColour(random) {
	// Set a cookie to remember (lasts a year):
	var today = new Date();
	today.setTime( today.getTime() );
	var expires_date = new Date( today.getTime() + (365*1000*60*60*24) );
	if (random == 0) {
		// Use the rgbcolor.js class:
		cookieColour = new RGBColor(document.getElementById('top-image-bg').style.backgroundColor);
		colour = escape(cookieColour.toHex());
	}
	else {
		colour = "random";
		var randomcolour = "#"+Math.ceil(Math.random()*7);
		randomcolour += ""+Math.ceil(Math.random()*9);
		randomcolour += ""+Math.ceil(Math.random()*7);
		randomcolour += ""+Math.ceil(Math.random()*9);
		randomcolour += ""+Math.ceil(Math.random()*7);
		randomcolour += ""+Math.ceil(Math.random()*9);
		colourImages(randomcolour);
		if (myColourPicker) {
			myColourPicker.setColor(randomcolour);
		}
	}
	document.cookie = "imageColour" + "=" + colour + ";expires=" + expires_date.toGMTString() + ";path=/";
	var colourRaw = getCookie("imageColour");
	togglePicker(0);
	return(false);
}

function togglePicker(toggle) {
	var onOff = new Array;
	onOff[0] = "none";
	onOff[1] = "block";

	document.getElementById("openPicker").style.display = onOff[1-toggle];
	document.getElementById("colourPicker").style.display = onOff[toggle];
	document.getElementById("closePicker").style.display = onOff[toggle];

	return(false);
}

function getCookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return false;
	}
}

var rightImageCookie = getCookie("rightImage")
if (rightImageCookie) {
	rightImageOrig = rightImageCookie;
}

function showRightImage(file) {
	if (file == "orig") {
		file = rightImageOrig;
	}
	else {
		// Let IE cache the damn thing...
		document.getElementById("iecache-"+file).src = "/interface/images/frontpage/"+file;
	}
	if (document.getElementById("rightsidecircle-"+file)) {
		document.getElementById("rightsidecircle-"+file).src="/interface/images/circle-highlighted.gif"
	}
	rightImageCopyright(file, "show");
	document.getElementById("rightsideimage").src = "/interface/images/frontpage/"+file;
	// Make sure the right circle is highlighted (only really used onLoad, to be fair):
	if (document.getElementById("rightsidecircle-"+rightImageOrig)) {
		document.getElementById("rightsidecircle-"+rightImageOrig).src="/interface/images/circle-highlighted.gif"
	}
	return(false);
}
function revertRightImage(file) {
		document.getElementById("rightsideimage").src = "/interface/images/frontpage/"+rightImageOrig;
		if (rightImageOrig != file) {
			document.getElementById("rightsidecircle-"+file).src="/interface/images/circle.gif"
		}
		rightImageCopyright(file, "revert");
		return(false);
}

var imageCredits = new Object;
imageCredits['bittern.jpg'] = 'Bittern image courtesy of <a href="http://www.mikelangman.co.uk">Mike Langman</a> &amp; the <a href="http://www.rspb.org.uk">RSPB</a>';
imageCredits['pomegranite.jpg'] = 'Pomegranate image courtesy of <a href="http://www.Cheerupcherup.etsy.com">Alaina Cherup</a>';
imageCredits['woodenman.jpg'] = 'Wooden man image courtesy of <a href="http://www.sxc.hu/profile/float">Dora Mitsonia</a>';
imageCredits['geometry.jpg'] = 'Goldsmith tools image courtesy of <a href="http://www.100magenta.com/">Iliana</a>';
imageCredits['colouredmask.jpg'] = 'Mexican mask image courtesy of <a href="http://www.garrisonphoto.org/">Benjamin Earwicker</a>';
imageCredits['bigcog.jpg'] = 'Cog image courtesy of <a href="http://www.sxc.hu/profile/kavitha">Kalyana Sundaram</a>';
imageCredits['keybunch.jpg'] = 'Key image courtesy of <a href="http://www.sxc.hu/profile/scol22">scoll22</a>';
imageCredits['greensweets.jpg'] = 'Sweets image courtesy of <a href="http://www.gracedesign.nl">Cecile Graat</a>';
imageCredits['watchinnards.jpg'] = 'Watch mechanism image courtesy of <a href="http://www.sxc.hu/profile/mariuseek">Marius B</a>';
imageCredits['handingflowers.jpg'] = 'Flowers image courtesy of <a href="http://www.uilenbroek.com/">Maarten Uilenbroek</a>';
imageCredits['streetlamp.jpg'] = 'Streetlamp image courtesy of <a href="http://www.sxc.hu/profile/mzacha">Michal Zacharzewski</a>';
imageCredits['abstractrainbow.jpg'] = 'Abstract image tweaked from an original by <a href="http://www.sxc.hu/profile/sundstrom">Lars Sundstr&ouml;m</a>';
imageCredits['ducks.jpg'] = 'Ducks image courtesy of <a href="http://www.flickr.com/photos/craigjewell/">Craig Jewell</a>';
imageCredits['limes.jpg'] = 'Limes image courtesy of <a href="http://www.flickr.com/photos/craigjewell/">Craig Jewell</a>';
imageCredits['blackbird.jpg'] = 'Bird image courtesy of <a href="http://www.sxc.hu/profile/lizerixt">Lize Rixt</a>';

function rightImageCopyright(file, action) {
	creditdiv = document.getElementById('rightsideimagecredit');
	if (action!= "show" && imageCredits[rightImageOrig]) {
		creditdiv.innerHTML = imageCredits[rightImageOrig];
	}
	else if (action != "revert" && file && imageCredits[file]) {
		creditdiv.innerHTML = imageCredits[file];
	}
	else {
		creditdiv.innerHTML = "&nbsp;";
	}
}


function saveRightImage(file) {
	// Make sure the old circle is unhighlighted:
	if (document.getElementById("rightsidecircle-"+rightImageOrig)) {
		document.getElementById("rightsidecircle-"+rightImageOrig).src="/interface/images/circle.gif"
	}
	rightImageOrig = file;
	// Make sure the new circle is highlighted:
	if (document.getElementById("rightsidecircle-"+rightImageOrig)) {
		document.getElementById("rightsidecircle-"+rightImageOrig).src="/interface/images/circle-highlighted.gif"
	}
	// Set a cookie to remember (lasts a year):
	var today = new Date();
	today.setTime( today.getTime() );
	var expires_date = new Date( today.getTime() + (365*1000*60*60*24) );
	document.cookie = "rightImage" + "=" + escape(rightImageOrig) + ";expires=" + expires_date.toGMTString() + ";path=/";
	return(false);
}


var myColourPicker = "";

$(document).ready(function() {
	myColourPicker = $.farbtastic('#colourPicker',colourImages);
});
