var $j = jQuery.noConflict();

var button;

$j(document).ready(function(){
    //$j("#submit").bind('click', function() { alert('click'); });
    button = $j("#submit");

    var v = $j("#commentform").validate({
        errorElement: "span",
        errorClass: "form-error",
        errorPlacement: function(error, element) {
			 $j("label", element.parent()).after(error);
		},
		highlight: function(element, errorClass) {
			$j(":input", $j(element).parent()).addClass(errorClass);
		},
		submitHandler : function(form) {
		    return submitContactForm();
		},
		invalidHandler : function(form) {
    		$j("#status-message").remove();
		    return false;
		}

    });
    
    $j("#reset").click(function() {
        $j("#status-message").remove();
		v.resetForm();
	});  
});

function submitContactForm() {
    $j("#submit").attr('disabled','disabled').val('Sending. Please Wait ...');
    $j("#status-message").remove();

    var postMail = new sack("/contact/");
    
    postMail.method = 'POST';
    postMail.encVar("commenterName", $j("#commenterName").val());
    postMail.encVar("email", $j("#email").val());
    postMail.encVar("url", $j("#url").val());
    postMail.encVar("comment", $j("#comment").val());
    postMail.encVar("time", $j("#time").val());
    postMail.encVar("hashcode", $j("#hashcode").val());
    postMail.encVar("method", "ajax");
    
    postMail.onError = function() {
        $j("#submit").removeAttr('disabled').val('Submit');
        $j("#submit-row").before('<p id="status-message" class="error">Sorry, but there was an error: ' + postMail.responseStatus + '</p>');
    };
    postMail.onCompletion = function() { 
        var result = $j.evalJSON(postMail.response).result;

        $j("#submit").removeAttr('disabled').val('Submit');

        if(result == 'ok') {
            $j("#submit-row").before('<p id="status-message" class="success">Your comment was submitted successfully.</p>');
            $j("#commenterName").val('');
            $j("#email").val('');
            $j("#url").val('');
            $j("#comment").val('');
        } else {
            $j("#submit-row").before('<p id="status-message" class="error">Sorry, but there was an error: ' + $j.evalJSON(postMail.response).message + '</p>');
        }
    };
    
    postMail.runAJAX();

    return false;
}

