/* TRGR code js file*/

$(document).ready(function(){
	// Add in "waiting text" for form fields
	$(':input.nolabel').each(function(){
		var $this = $(this);
		var type = $this.attr('type');
		var $label = $this.prev();
		var labelText = $label.text();
		var currentValue = $this.val();
		$label.hide();
		
		if (type == 'text')
		{
			// Waiting?
			if (currentValue == '' || currentValue == labelText)
			{
				$this.val(labelText).addClass('waiting');
			}
			
			// Keep the box in waiting state when it's empty
			$this
				.focus(function(){
					if ($this.hasClass('waiting'))
					{
						$this.val('');
						$this.removeClass('waiting');
					}
				})
				.blur(function(){
					if ($this.val() == '')
					{
						$this.val(labelText);
						$this.addClass('waiting');
					}
				})
				.closest('form').submit(function(){
					if ($this.val() == labelText) $this.val('');
				})
		}
	})
	
	//Put AJAX submit to encode form on home page	
	$postResult = $('#postResult');
	var postOptions = {
		dataType: 'xml',
		data: {format: 'xml' },
		beforeSubmit: function(data, $frm, options){
			if ($postResult.text() == '')
			{
				$postResult.hide().attr('class', 'waiting').text('Shrtnng ur URL...').slideDown();
			}
			else
			{
				$postResult.attr('class', 'waiting').text('Shrtnng ur URL...');
			}
		},
		success: function(response, status){
			var error = $(response).find('error').text();
			var originalURL = $(response).find('originalURL').text();
			var code = $(response).find('code').text();
			var shortURL = $(response).find('shortURL').text();
			
			// Any error?
			if (error != '')
			{
				$postResult.attr('class', 'error').html(error);
			}
			else
			{
				$postResult.attr('class', 'message').html('<p>Here\'s your new URL: <br />' + ' <a href="' + shortURL + '" target="_blank">' + shortURL + '</a></p>');
			}
		}
	};	
	$('#encodeForm').ajaxForm(postOptions);
	
})
