(function ($) {

$.widget( "ui.forgotPassword", {

    _init: function () {
	var self = this;
	
	this.element.bind( 'submit.forgotPassword', function () {
	    return self.sendRequest();
	} );
	
	return;
    }, // _init

    destroy: function () {
	this.element.unbind( '.forgotPassword' );

	$.widget.prototype.destroy.apply( this, arguments );
    }, // destroy

    sendRequest: function () {
	var self = this;

	$( '#forgot-msg-error', self.element ).hide();
	$( '#forgot-msg-success', self.element ).hide();
	
	var url = self.element[0].getAttribute( 'action' );

	var params = self.element.serialize();

	$.ajax( {
	    url : url,
	    type : 'post',
	    data : params,
	    success : function (data) { self.processResponse(data) },
	    error  : function (resp) { self.processFailure(resp) }
	} );

	return false;
    }, // sendRequest

    processResponse : function (xmlResp) {
	var self = this;

	var xml     = xmlResp.documentElement;
	var success = parseInt( xml.getAttribute( 'code' ) );

	if( success )
	{
	    $( '#forgot-msg-success', self.element )
		.html( 'Your new Password will be emailed to you.' )
	 	.show()
	    ;
	    window.setTimeout( function () {
		$( '#forgot-msg-success', self.element ).fadeOut( 1400 );
	    }, 5000 );
	}
	else
	{
	    var errors = xml.getElementsByTagName( 'error' );
            var message = '';

            $.each( errors, function(idx, err) {
                var key = err.getAttribute( 'key' );
                var msg = err.getAttribute( 'msg' );
                if (key == 'email') message += msg;
            } );
	
	    $( '#forgot-msg-error', self.element )
		.html( message )
		.show()
	    ;
	}
    }, // processRequest

    processFailure : function (resp) {

	alert( "An error has occurred while requesting a new password.\n"
	       + "Please try again in a few minutes." );

    } // processFailure
    
}); // $.widget

})(jQuery); // function($)
