var baseDir = ( ( typeof( parent.appBaseDir ) != "undefined" ) ? parent.appBaseDir : "" );

var Auth =
{
  domId: "dlm_auth_mdl",
  loginForm:"", /*stored cached login form*/
  postLogin:function(){}, /* overwrite this with your deployment's post-login calls (eg. hide "login" & show "logout" buttons)*/
  postLogout:function(){}, /* overwrite this with your deployment's post-login calls. See above*/
  optionLoginPrompt: function(msg,onSuccess,buttons)
  {

    if( typeof(buttons) == "undefined" )
    {
      buttons = { "Cancel":"f", "Login":"t", "Remain Anonymous":"a" };
    }

    return Auth.loginPrompt(msg,onSuccess,buttons);

    /*
    if( typeof( $.prompt ) == "undefined" )
    {
      document.location.href=baseDir + "/?c=/user/login.jsp";
    }

    if( typeof(buttons) != "object" && typeof(onSuccess)=="object" )
    {
      buttons = onSuccess;
    }

    if( typeof(buttons) == "undefined" )
    {
      buttons = { "Cancel":"f", "Login":"t", "Remain Anonymous":"a" };
    }

    var postSub = function(data,status)
    {
      if( typeof( console ) != "undefined" ) { console.log( data, status ); }
      if(status!="success" || !data.success)
      {
        var message = (data.error=="" && data.message=="")?"Log-in Failed": data.error +"\n"+ data.message;
        Auth.optionLoginPrompt(message,onSuccess);
      }
      else
      {
        if( typeof(onSuccess)=="function" )
        {
          onSuccess();
        }
        Auth.postLogin();
      }
    }
    var showPrompt = function()
    {
      $.prompt( Auth.loginForm, {
          "prefix": Auth.domId,
          "loaded": function(){
            $(".loginMsg",$(this)).text(msg);
            $("[name='username']",$(this)).focus();
            $("[name='password']",$(this)).keypress(function(e)
            {
              if( (e.keyCode&&e.keyCode == 13) || e.which == 13){ $("#"+Auth.domId+" button:last").trigger("click") }
            }
          ); },
          "opacity": 0.2,
          "buttons": buttons,
          "promptspeed": -1,
          "submit": function( val, msg )
          {
            if( val == "t" && ( $("[name='username']",msg).val() == "" || $("[name='password']",msg).val() == "" ) )
            {
              $.prompt( "Please fill both the username and password if you wish to proceed." );
              return false;
            }
            return val == "f" || val == "a" || ( $("[name='username']",msg).val() != "" && $("[name='password']",msg).val() != "" );
          },
          "callback": function( val, msg )
          {
            if( val == "f" )
            {
              document.location.href = baseDir + "/";
              return;
            }
            else if( val == "a" )
            {
              if( typeof(onSuccess)=="function" )  //go to poll/survey without logging in
              {
                onSuccess();
              }
              Auth.postLogin();
              return;
            }

            $.ajax( {url:baseDir + "/servlet/Login", type:"post", dataType:"json", data:$("form",msg).serializeArray(), success:postSub, error:postSub} );
          }
      });
    }

    if( Auth.loginForm == "" )
    {
      $.get(baseDir + "/user/loginPop.jsp", {}, function(data,status)
      {
        if(status!="success")
        {
          document.location.href=baseDir + "/servlet/Login";
        }
        else
        {
          Auth.loginForm = data;
          showPrompt();
        }
      });
    }
    else
    {
      showPrompt();
    }
    */
  },

  loginPrompt: function(msg,onSuccess,buttons)
  {
    if( typeof( $.prompt ) == "undefined" )
    {
      document.location.href=baseDir + "/?c=/user/login.jsp";
    }

    if( typeof(buttons) != "object" && typeof(onSuccess)=="object" )
    {
      buttons = onSuccess;
    }

    if( typeof(buttons) == "undefined" )
    {
      buttons = { "Cancel":"f", "Login":"t" };
    }

    var postSub = function(data,status)
    {
      if( typeof( console ) != "undefined" ) { console.log( data, status ); }
      if(status!="success" || !data.success)
      {
        var message = (data.error=="" && data.message=="")?"Log-in Failed": data.error +"\n"+ data.message;
        Auth.loginPrompt(message,onSuccess);
      }
      else
      {
        if( typeof(onSuccess)=="function" )
        {
          onSuccess();
        }
        Auth.postLogin();
      }
    }

    var showPrompt = function()
    {
      $.prompt( Auth.loginForm,
      {
        "prefix": Auth.domId,
        "loaded": function()
        {
          $(".loginMsg",$(this)).text(msg);
          $("[name='username']",$(this)).focus();
          $("[name='password']",$(this)).keypress(function(e)
          {
            if( (e.keyCode&&e.keyCode == 13) || e.which == 13){ $("#"+Auth.domId+" button:last").trigger("click") }
          });
        },
        "opacity": 0.2,
        "buttons": buttons,
        "promptspeed": -1,
        "submit": function( val, msg )
        {
          if( val == "t" && ( $("[name='username']",msg).val() == "" || $("[name='password']",msg).val() == "" ) )
          {
            $.prompt( "Please fill both the username and password if you wish to proceed." );
            return false;
          }
          return val == "f" || val == "a" || ( $("[name='username']",msg).val() != "" && $("[name='password']",msg).val() != "" );
        },
        "callback": function( val, msg )
        {
          if( val == "f" )
          {
            document.location.href = baseDir + "/";
            return;
          }
          else if( val == "a" )
          {
            if( typeof(onSuccess)=="function" )  //go to poll/survey without logging in
            {
              onSuccess();
            }
            Auth.postLogin();
            return;
          }

          $.ajax( {url:baseDir + "/servlet/Login", type:"post", dataType:"json", data:$("form",msg).serializeArray(), success:postSub, error:postSub} );
        }
      });
    }

    if( Auth.loginForm == "" )
    {
      $.get(baseDir + "/user/loginPop.jsp", {}, function(data,status)
      {
        if(status!="success")
        {
          document.location.href=baseDir + "/servlet/Login";
        }
        else
        {
          Auth.loginForm = data;
          showPrompt();
        }
      });
    }
    else
    {
      showPrompt();
    }
  },

  logoutConfirm: function(msg,onSuccess)
  {

    msg = (msg==undefined || msg=="")?"Are you sure you wish to logout?": msg;

    var doLogout = function()
    {
      $.ajax( {url:baseDir + "/servlet/Logout", type:"post", complete:function(data,status)
      {
        if(status!="success")
        {
          Auth.logoutConfirm("Log-out failed. Please try again",onSuccess);
        }
        else
        {
          if( typeof(onSuccess)=="function" )
          {
            onSuccess();
          }
          Auth.postLogout();
        }
      } });
    }

    if( typeof( $.prompt ) == "undefined" || ( jQuery.browser.msie && jQuery.browser.version < 7 ) )
    {
      if( confirm(msg) )
      {
        doLogout();
      }
      return;
    }
    $.prompt( msg, {
        prefix: Auth.domId,
        buttons: { "Logout":true, "Cancel":false },
        focus:1,
        promptspeed:-1,
        callback:function( val )
        {
          if( val )
          {
            doLogout();
          }
        }
    });
  }
}
