jQuery(document).ready(function() {
	// Get the form objects
	var txt = $("#url");
	var btn = $("#btn");
	
	// Result
	var result = $("#result");
	
	$("form").submit(function(e) {
		extract();
		return false;
	});
	
	function extract()
	{
		var u = txt.val();
		var ht = "http://";
		
		// Clean the URL
		if(u.indexOf(ht) < 0)
			u = ht + u;
		
		u =  ht + u.match(/:\/\/(.[^/]+)/)[1];
		
		result.html('<p><img src="loading.gif" alt="" /> Loading...</p>');
		
		var html = '';
		$.ajax({
			type: "GET",
			url: "test.php",
			cache: false,
			data: "url="+u,
			dataType: "text",
			success: function(data) {
				if(data != "E")
				{
					var id = getID(data);
					if(id != null) {
						html += '<p><strong>Blog ID:</strong> '+ id +' <br /><strong>URL:</strong> '+ u +'</p>';
						html += '<p><a href="http://www.google.com/support/blogger/?action=flag&blog_ID='+ id +'&blog_URL='+ u +'">Click to flag this blog</a>. Remember to go through all the steps!</p>';
					}
					else {
						html += '<p><strong>Unable to find Blog ID</strong>. Please make sure the URL you typed points to a valid blogger page.</p>'
					}
					result.html(html);
				}
				else
				{
					result.html('<p><strong>Error loading page.</strong> The site may be temporarily unavailable. Please check the URL and try again.</p>');
				}
			}
		});
	}
	
	// Extracts the ID from the Blogger inserted stylesheet
	function getID(raw)
	{
		var r = new RegExp("targetBlogID=([0-9]+)");
		var m = r.exec(raw);
		var id = null;
		
		if(m != null)
		{
			id = '';
			for(var i=1; i<m.length; i++)
			{
				id += m[i];
			}
		}
		return id;
	}
});