function jQueryLoader() {
	$('.removePart, .colorFlip').unbind();
	
	$('.removePart').click(function() {
		$(this).parent().parent().remove();
		partCount--
	});

	$('.colorFlip').click(function() {
		var id = $(this).attr('id');
		var num = id.replace(/flipColor/, '');
		var c1 = $('#gColorFirst'+num).val();
		var c2 = $('#gColorSecond'+num).val();
		$('#gColorFirst'+num).val(c2);
		$('#gColorSecond'+num).val(c1);
		return false;
	});

	$('.gColorFirst, .gColorSecond').focus(function() {
		$('.gColorPicker').hide();
		$(this).parent().next().show();
	})

	$('.gColorFirst, .gColorSecond').blur(function() {
		$('.gColorPicker').hide();
		if($(this).val()[0]!='#') {
			$(this).val('#'+$(this).val());
		}
	})
}

function addPart(tpl) {
	partCounter++;
	partCount++;
	var html = $('#'+tpl).html();
	html = html.replace(/NUM/g, partCounter).replace(/partId/, 'genPart'+partCounter).replace(/partClass/, 'genPart');
	$('#genPartMarker').before(html);
	if(tpl=='genPartGradientTemplate') {
		activateGradient(partCounter);
	} else {
		activateSolid(partCounter);
	}
	return partCounter;
}
function activateGradient(partNum) {
	var okButton = '<p>OK</p>';
	$('#gColorFirst'+partNum+'Picker').farbtastic('#gColorFirst'+partNum).append(okButton);
	$('#gColorSecond'+partNum+'Picker').farbtastic('#gColorSecond'+partNum).append(okButton);
	jQueryLoader();
}
function activateSolid(partNum) {
	var okButton = '<p>OK</p>';
	$('#gColorFirst'+partNum+'Picker').farbtastic('#gColorFirst'+partNum).append(okButton);
	jQueryLoader();
}

$(document).ready(function(){
	partCounter = 100;
	partCount = 0;
	jQueryLoader();

	$('#fwTabs ul li').click(function() {
		var id = $(this).attr('id');
		$('#fwTabs ul li').removeClass('active');
		$('#'+id).addClass('active');
		$('.fwBlockContent').hide();
		$('#'+id+'Content').show();
	});

	$('#addGradient').click(function() {
		if(partCount>=10) {
			alert('Enough already!');
		} else {
			addPart('genPartGradientTemplate');
		}
	});

	$('#addSolid').click(function() {
		if(partCount>=10) {
			alert('Enough already!');
		} else {
			addPart('genPartSolidTemplate');
		}
	});

	$('#generateLink').click(function() {
		$('#fwBlockGeneratorContent form').submit();
	})

	$('#gRotate').change(function() {
		if($(this).attr('checked')) {
			$('.widthLabel').text('Height:');
			$('.heightLabel').text('Width:');
		} else {
			$('.widthLabel').text('Width:');
			$('.heightLabel').text('Height:');
		}
	});

	$('#fwBlockGeneratorContent form').submit(function() {
		var params = $(this).serialize();
		var loading = '<p>Loading...</p>';
		$('#result').html(loading).load('/web20/generate?'+params).show();
		return false;
	});
});
