$(document).ready(function () {

	$('#basefont .slider').Slider({
		accept: '.indicator',
		fractions: 8, // Equals 9 actual values
		onSlide: function (x) {
			var old_font_size = parseInt($('#basefontvalue').val());
			$('#basefontvalue').val(parseInt(x / 12.5) + 8); // Divide by (100/fractions) and add an offset
			// Need to recalculate the values of column and gutter width as well
			$('#columnwidthvalue').val((parseInt($('#columnwidthvalue').val()) / old_font_size * parseInt($('#basefontvalue').val())));
			$('#gutterwidthvalue').val((parseInt($('#basefontvalue').val()) * parseInt($('#gutterwidthvalue').val()) / old_font_size));
			recalculateTotalWidth();
		},
		values: [
			[150,0]
		]
	});

	$('#columns .slider').Slider({
		accept: '.indicator',
		fractions: 20, // Equals 11 actual values
		onSlide: function (x) {
			$('#columnsvalue').val(parseInt(x / 5) + 2); // Divide by (100/fractions) and add an offset
			recalculateTotalWidth();
		},
		values: [
			[70,0]
		] 
	});

	$('#columnwidth .slider').Slider({
		accept: '.indicator',
		fractions: 25, // Equals 21 actual values
		onSlide: function (x) {
			$('#columnwidthvalue').val((parseInt(x / 4) + 2) * parseInt($('#basefontvalue').val())); // Divide by (100/fractions) and add an offset
			recalculateTotalWidth();
		},
		values: [
			[110,0]
		]
	});

	$('#gutterwidth .slider').Slider({
		accept: '.indicator',
		fractions: 4, // Equals 5 actual values
		onSlide: function (x) {
			$('#gutterwidthvalue').val((parseInt(x / 25) + 1) * parseInt($('#basefontvalue').val())); // Divide by (100/fractions) and add an offset
			recalculateTotalWidth();
		},
		values: [
			[0,0]
		]
	});
	
	$('div.block input').keyup(function () {
		recalculateTotalWidth();
	});
	
	recalculateTotalWidth();

});

function recalculateTotalWidth() {
	var columnwidth = parseInt($('#columnwidthvalue').val());
	var no_of_columns = parseInt($('#columnsvalue').val());
	var gutterwidth = parseInt($('#gutterwidthvalue').val());
	var total_width_of_columns = columnwidth * no_of_columns;
	var total_width_of_gutters = gutterwidth * (no_of_columns - 1);
	var total_width = total_width_of_columns + total_width_of_gutters;
	if (total_width) {
		$('#totalwidth').html("<span>Total width:</span>" + total_width + "px");
	}
	drawGrid(columnwidth, no_of_columns, gutterwidth);
}

function drawGrid(columnwidth, no_of_columns, gutterwidth) {
	// Set up a string to hold the generated HTML
	var grid = '';
	// Loop through the number of columns
	for (var i=0; i<no_of_columns; i++) {
		// Create a column
		grid += '<div class="column" style="width: ' + columnwidth + 'px;"></div>';
		// If this isn't the last column, add a gutter
		if (i != no_of_columns - 1) {
			grid += '<div class="gutter" style="width: ' + gutterwidth + 'px;"></div>';
		}
	}
	// Inject the HTML into the page
	$('#grid').css('width', (no_of_columns * columnwidth) + ((no_of_columns - 1) * gutterwidth)).html(grid);
}
