$(document).ready(function()
{
	// generic dialog
	$("#statusdialog").dialog( { autoOpen: false, modal: true, resizable: false } );

    // Keep Me Updated
    $(".signuplink").click(function(){ $("#updateddialog").dialog('open'); return false; });
    $("#updateddialog").dialog(
    { 
    	autoOpen: false, 
    	width:420, 
    	closeOnEscape: true, 
    	modal: true, 
    	draggable: true, 
    	resizable: false, 
    	title: "Keep Me Updated", 
    	buttons: 
    	{
    		"Sign Up": function() { $("#updateddialog form").submit(); },
    		"Cancel":function() { $(this).dialog('close'); }
    	}
    });

    function UpdateFormSubmitHandler(theForm)
    {
    	$(theForm).ajaxSubmit(
    	{
    		beforeSubmit:function(data,$form,options)
    		{
    			$("#updateddialog").dialog('close');
    			$("#statusdialog").html("<h2>Please Wait</h2><p>We are processing your request.</p><center><img src='/images/spinner.gif' alt='progress indicator'/>");
                $("#statusdialog").dialog('option','buttons',{});
                $("#statusdialog").dialog('open');
    			return true;
    		},
    		dataType: 'json',
    		url:"/form-submit.php",
    		success:function(response)
    		{
    			$("#statusdialog").html(response.message);
    			$("#statusdialog").dialog('open');
    			$("#statusdialog").dialog('option','buttons',{OK:function(){ $("#statusdialog").dialog('close'); }});

    			if (response.action != 'retry' && response.action != 'stay')
    				$("#statusdialog").dialog('option','close',function(){ window.location = "/" });
    		}
    	})
    }

	function PlaceError(error,$element)
	{
		var $batchElem = $element.closest('fieldset').children('.batcherror');
		if ($batchElem.length)
			error.appendTo($batchElem);
		else
			error.prependTo($element.closest('div.qfrow'));
	}

	function HiliteFieldOnError2(element,errorClass)
	{
		$(element).closest("div.qfelement").addClass('qferror');
	}

	function UnhiliteFieldOnError2(element,errorClass)
	{
		$(element).closest("div.qfelement").removeClass('qferror');
	}

	$("#updateddialog form").validate(
	{
		errorPlacement:PlaceError, 
		highlight:HiliteFieldOnError2, 
		unhighlight:UnhiliteFieldOnError2, 
		submitHandler:UpdateFormSubmitHandler,
		debug:false
	});
});
