Drupal.behaviors.jquery_ui_login = function(context) {
  
  var settings = Drupal.settings.jQueryUILogin.settings;
  var paths = Drupal.settings.jQueryUILogin.paths;
  
  var login;
  if (settings.login) {
    $("a[href^='/user/login'], a[href^='/?q=user/login']").each(function(){
    $(this).click(function(){
      var destination = '?destination=' + paths.current.path;
      var throbber = $('<img/>').css({
		    display: 'none',
		    float: 'left'
		  }).attr('src', paths.throbber.absolute);
      if (login === undefined || login.length === 0) {
        login = $('<div/>').attr('id', 'jquery_ui_login').css('overflow', 'hidden');
      }
      var form;
      var title = 'Login';
      if ($(this).attr('title') != '') {
        title = $(this).attr('title');
  	  }
  	  else if ($(this).text() != '') {
        title = $(this).text();
      }
      $.ajax({
        url: paths.ajax.relative,
        data: {
          destination: paths.current.path
        },
        dataType: 'json',
        type: 'POST',
        complete: function(XMLHttpRequest, textStatus) {
          switch(textStatus) {
            case 'error':
              login.html('An error has occured and the login form cannot not be displayed.<br /><br />To login, please visit:<br /><a href="' + paths.login.absolute + '">' + paths.login.absolute + '</a>');
              login.dialog('option', { position: 'center' });
              break;
          }
        },
        success: function(data) {
          form = $(data.form);
          form.find('input[type="submit"]').hide();
          login.html(form);
          login.dialog('option', { position: 'center' });
          login.dialog({
      			title: title,
      			draggable: false,
      			resizable: false,
      			width: 400,
      			modal: true,
      			open: function(e, ui) {
      			  login.parent().find('.ui-dialog-buttonpane').prepend(throbber);
      			},
      			close: function(e,ui) {
      				login.dialog('destroy');
      				login.remove();
      			},
      			buttons: {
      			  'Cancel': function() {
      					login.dialog('close');				
      				},
      				'Login': function() {
      					form.submit();
        			}
      			}
      		}).dialog('open');
          var loginValid = false;
          // Form submit event handler
          form.submit(function(){
            var messages = $(login).find('div.jul-messages');
            if (messages.length) {
              messages.remove();
              login.dialog('option', { position: 'center' });
            }
            if (loginValid) {
              return true;
            };
            passingData = {
              name: form.find('#edit-name').val(),
              pass: form.find('#edit-pass').val()
            };
            if ($.md5 !== undefined && typeof $.md5 === 'function' && settings.md5) {
              passingData['md5'] = 1;
              passingData['pass'] = $.md5(passingData['pass']);
            }
            var windowname = false;
            if (!paths.current.secure && paths.login.secure) {
              windowname = true;
            }
            throbber.fadeIn();
            $.ajax({
              url: paths.authenticate.absolute,
              'windowname': windowname,
              'data': passingData,
              cache: false,
              type: 'POST',
              dataType: 'json',
              complete: function(XMLHttpRequest, textStatus) {
                throbber.fadeOut();
                switch(textStatus) {
                  case 'error':
                    login.html('An error has occured while attempting to login.');
                    login.dialog('option', { position: 'center', buttons: {
                			  'Cancel': function() {
                					login.dialog('close');				
                				},
                				'Manual Login': function() {
                				  location.href=paths.login.absolute + destination;
                					form.submit();
                  			}
              			  }
              			});
                    break;
                }
              },
              success: function(data){
                if (data.success === true) {
                  loginValid = true;
                  form.submit();
                }
                else {
                  var messages = login.find('div.jul-messages');
                  if (!messages.length) {
                    messages = $('<div/>').addClass('jul-messages ui-state-error ui-corner-all');
                    login.prepend(messages);
                  }
                  var ul = $('<ul>');
                  $.each(data.messages, function(key, message){
                    var icon = $('<span/>').addClass('ui-icon ui-icon-alert');
                    var li = $('<li/>').html(message);
                    li.prepend(icon);
                    ul.append(li);
                  });
                  messages.html(ul);
                }
                login.dialog('option', { position: 'center' });
              }
            });
            return false;
          });
        }
      });
      return false;
    });
  });
  }
  
  // Process logout dialogs
  if (settings.logout) {
    $("a[href^='/logout'], a[href^='/?q=logout']").each(function(){
      $(this).click(function(){
        var link = $(this).attr('href');
        var title = 'Logout';
        var logout = $('<div/>').attr('id', 'jquery_ui_login');
        $(logout).text('Are you sure you wish to logout and end this session?').dialog({
    			title: title,
    			bgiframe: true,
    			draggable: false,
    			resizable: false,
    			width: 400,
    			height:75,
    			modal: true,
     			overlay: {
       				backgroundColor: '#000',
    				opacity: 0.25
    			},
    			buttons: {
    			  'Cancel': function() {
    					$(this).dialog('close');				
    					return false;
    				},
    				'Logout': function() {
    					$('#dialog').dialog('close');
    					window.location = link;
    				}
    			},
    			close: function(e,ui) {
    				$(login).dialog('destroy');
    			}
    		}).dialog('open');
        return false;
      });
    });
  }
}
