$.fn.liveUpdate = function(){
	this.keyup(filter).keyup();
	return this;

	function filter(){
	    var term = $.trim( $(this).val().toLowerCase());
		if (term == '') {
			$('#alert').html('');
			$('#alert').removeClass("taken");
			$('#btnShorten').removeAttr("disabled");
		}
		else {
			$.get("check.php", {url:term}, function(ret) {
				msg = "available";
				if (ret==1) {
					msg = "taken";
					$('#btnShorten').attr("disabled", true);
					$('#alert').addClass("taken");
				}
				else if (ret==2) {
					msg = "invalid";
					$('#btnShorten').attr("disabled", true);
					$('#alert').addClass("taken");
				}
				else {
					$('#btnShorten').removeAttr("disabled");
					$('#alert').removeClass("taken");
				}
				$('#alert').html(msg);
			});
		}
		return true;
	}
};

$(document).ready(function() {
	$('#url').focus().select();
	$('#url').click(function() {
		$(this).select();
	});
	$('#custom').liveUpdate();
	$('#customize').click(function() {
		if ($('#custom_input').css('display')=='block')
			$('#custom').val('');
		else
			$('#custom').focus();
		$('#custom_input').slideToggle('fast');
		return false;
	});
	$('#shortened').click(function() {
		$(this).select();
	});
	$('.api_text').hide();
	$('#campaign_toggle').click(function() {
		if (this.checked) {
			$(this).parent().removeClass('disabled');
			$('.campaign_field').removeAttr('disabled');
		}
		else {
			$(this).parent().addClass('disabled');
			$('.campaign_field').attr('disabled', true);
		}
	});
	$('#preview').click(function() {
		if (this.checked) {
			$.get('/ajax.php', {action:'preview_on'}, function(ret) {
				if (ret=='on')
					$('#preview_status').html('on');
			});
		}
		else {
			$.get('/ajax.php', {action:'preview_off'}, function(ret) {
				if (ret=='off')
					$('#preview_status').html('off');
			});
		}
	});
});

function toggleApiFormat(format) {
	if (format=='json') {
		$('.api_text').hide();
		$('.api_json').fadeIn();
	}
	else {
		$('.api_json').hide();
		$('.api_text').fadeIn();
	}
	return false;
}
