$$.extend({
  Events : {
    Ready : function()
    {
      $('input#tmpEventDialogueCancel').click(
        function($e) {
          $e.preventDefault();
          $$.Events.CloseDialogue();
        }
      );

      $('input#tmpEventDialogueLogin').click(
        function($e) {
          $e.preventDefault();
          
          if ($('fieldset#tmpLogin').is(':hidden')) {
            $$.Events.OpenLoginForm();
          } else {
            $$.Events.CheckLogin();
          }
        }
      );

      $('a#tmpEventRegisterLink').click(
        function($e) {
          $e.preventDefault();
          $('form#tmpEventDialogue').OpenDialogue();
          
          if (hUserAgent == 'ie' && hUserAgentVersion == 6) {
            $('select#tmpEventPlatform').hide();
            $('select#tmpEventType').hide();
          }

          if ($('input#hUserName').val().length) {
            $('fieldset#tmpEventRegistration').hide();
            $('input#tmpEventDialogueRegister').hide();
            $('input#tmpEventDialogueLogin').hide();
            
            $('fieldset#tmpEventRegistrationLoggedIn').show();
            $('input#tmpEventDialogueRegisterForEvent').show();
          }

/*
          var $tmpEventTitle    = $('h4.tmpEventTitle').text();
          var $tmpEventLocation = $('p.tmpEventLocation').text();
          var $tmpEventDate     = $('div.tmpEventDateTime').html();
   
          $('td#tmpEventTitleDisplay').text($tmpEventTitle);
          $('td#tmpEventLocationDisplay').text($tmpEventLocation);
          $('td#tmpEventDateDisplay').html($tmpEventDate);
    
          $('input#tmpEventTitle').val($tmpEventTitle);
          $('input#tmpEventLocation').val($tmpEventLocation);
          $('input#tmpEventDate').val($('div.tmpEventDateTime').text());
*/
        }
      );

      $('input#tmpEventDialogueRegister').click(
        function($e) {
          $e.preventDefault();

          if (!$('fieldset#tmpLoginRegistration').is(':hidden')) {
            var $errors = '';

            if ($('input#hUserPasswordRegister').val() !== $('input#hUserPasswordRegisterConfirm').val()) {
              $errors += "Password and Password Confirmation do not match.\n";
            }

            if (!$('select#tmpEventDate option:selected').length) {
              $('select#tmpEventDate option').eq(0).attr('selected', 'selected');
            }

            if (!$errors) {
              var $fields = [
                'hContactFirstName',
                'hContactLastName',
                'hContactEmailAddress',
                'hContactCompany',
                'hContactTitle',
                //'hContactAddressStreet',
                //'hContactAddressCity',
                //'hLocationStateID',
                //'hContactAddressPostalCode',
                'hUserNameRegister',
                'hUserPasswordRegister',
                'hUserPasswordRegisterConfirm'
              ];
  
              $($fields).each(
                function() {
                  if (!$('#' + this).val()) {
                    var $label = $('#' + this).parents('tr').find('label').text();
                    $errors += "Required field, " + ($label.substring(0, $label.length - 1)) + ", is not filled in.\n";
                  }
                }
              );
            }

            if (!$errors) {
              $('img#tmpEventsActivity').show();
            
              $.post(
                '/private/tmpEvents/register',
                $('form#tmpEventDialogue').serialize(),
                function(xml) {
                  $('img#tmpEventsActivity').hide();
                  //$$.Events.CloseDialogue();
                  var $hUserID = parseInt($(xml).find('response').text());

                  if ($hUserID < 0) {
                    var $error = '';

                    switch ($hUserID) {
                      case -13: {
                        $error += "Username is already registered.\n";
                        break;
                      };
                      case -14: {
                        if (confirm(
                          "An account already exists with this email address.\n\n" +
                          "To login using that account, click \"OK\".\n\n" +
                          "To register a different address, click \"Cancel\"."   
                        )) {
                          $$.Events.OpenLoginForm();
                        } 
                            
                        return;
                      };
                      case -23: {
                        $error += "Email address does not appear to be valid.\n";
                        break;
                      };
                    }

                    alert("An error was detected in your account registration, please review and correct the following:\n\n" + $error);
                  } else {
                    $$.Events.ResendActivationCode();
                    $$.Events.OpenActivationForm();
                  }
                },
                'xml'
              );
            } else {
              alert("Some errors were detected in your account registration, please review and correct the following:\n\n" + $errors);
            }
          } else {
            $$.Events.OpenContactForm();
          }
        }
      );

      $('input#tmpEventDialogueActivate').click(
        function($e) {
          $e.preventDefault();
          
          if ($('input#hUserConfirmation').val()) {
            $('img#tmpEventsActivity').show();
            $.get(
              $$.Path(
                '/plugins/hUser/hUserLogin/activateUser', {
                  hUserName: $('input#hUserNameRegister').val(),
                  hUserConfirmation: $('input#hUserConfirmation').val()
                }
              ),
              function() {
                $('img#tmpEventsActivity').hide();
                $$.Events.RegisterForEvent();
              }
            );
          } else {
            alert('Please enter a valid confirmation code!');
          }
        }
      );

      $('input#tmpEventDialogueResendActivationCode').click(
        function($e) {
          $e.preventDefault();
          if (confirm("The activation code can take 10 minutes or more to arrive, to resend your activation code, click OK, otherwise press Cancel.")) {
            $$.Events.ResendActivationCode();
          }
        }
      );

      $('input#tmpEventDialogueRegisterForEvent').click(
        function($e) {
          $e.preventDefault();

          if (!$('select#tmpEventDate option:selected').length) {
            $('select#tmpEventDate option').eq(0).attr('selected', 'selected');
          }

          $$.Events.RegisterForEvent();
        }
      );

      $('input#tmpEventDialogueUpdateEmailAddress').click(
        function($e) {
          var $email = prompt('Enter a new Email Address:', '');

          if ($email && $email.length) {
            $('img#tmpEventsActivity').show();
            $.get(
              $$.Path(
                '/plugins/hUser/hUserLogin/updateEmailAddress', {
                  hUserName     : $('input#hUserNameRegister').val(),
                  hUserEmailOld : $('input#hUserActivationEmail').val(),
                  hUserEmailNew : $email,
                  hUserPassword : $('input#hUserPasswordRegister').val()
                }
              ),
              function(xml) {
                $('img#tmpEventsActivity').hide();
                var $response = parseInt($(xml).find('response').text());

                if ($response <= 0) {
                  switch ($response) {
                    case 0: {
                      alert('Update failed, username, password, or email address does not match.');
                      break;
                    };
                    case -23: {
                      alert('Update failed, new email address is not a valid email address.');
                      break;
                    };
                  }
                }
              }
            );
          }
        }
      );

      $('input#tmpEventDialogueContinue').click(
        function($e) {
          $e.preventDefault();
          $$.Events.OpenLoginRegistrationForm();
        }
      );

      $('input#tmpEventDialogueBack').click(
        function($e) {
          $e.preventDefault();

          switch (true) {
            case (!$('fieldset#tmpLogin').is(':hidden')):
            case (!$('fieldset#hContactForm').is(':hidden')): {
              $$.Events.OpenRegistrationForm();
              break;
            };
            case (!$('fieldset#tmpLoginRegistration').is(':hidden')): {
              $$.Events.OpenContactForm();
              break;
            };
          }
        }
      );

      $('input#hContactEmailAddress').keyup(
        function() {
          $('input#hUserNameRegister').val(this.value);
        }
      );
    },

    CheckLogin : function()
    {
      if (!$('select#tmpEventDate option:selected').length) {
        $('select#tmpEventDate option').eq(0).attr('selected', 'selected');
      }

      if ($('input#hUserName').val() && $('input#hUserPassword').val()) {
        $('img#tmpEventsActivity').show();
      
        $.post(
          $$.Path('/plugins/hUser/hUserLogin/login'), {
            hUserName: $('input#hUserName').val(),
            hUserPassword: $('input#hUserPassword').val()
          },
          function(xml) {
            $('img#tmpEventsActivity').hide();
            var $response = parseInt($(xml).find('response').text());

            if ($response) {
              $$.Events.GetEmailAddress();
            } else {
              alert('Error: Username or Password is incorrect.');
            }
          } 
        );
      } else {
        alert('Error: You did not enter a Username and Password.');
      }
    },

    GetEmailAddress : function()
    { 
      $('img#tmpEventsActivity').show();
      
      if ($('input#hUserName').val().indexOf('@') == -1) {
        $.post(
          $$.Path('/plugins/hUser/hUserLogin/getEmailAddress'), {
            hUserName: $('input#hUserName').val(),
            hUserPassword: $('input#hUserPassword').val() 
          },
          function(xml) {
            $('img#tmpEventsActivity').hide();
            var $response = $(xml).find('response').text();
  
            if ($response.length) {
              $('input#hContactEmailAddress').val($response);
              $$.Events.VerifyActivation();
            } else {
              alert('Error: Unable to retrieve an email address.');
            }
          }
        );
      } else {
        $.post(
          $$.Path('/plugins/hUser/hUserLogin/getUserName'), {
            hUserEmail: $('input#hUserName').val(),
            hUserPassword: $('input#hUserPassword').val() 
          },
          function(xml) {
            $('img#tmpEventsActivity').hide();
            var $response = $(xml).find('response').text();

            if ($response.length) {       
              $('input#hContactEmailAddress').val($('input#hUserName').val());
              $('input#hUserName').val($response);
              $$.Events.VerifyActivation();
            } else {
              alert('Error: Unable to retrieve an email address.');
            }
          }
        );
      
      }      
    },

    VerifyActivation : function()
    {    
      $('input#hUserNameRegister').val($('input#hUserName').val());
      $('input#hUserPasswordRegister').val($('input#hUserPassword').val());
      
      $('img#tmpEventsActivity').show();

      $.post(
        $$.Path('/plugins/hUser/hUserLogin/isActivated'), {
          hUserName: $('input#hUserName').val()
        },
        function(xml) {
          $('img#tmpEventsActivity').hide();
          var $response = parseInt($(xml).find('response').text());

          if ($response) {
            $$.Events.RegisterForEvent();
          } else {
            $$.Events.OpenActivationForm();
          }          
        }
      );
    },

    Login : function()
    {
      if ($('form#tmpLoginDialogue').length) {
        $('input#tmpUserLoginName').val($('input#hUserNameRegister').val());
        $('input#tmpUserLoginPassword').val($('input#hUserPasswordRegister').val());
        $('form#tmpLoginDialogue').get(0).submit();
      }
    },

    RegisterForEvent : function()
    {
      if ($('select#tmpEventDate option').length > 1) {
        if (!confirm("Please confirm your event date. You selected:\n\n" + $('select#tmpEventDate').val() + "\n\nIs this correct?")) {
          return;
        }
      }
      
      $('img#tmpEventsActivity').show();

      $.post(
        $$.Path(
          '/private/tmpEvents/registerForEvent', {
            hUserName : $('input#hUserNameRegister').val()
          }
        ),
        $('form#tmpEventDialogue').serialize(),
        function() {
          $('img#tmpEventsActivity').hide();
          //$$.Debug(html);
          alert('You are now registered for ' + $('td#tmpEventTitleDisplay').text());
          //$$.Events.Login();
          location.href = '/';
        }
      );
    },

    ResendActivationCode : function()
    {
      $('img#tmpEventsActivity').show();
      $.get(
        $$.Path(
          '/plugins/hUser/hUserLogin/resendActivation', {
            hUserName : $('input#hUserNameRegister').val(),
            hUserLoginActivationURL: $('input#hUserLoginActivationURL').val()
          }
        ),
        function() {
          $('img#tmpEventsActivity').hide();
        }
      );
    },

    CloseDialogue : function()
    {
      this.OpenRegistrationForm();

      $('form#tmpEventDialogue').CloseDialogue();
      
      if (hUserAgent == 'ie' && hUserAgentVersion == 6) {
        $('select#tmpEventPlatform').show();
        $('select#tmpEventType').show();
      }

      $('form#tmpEventDialogue').get(0).reset();
    },

    OpenRegistrationForm : function()
    {
      $('fieldset#tmpEventRegistration').show();
      $('fieldset#tmpLogin').hide();
      $('fieldset#tmpLoginRegistration').hide();
      $('fieldset#hContactForm').hide();
      $('fieldset#tmpEventActivation').hide();
      $('fieldset#tmpEventRegistrationLoggedIn').hide();

      $('input#tmpEventDialogueRegisterForEvent').hide();
      $('input#tmpEventDialogueRegister').show();
      $('input#tmpEventDialogueContinue').hide();
      $('input#tmpEventDialogueLogin').show();
      $('input#tmpEventDialogueBack').hide();

      $('input#tmpEventDialogueActivate').hide();
      $('input#tmpEventDialogueResendActivationCode').hide();
      $('input#tmpEventDialogueUpdateEmailAddress').hide();

      $('form#tmpEventDialogue').animate({
        height: '360px',
        marginTop: '-180px'
      });
    },

    OpenContactForm : function()
    {
      $('fieldset#tmpEventRegistration').hide();
      $('fieldset#tmpLoginRegistration').hide();
      $('fieldset#hContactForm').show();
      $('input#tmpEventDialogueLogin').hide();
      $('input#tmpEventDialogueBack').show();

      $('form#tmpEventDialogue').animate({
        height: '510px',
        marginTop: '-255px'
      });

      $('input#tmpEventDialogueRegister').hide();
      $('input#tmpEventDialogueContinue').show();
      $('fieldset#tmpLoginRegistration').hide();
    },

    OpenLoginRegistrationForm : function()
    {
      $('fieldset#hContactForm').hide();
      $('fieldset#tmpLoginRegistration').show();
      
      $('input#tmpEventDialogueContinue').hide();
      $('input#tmpEventDialogueRegister').show();
      $('input#tmpEventDialogueBack').show();

      $('form#tmpEventDialogue').animate({
        height: '450px',
        marginTop: '-225px'
      });
    },

    OpenActivationForm : function()
    {
      $('fieldset#tmpEventActivation').show();
      $('fieldset#tmpLoginRegistration').hide();
      $('fieldset#tmpEventRegistration').hide();
      $('fieldset#tmpLogin').hide();
      $('input#tmpEventDialogueBack').hide();
      $('input#tmpEventDialogueRegister').hide();
      $('input#tmpEventDialogueLogin').hide();
      $('input#tmpEventDialogueActivate').show();
      $('input#tmpEventDialogueResendActivationCode').show();
      $('input#tmpEventDialogueUpdateEmailAddress').show();

      var $email = $('input#hContactEmailAddress').val();

      $('p#tmpEventActivationCopy b').text($email);

      $('input#hUserActivationEmail')
        .attr('readonly', 'readonly')
        .val($email);

      $('form#tmpEventDialogue').animate({
        height: '426px',
        marginTop: '-213px'
      });
    },
    
    OpenLoginForm : function()
    {
      $('fieldset#tmpEventRegistration').hide();
      $('fieldset#tmpLogin').show();
      $('input#tmpEventDialogueRegister').hide();
      $('fieldset#tmpLoginRegistration').hide();
      $('input#tmpEventDialogueBack').show();
      
      $('form#tmpEventDialogue').animate({
        height: '360px',
        marginTop: '-180px'
      });
    }
  }
});

$(document).ready(
  function() {
    $$.Events.Ready();
  }
);