

/*
* Version 1.1 20100708 MP
* Requires jQuery 1.5 and the jQuery template plugin (http://api.jquery.com/category/plugins/templates/)
*
* This plugin has 3 methods.
* - The default method outputs the currently logged in user's account data
* (everything that is exposed by the OpenCMS registration rest API - http://sp10prod/divisions/dispatch_it_web/Redtail%20Wiki/Registration%20Module.aspx)
* in a named jquery template. You can pass this method the name of a named template (there are 6 defined in the plugin - see the documentation).
* 
* - 'getValues' takes no parameters and outputs the profiledata object returned by the rest api.
*
* - 'isGuest' returns true if the user is currently a guest, false if the user is logged in to a registered account. Takes no parameters.
*
* Version 1.1 -- added a callback to the init function and a custom template for the dispatch toobar.
* Version 1.2 -- added caching of account data to avoid repeated calls.
*
*/

(function( $ ){


  // set the cms-link-tagged uri base (all methods below use the same one).
  var globalPostUri = "/content/system/modules/com.dispatch.registration/rest/user";
  
  var userProfile = {};

  var methods = {

    init : function( options ) {

      var tmpmarkup = '<div class="dAccount"><p class="monikers"><span class="realname">{{= firstname}} {{= lastname}}</span> <span class="username">({{= login}})</span></p><p class="email">{{= email}}</p><p class="zipcode">{{= zipcode}}</p><p class="dates">Account Created: <span class="createddate">{{= createddate}}</span> | Last Login: <span class="lastlogin">{{= lastlogin}}</span></p></div>';
      $.template("dAccountDefault", tmpmarkup);
      
      tmpmarkup = '<div class="dAccount"><p class="monikers"><span class="realname">{{= firstname}} {{= lastname}}</span> <span class="username">({{= login}})</span></p><p class="email">{{= email}}</p><p class="zipcode">{{= zipcode}}</p></div>';
      $.template("dAccountNameAndEmail", tmpmarkup);
      
      tmpmarkup = '<div class="dAccount"><p class="monikers"><span class="realname">{{= firstname}} {{= lastname}}</span> <span class="username">({{= login}})</span></p></div>';
      $.template("dAccountName", tmpmarkup);
      
      tmpmarkup = '<div class="dAccount"><p class="username">{{= login}}</p></div>';
      $.template("dAccountUsername", tmpmarkup);
      
      tmpmarkup = '<span class="realname">{{= firstname}} {{= lastname}}</span> <span class="username">({{= login}})</span>';
      $.template("dAccountNameInline", tmpmarkup);
      
      tmpmarkup = '<span class="username">{{= login}}</span>';
      $.template("dAccountUsernameInline", tmpmarkup);
      
      var settings = {
        'template' : 'dAccountDefault',
        'posturi'  : globalPostUri,
        'ifLoggedIn'  : true,
        'loggedOutAlt' : false,
        'loggedOutHTML' : '',
        'clearfirst' : false,
        'callback'  : ''
        
      }
      
      if ( options ) { 
        $.extend( settings, options );
      }

      return this.each(function() {

        var $this = $(this);
        
        if (!userProfile.hasOwnProperty('login')) {
        
          var cachebust = Math.round(new Date().getTime() / 1000);
        
          $.ajax({
            type: "GET",
            jsonp: null,
            jsonpCallback: null,
            url: settings.posturi,
            async: false,
            data: {
            	z : cachebust
            },
            dataType: "json",
            success: function (accountdata) {
              if ((accountdata.login != "Guest" && settings.ifLoggedIn) ||  !settings.ifLoggedIn) {
                if (settings.clearfirst) {
                  $this.html('');
                }
                $.tmpl(settings.template, accountdata).appendTo($this);
                userProfile = accountdata;
              }
              if(typeof settings.callback == 'function'){
                //settings.callback.call(accountdata.login);
                settings.callback(accountdata.login);
              }
            }
          });
        
        } else {
          $.tmpl(settings.template, userProfile).appendTo($this);
        }
        
      });
    },
    getValues : function (options) {
      
      var settings = {
        'posturi'  : globalPostUri
      }
      
      if ( options ) { 
        $.extend( settings, options );
      }
      
      if (!userProfile.hasOwnProperty('login')) {
      
        var cachebust = Math.round(new Date().getTime() / 1000);
        
        var profiledata;
        
        $.ajax({
            type: "GET",
            async: false,
            url: settings.posturi,
            jsonp: null,
            jsonpCallback: null,
            data: {
            	z : cachebust
            },
            dataType: "json",
            success: function (accountdata) {
              profiledata = accountdata;
              userProfile = accountdata;
            }
          });
      
      } else {
        profiledata = userProfile;
      }
        
      return profiledata;
      
    },
    isGuest : function (options) {
      
      var settings = {
        'posturi'  : globalPostUri
      }
      
      if ( options ) { 
        $.extend( settings, options );
      }
      
      var loggedasguest;
      
      if (!userProfile.hasOwnProperty('login')) {
      
        var cachebust = Math.round(new Date().getTime() / 1000);
        
        $.ajax({
            type: "GET",
            async: false,
            url: settings.posturi,
            jsonp: null,
            jsonpCallback: null,
            data: {
            	z : cachebust
            },
            dataType: "json",
            success: function (accountdata) {
              if (accountdata.login == "Guest") {
                loggedasguest = true;
              } else {
                loggedasguest = false;
              }
              userProfile = accountdata;
            }
          });
          
        } else {
        
          if (userProfile.login == "Guest") {
            loggedasguest = true;
          } else {
            loggedasguest = false;
          }
        
        }
      
      return loggedasguest;
    } 
  }

  $.fn.daccount = function ( method ) {

    if ( methods[method] ) {
      return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist.' );
    }
  }
})( jQuery );
