$(document).ready(function() {

// User data
	var numSwatches = 36; // How many swatches in palette?
	var numSwatchRows = 6; // How many rows of swatches?
	
// Gather some more data
	var numSwatchCols = numSwatches / numSwatchRows; // Just so you don't have to think about it
	var swatchWidth = $('.pPixel').width();
	var swatchHeight = $('.pPixel').height();
	
// create pixels

	for(i=1;i<960;i++) {
		$('#pixels').append('<div class="pixel"></div>');
	}
	
	var count = 0;
	$('.pixel').each(function() {
		count++;
		$(this).attr('id','pixel-'+count);
	});
	
// create palette

	var r=0;
	var rI=0;
	var g=0;
	var gI=0;
	var b=0;
	var bI=0;
	
	var currColor;
	
	function incR() {
		r = r+51;
	}
	function incG() {
		g = g+51;
	}
	function incB() {
		b = b+51;
	}
	
	function incColor() {
		if(bI<3) { // is b done incrementing?
			if(b<255) { // is b less than all the way up?
				incB(); // increment b
				if(bI<2) { // is this the first or second time through?
					incG(); // increment g
				}
				if(bI<1) { // is this the first time through?
					incR();
				}
			} else { // b is all the way up
				b=0; // reset b to 0
				g=0;
				r=0;
				bI++; // increment bI
			}
		} else { // b is done incrementing
			if(gI<2) { // is g done incrementing?
				if(g<255) { // is g less than all the way up?
					incG();
					if(gI>0) { // has g gone through once already?
						incR(); // increment R
					}
				} else { // g is all the way up
					g=0; // reset g to 0
					r=0;
					gI++; // increment gI
				}
			} else { // g is done incrementing
				if(rI<1) { // is a done incrementing?
					if(r<255) { // is a less than all the way up?
						incR();
					} else { // a is all the way up
						r=0;
						rI++
					}
				} else { // a is done incrementing
					// we're all done!!
				}
			}
		}
	}

	for(i=1;i<numSwatches;i++) {
		incColor();
		currColor = r+','+g+','+b;
		$('#palette').append('<div class="pPixel"></div>');
		$('.pPixel:last').css('background-color','rgb('+currColor+')');
	}
	
	count = 0;
	$('.pPixel').each(function() {
		count++;
		$(this).attr('id','pPixel-'+count).css({margin:0,padding:0,overflow:'hidden'});
	});
	

// select color
	
	var selColor = 'rgb(0,0,0)';

	$('.pPixel').click(function() {
		selColor = $(this).css('background-color');
		$('#selected').css('background-color',selColor);
		$('#selected-color').html(selColor);
	});

// paint that color
	
	var mouseDown = 0;
	$('#pixels').mousedown(function() {
		mouseDown = 1;
	});
	
	$('#pixels').mouseup(function() {
		mouseDown = 0;
	});

	$('.pixel').mouseenter(function() {
		if (mouseDown == 1) {
			$(this).css('background-color',selColor);
		}
	}).mousedown(function() {
		$(this).css('background-color',selColor);
	});
	
});
