/**
 * Set the window background to a specific texture
 */
function set_background(bg) {
	var images, imagename;

	images = {
		0: 'bricktile_small.jpg',
		1: 'tileconcrete.jpg',
		2: 'tileasphalt.jpg',
		3: 'tileplaster.jpg'
	};

	imagename = images[bg];

	if (!imagename) {
		imagename = images[BACKGROUND_PLASTER];
	}

	$('body').css('background-image', 'url("images/' + imagename + '")');

	modify_selflinks('bg', bg);
}

/**
 * Choose the graffiti color
 */
function set_grafcolor(color) {
	// find all graffiti images, and modify the path to the new color
	var r = new RegExp(".*_web_");
	var url;

	$('img.grafwebimg').each(function() {
		url = $(this).attr('src');
		url = r.exec(url) + color + ".png";
		$(this).attr('src', url);
	});

	modify_selflinks('r', color);
}

/**
 * Find all the selflinks, and modify the GET string
 */
function modify_selflinks(key, val) {
	var url;
	var r = new RegExp(key + "=" + "[^&#]*");
	var hashindex;

	$('a.selflink').each(function(e) {
		url = $(this).attr('href');
		hashindex = url.indexOf("#");

		if (hashindex != -1) {
			posthash = url.substring(hashindex);
			url = url.substring(0, hashindex);
		} else {
			posthash = '';
		}

		if (r.test(url)) {
			url = url.replace(r, key + "=" + val);
		} else {
			if (url.indexOf("?") != -1) {
				url += "&" + key + "=" + val;
			} else {
				url += "?" + key + "=" + val;
			}
		}
		$(this).attr('href', url + posthash);
	});
}

/**
 * On load functionality
 */
$(function() {

	// set up the bg changer:
	$('#bgselector').change(function(e) {
		var val = $('#bgselector option:selected').val();
		if (val >= 0) {
			set_background(val);
		}
	});
	$('#bgselector').change(); // force update

	// set up the color changer:
	$('#colorselector').change(function(e) {
		var val = $('#colorselector option:selected').val();
		if (val != 'none') {
			set_grafcolor(val);
		}
	});
	$('#colorselector').change(); // force update

	$('.backbutton').click(function(e) {
		history.go(-1);
		return false;
	});
});

