var scriptHost = "http://embed.carbonquilt.org";

function forceFill(showCode) {
	fillTemplate($('#parameters').get(0), showCode);
};
$(function(){
	$('.clear a').click(function(){
		$(this).parent().prev().children("input[type=text], textarea").val('');
		return false;
	});
	$('#form p.example a.eg').click(function() {
		$($(this).attr('href')).val($(this).text());
		forceFill(true);
		return false;
	});
	$('#parameters select').change(function() {
		forceFill(true);
	})
	$('#parameters').submit(function() {
		fillTemplate(this, true);
		return false;
	});
	forceFill(false);
});

function fillTemplate(form, showCode){
	var validate = {
		size: function(form, field, val) {
			var i = parseInt(val, 10);
			if (i < 220) { i = 220};
			form.elements[field].value = i;
			return i;
		}
	}
	var template = function(opts) {
		var safe = function(s) { return s.replace(/"/g, '\\"'); };
		with (opts) {
			var hasTitle = (title && title !== ''), hasCaption = (caption && caption !== "");
			var t = unescape('%3Cscript type="text/javascript" src="'+scriptHost+'/embed.nocache.js"%3E%3C/script%3E\n')+
				unescape("%3Cscript type=\"text/javascript\"%3E\n")+
				"EmbedCarbon.cube({\n"+
				"  mass: \""+safe(""+mass)+"\",\n"+
				"  size: "+size+((hasTitle || hasCaption) ? ",\n" : "") +
				(hasTitle ? "  title: \""+safe(title)+"\",\n" : "")+
				(hasTitle ? "  titlePosition: \"" + titlePosition + '"' + (hasCaption ? ",\n" : "")  : "")+
				(hasCaption ? "  caption: \""+safe(caption)+"\"\n" : "\n" )+
				"});\n" +
				unescape("%3C/script%3E\n")
			return t;
		}
	}
	var opts = {
	};
	for (var i = 0, ii = form.elements.length; i < ii; i++) {
		var el = form.elements[i], name = el.name, val = el.value;
		if (el.className.match("field")){
			if (typeof validate[name] === 'function') {
				val = validate[name](form, name, val);
			}
			opts[el.name] = val;
		}
	}
	$('#results').text(template(opts));
	var sb = $('#sandbox');
	sb.val(template(opts)).addClass('active');
	EmbedCarbon.cube("sandbox", opts)
	if (showCode){
		// flash resulting code
		//				/* $('#resultWrap').show(); */
	}
}

