(function ($) {

$.widget( "ui.forgotUsername", {

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

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

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

    sendRequest: function () {
	var self = this;
	
	self.clearErrors();

	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-form' ).hide();
	    $( '#forgot-msg' )
		.html( 'Your username and new password have been emailed to you.' )
		.show()
	    ;
	    window.setTimeout( function () {
		$( '#forgot-msg' ).fadeOut( 1400 );
	    }, 5000 );
	}
	else
	{
	    self.showErrors( xml );
	}
    }, // processRequest

    processFailure : function (resp) {

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

    }, // processFailure
    
    clearErrors: function () {
	var self = this;

	/* Clear their error message and hide them */
	$( '.ui-state-error', self.element ).each( function () {
	    $(this).html('').hide();
	} );
	
	return;
    }, // clearErrors

    showErrors: function (xml) {
	var self = this;

	var errors = xml.getElementsByTagName( 'error' );
	var form   = self.element[0];

	$.each( errors, function(idx, err) {
	    var key = err.getAttribute( 'key' );
	    var msg = err.getAttribute( 'msg' );
	    
	    var input  = form.elements[ key ];
	    var errDiv = $( '#' + key + '_fp_error' )[0];
	    
	    if( !errDiv ) {
		errDiv           = document.createElement( 'DIV' );
		errDiv.id        = key + '_error';
		errDiv.className = 'ui-state-error';
		input.parentNode.appendChild( errDiv );
		errDiv.innerHTML = msg;
	    }
	    else {
		errDiv.innerHTML = msg;
		$( errDiv ).show();
	    }
	} ); // errors.each
    } // showErrors

}); // $.widget

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

