Free JQuery Mobile Adoption Manager JavaScript Code

Written by ShamrockCRM on August 26, 2012 – 9:03 pm

This is Part 3 in the series of Salesforce.com HTML5 Mobile Development using VisualForce, APEX, JavaScript (JQuery Mobile) and HTML5.  I have already posted the code for the Visualforce as well as the APEX Controller.  This part in the series provides you with the JavaScript code to finalize everything.  The combination of all of this will show you how to implement this Adoption Manager AppExchange app for managing the adoption of your users.

A couple of notes here.  This code is certainly not optimized and certainly not prettied up.  A lot of the functions need to be merged into cleaner functions.  The memory usage could probably optimized a little better.  There are a couple of other things to play with as well.  This is basically a way to help you learn how to implement different features using Salesforce.com in HTML5 with JQuery mobile, such as querying profiles and dynamically populating a form picklist and displaying lists of users on the screen and activating/deactivating users, etc.  Take what you will from this, but it is a fully functional mobile app for you to hack and place into PhoneGap if you would like.

Salesforce JQuery Mobile

This code goes into the usermanager.resource static resource (after the break).

var currentTracks = new Array();
var currentAlbums = new Array();
var currentUsers = new Array();
var neverUsers = new Array();
var searchUsers = new Array();
var inactiveUsers = new Array();
var profiles = new Array();
var userRoles = new Array();
var userLicenses = new Array();
var activeUsersRecords = new Array();
var inactiveUsersRecords = new Array();
var numUsersPerBlock = 50;
var numActiveUsersLoaded = 0;
var numInactiveUsersLoaded = 0;
var numNeverUsersLoaded = 0;
var numSearchUsersLoaded = 0;

var $j = jQuery.noConflict(); 

$j(document).ready(init);
    
function init() {
    if(window.location.href.indexOf('#') > 0) {
        window.location.href = window.location.href.split("#")[0];
    }
        
    $j.mobile.showPageLoadingMsg();
    getUsers(function(){
        $j.mobile.hidePageLoadingMsg();
    });
}

$j(document).delegate("#inactivepage", "pageinit", function() {
   $j.mobile.showPageLoadingMsg();
    getInactiveUsers(function(){
        $j.mobile.hidePageLoadingMsg();
    });
});

$j(document).delegate("#neverpage", "pageinit", function() {
   $j.mobile.showPageLoadingMsg();
    getNeverUsers(function(){
        $j.mobile.hidePageLoadingMsg();
    });
});

$j(document).delegate("#newuserpage", "pageinit", function() {
   $j.mobile.showPageLoadingMsg();
    getProfileRole(function(){
        $j.mobile.hidePageLoadingMsg();
    });
});

$j(document).delegate("#searchpage", "pageinit", function() {
	//form validation
    $j("#searchFormForm").submit(function(event) {
      event.preventDefault();
      $j("#searchUserlist").empty();
      $j('div#searchUserListDiv ul').listview('refresh');
      try{
      $j("#searchForm").focus();
      }
      catch(err){
      	//
      }
      numSearchUsersLoaded=0;
      var fireError = false;
      var searchForm = "";

      $j("#errorMessageSearchUser").empty();
      
      if ($j("#searchForm").val() == "") {
        $j("#errorMessageSearchUser").append("-Search box must be filled in<br />").show();
        fireError = true;
      }
      if(fireError==true){
      	try{
      	 $j("#errorMessageSearchUser").focus();
      	}
      	catch(err){
      	 //
      	}
      	return false;
      }
      else{
      	 //no errors with submission
      	 $j.mobile.showPageLoadingMsg();
         searchForm = $j("#searchForm").val();
         adoptionmanager.usermanagerController.querySearchUsers(searchForm, function(records, e) { showSearchUsers(records, $j.mobile.showPageLoadingMsg()) }, {escape:true}); 
      }
      return false;
    });
    
    
   $j.mobile.showPageLoadingMsg();
    getSearchPage(function(){
        $j.mobile.hidePageLoadingMsg();
    });
    
    
});

function getUsers(callback) {
    $j('#userlist').empty();
    var numActiveUsersLoaded = 0;
    adoptionmanager.usermanagerController.queryUsers(function(records, e) { activeUsersRecords = records; showUsers(activeUsersRecords, callback) }, {escape:true}); 
}


function getUsersSubset() {
	//return just a subset of all records to save time in JS processing
	if((numActiveUsersLoaded+numUsersPerBlock)<activeUsersRecords.length-1){
		showUsers(activeUsersRecords.slice(numActiveUsersLoaded, numActiveUsersLoaded+numUsersPerBlock), $j.mobile.showPageLoadingMsg());
	}
	else{
		showUsers(activeUsersRecords.slice(numActiveUsersLoaded, activeUsersRecords.length), $j.mobile.showPageLoadingMsg());
	}  
}

function getInactiveUsers(callback) {
    $j('#inactiveuserlist').empty();
    var numInactiveUsersLoaded = 0;
    adoptionmanager.usermanagerController.queryInactiveUsers(function(records, e) { inactiveUsersRecords = records; showInactiveUsers(inactiveUsersRecords, callback) }, {escape:true}); 
}

function getUsersInactiveSubset() {
	//return just a subset of all records to save time in JS processing
	if((numInactiveUsersLoaded+numUsersPerBlock)<inactiveUsersRecords.length-1){
		showInactiveUsers(inactiveUsersRecords.slice(numInactiveUsersLoaded, numInactiveUsersLoaded+numUsersPerBlock), $j.mobile.showPageLoadingMsg());
	}
	else{
		showInactiveUsers(inactiveUsersRecords.slice(numInactiveUsersLoaded, inactiveUsersRecords.length), $j.mobile.showPageLoadingMsg());
	}  
}

function getNeverUsers(callback) {
    $j('#neveruserlist').empty();
    var numNeverUsersLoaded = 0;
    adoptionmanager.usermanagerController.queryNeverUsers(function(records, e) { neverUsersRecords = records; showNeverUsers(neverUsersRecords, callback) }, {escape:true}); 
}

function getUsersNeverSubset() {
	if((numNeverUsersLoaded+numUsersPerBlock)<neverUsersRecords.length-1){
		showNeverUsers(neverUsersRecords.slice(numNeverUsersLoaded, numNeverUsersLoaded+numUsersPerBlock), $j.mobile.showPageLoadingMsg());
	}
	else{
		showNeverUsers(neverUsersRecords.slice(numNeverUsersLoaded, neverUsersRecords.length), $j.mobile.showPageLoadingMsg());
	}  
}

function getProfileRole(callback) {
    $j('#profileForm').empty();
    $j('#roleForm').empty();
    $j('#userlicenceForm').empty();
    adoptionmanager.usermanagerController.queryProfile(function(records, e) { showProfiles(records, callback) }, {escape:true}); 
    adoptionmanager.usermanagerController.queryRole(function(records, e) { showRoles(records, callback) }, {escape:true}); 
    adoptionmanager.usermanagerController.queryUserLicense(function(records, e) { showUserLicenses(records, callback) }, {escape:true}); 
    
    //form validation
    $j("#newUserFormForm").submit(function() {
      
      var fireError = false;
      var firstName = "";
      var lastName = "";
      var email = "";
      var userLicense = "";
      var profile = "";
      var role = "";
      var sendEmail = "";
      
      $j("#errorMessageNewUser").empty();
      
      if ($j("#firstNameForm").val() == "") {
        $j("#errorMessageNewUser").append("-First name must be filled in<br />").show();
        fireError = true;
      }
      if ($j("#firstNameForm").val().length < 2) {
        $j("#errorMessageNewUser").append("-First name must be 2 digits or more<br />").show();
        fireError = true;
      }
      if ($j("#lastNameForm").val() == "") {
        $j("#errorMessageNewUser").append("-Last name must be filled in<br />").show();
        fireError = true;
      }
      if ($j("#lastNameForm").val().length <2) {
        $j("#errorMessageNewUser").append("-Last name must be 2 digits or more<br />").show();
        fireError = true;
      }
      if ($j("#emailForm").val() == "") {
        $j("#errorMessageNewUser").append("-Email must be filled in<br />").show();
        fireError = true;
      }
      if ($j("#userlicenseForm").val() == "") {
        $j("#errorMessageNewUser").append("-User license must be selected<br />").show();
        fireError = true;
      }
      if ($j("#profileForm").val() == "") {
        $j("#errorMessageNewUser").append("-Profile must be selected<br />").show();
        fireError = true;
      }
      if ($j("#roleForm").val() == "") {
        $j("#errorMessageNewUser").append("-Role must be selected<br />").show();
        fireError = true;
      }
      if(fireError==true){
      	try{
      	 $j("#errorMessageNewUser").focus();
      	}
      	catch(err){
      	 //
      	}
      	return false;
      }
      else{
      	 //no errors with submission
         firstName = $j("#firstNameForm").val();
         lastName = $j("#lastNameForm").val();
         email = $j("#emailForm").val();
         userLicense = $j("#userlicenseForm").val();
         profile = $j("#profileForm").val();
         role = $j("#roleForm").val();
         sendEmail = $j("#generatePassForm").val();
         adoptionmanager.usermanagerController.insertUser(firstName, lastName, email, profile, role, sendEmail, function(records, e) { insertUserFinal(records, callback) }, {escape:true}); 
      }
      //never return true?
      return false;
    });
}

function getSearchPage(callback) {
    $j("#searchForm").val('');
    $j("#searchUserlist").empty();
    $j('div#searchUserListDiv ul').listview('refresh');
    numSearchUsersLoaded=0;   
}

function showSearchUsers(records, callback) {
	if(records.length==0){
		alert("No records found");
		$j.mobile.hidePageLoadingMsg();
		return false;
	}
	else{
       searchUsers.length = 0;
       for(var i = 0; i < records.length; i++) { searchUsers[records[i].Id] = records[i];  }
       var textToAppend = '';
   
    $j.each(records,
        function() {
        	numSearchUsersLoaded++;
        	
        	var activeStatus = "";
        	if(this.IsActive == true){
        		activeStatus = "Active";
        	}
        	else{
        		activeStatus = "Not Active";
        	}

        textToAppend+= '<li id="'+this.Id+'" >';
        textToAppend+= '<a href="javascript:void(0)" onclick="getUserDetailsSearch(\''+this.Id+'\');">';
        textToAppend+= '<img src="' + this.SmallPhotoUrl + '" border="1" width="64" height="64" /><h3>' + htmlEscape(cleantext(this.FirstName)) + ' ' + htmlEscape(this.LastName) + '</h3><p>'+this.Email+'</p><p><strong>Login:</strong> '+numDaysString(this.LastLoginDate)+', <strong>Create:</strong> '+numDaysString(this.CreatedDate)+'</p><p>Status:  <strong>'+activeStatus+'</strong></p>';
        textToAppend+= '</a></li>';
        });


    $j('#searchUserlist').append(textToAppend).trigger('create');
    $j('div#searchUserListDiv ul').listview('refresh');
    $j.mobile.hidePageLoadingMsg();
    
    if(callback != null) {  callback(); $j('#searchUserlist').listview('refresh');  }
	}
    
}

function htmlEscape(str) {
    return String(str)
            .replace(/&/g, '&amp;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
}

function insertUserFinal(success, callback){
   if(success=="true"){
     alert('User has been created');
   }
   else{
     alert('An error occurred or you do not have the capability to create users. Error - '+success);
     return false;
   }
   
    //reset form
    $j("#firstNameForm").val('');
    $j("#lastNameForm").val('');
    $j("#emailForm").val('');
    $j("#userlicenseForm").val('');
    $j("#profileForm").val('');
    $j("#roleForm").val('');
    $j("#generatePassForm").val('');
   
    $j.mobile.showPageLoadingMsg();
    getUsers(function(){
    	//console.log('Get active users');
        $j.mobile.hidePageLoadingMsg();
    });

    $j('#mainpage').page();
    $j.mobile.changePage('#mainpage', {changeHash: true});
    //console.log('Done Creation - Before callback check');
    
    if(callback != null) { callback();  }
}


function numDays(lastLogin) {
   var today = new Date();
   var t2 = today.getTime();
   var t1 = lastLogin;
   
   if(lastLogin!=null){
      return parseInt((t2-t1)/(24*3600*1000)); 
   }
   else{
      return null;
   }
}

function numDaysString(lastLogin) {
   var today = new Date();
   var t2 = today.getTime();
   var t1 = lastLogin;
   
   if(lastLogin!=null){
      return parseInt((t2-t1)/(24*3600*1000))+" Days"; 
   }
   else{
      return "Never";
   }
}

function showUsers(records, callback) {
    currentUsers.length = 0;
    for(var i = 0; i < records.length; i++) { currentUsers[records[i].Id] = records[i]; }

    var shown120 = false;
    var shown90 = false;
    var shown60 = false;
    var shown45 = false;
    var shown30 = false;
    var shown15 = false;
    var shown0 = false;
    var shownNever = false;
    var counter = 0;
    var shownThis = false;
    var prevStatus = "";
    var textToAppend = "";

    $j.each(records,
        function() {
        	counter++;
        	//default 50 users per page block/load...if counter hits 51, stop
        	if(counter>numUsersPerBlock){
        		return false;
        	}
        	numActiveUsersLoaded++;

        //if one header was added in this round, we will not need to add another header in the same loop
        shownThis = false;
        if(shownNever == false && prevStatus!="Never"){
            if(this.LastLoginDate==null){
               if ($j("#activeNever").length < 1 && textToAppend.indexOf('id="activeNever"')<0){
               	  textToAppend+='<li data-role="list-divider" id="activeNever">Never logged in</li>';
                  shownNever=true;
                  shownThis = true;
                  //if there is a second record that comes in of the same category, don't recheck if the header exists, bc it does
                  //this primarily works if we are doing a search for the li ID and not just simply appending without checking
               }//if header exists 
               prevStatus = "Never";
            }//if never logged in
        }
        if(shown120 == false && shownThis == false && prevStatus!="120"){
            if(numDays(this.LastLoginDate)>=120){
               if ($j("#active120").length < 1 && textToAppend.indexOf('id="active120"')<0){
               	  textToAppend+='<li data-role="list-divider" id="active120">120 Days or more</li>';
                  shown120=true;
                  shownThis = true;
               }//if header exists 
               prevStatus = "120";
            }
        }
        if(shown90 == false && shownThis == false && prevStatus!="90"){
            if(numDays(this.LastLoginDate)<120 && numDays(this.LastLoginDate)>=90){
            	if ($j("#active90").length < 1 && textToAppend.indexOf('id="active90"')<0){
                  textToAppend+='<li data-role="list-divider" id="active90">90 Days or more</li>';
                  shown90=true;
                  shownThis = true;
               }//if header exists 
               prevStatus = "90";
            }
        }
        if(shown60 == false && shownThis == false && prevStatus!="60"){
            if(numDays(this.LastLoginDate)<90 && numDays(this.LastLoginDate)>=60){
            	if ($j("#active60").length < 1 && textToAppend.indexOf('id="active60"')<0){
            		textToAppend+='<li data-role="list-divider" id="active60">60 Days or more</li>';
                  shown60=true;
                  shownThis = true;
               }//if header exists 
               prevStatus = "60";
            }
        }
        if(shown45 == false && shownThis == false && prevStatus!="45"){
            if(numDays(this.LastLoginDate)<60 && numDays(this.LastLoginDate)>=45){
            	if ($j("#active45").length < 1 && textToAppend.indexOf('id="active45"')<0){
            		textToAppend+='<li data-role="list-divider" id="active45">45 Days or more</li>';
                  shown45=true;
                  shownThis = true;
               }//if header exists 
               prevStatus = "45";  
            }
        }
        if(shown30 == false && shownThis == false && prevStatus!="30"){
            if(numDays(this.LastLoginDate)<45 && numDays(this.LastLoginDate)>=30){
            	if ($j("#active30").length < 1 && textToAppend.indexOf('id="active30"')<0){
            		textToAppend+='<li data-role="list-divider" id="active30">30 Days or more</li>';
                  shown30=true;
                  shownThis = true;
               }//if header exists 
               prevStatus = "30";  
            }
        }
        if(shown15 == false && shownThis == false && prevStatus!="15"){
            if(numDays(this.LastLoginDate)<30 && numDays(this.LastLoginDate)>=15){
            	if ($j("#active15").length < 1 && textToAppend.indexOf('id="active15"')<0){
            		textToAppend+='<li data-role="list-divider" id="active15">15 Days or more</li>';
                  shown15=true;
                  shownThis = true;
               }//if header exists 
               prevStatus = "15";  
            }
        }
        if(shown0 == false && shownThis == false && prevStatus!="0"){
            if(numDays(this.LastLoginDate)<15 && this.LastLoginDate!=null){
            	if ($j("#active0").length < 1 && textToAppend.indexOf('id="active0"')<0){
            		textToAppend+='<li data-role="list-divider" id="active0">15 Days or less</li>';
                  shown0=true;
               shownThis = true;
               }//if header exists 
               prevStatus = "0";
            }
        }
        
        textToAppend+= '<li id="'+this.Id+'" >';
        textToAppend+= '<a href="javascript:void(0)" onclick="getUserDetailsActive(\''+this.Id+'\');">';
        textToAppend+= '<img src="' + this.SmallPhotoUrl + '" border="1" width="64" height="64" /><h3>' + htmlEscape(cleantext(this.FirstName)) + ' ' + htmlEscape(this.LastName) + '</h3><p>'+this.Email+'</p><p><strong>Login:</strong> '+numDaysString(this.LastLoginDate)+', <strong>Create:</strong> '+numDaysString(this.CreatedDate)+'</p>';
        textToAppend+= '</a></li>';
        });
        
        $j('#userlist').append(textToAppend).trigger('create');
        
    //get rid of old more records LI and add new one on bottom
    $j('#showMoreRecords').remove();
    //only show if there are more records to show
    if(numActiveUsersLoaded<activeUsersRecords.length){
       $j('#userlist').append('<li id="showMoreRecords"><a href="javascript:void(0)" onclick="getUsersSubset();">Show more records</a></li>').trigger('create');;
    }
    $j('#activeUsersHeader').html(activeUsersRecords.length).show();

    $j('div#userListDiv ul').listview('refresh');
    
    $j.mobile.hidePageLoadingMsg();
    
    if(callback != null) {  callback(); $j('#userlist').listview('refresh');  }
}


function showInactiveUsers(records, callback) {
    inactiveUsers.length = 0;
    for(var i = 0; i < records.length; i++) { inactiveUsers[records[i].Id] = records[i]; }
    
    var counter2 = 0;
    var textToAppend = '';
   

    $j.each(records,
        function() {
            counter2++;
        	//default 50 users per page block/load...if counter hits 51, stop
        	if(counter2>numUsersPerBlock){
        		return false;
        	}
        	numInactiveUsersLoaded++;
        
        textToAppend+= '<li id="'+this.Id+'" >';
        textToAppend+= '<a href="javascript:void(0)" onclick="getUserDetailsInactive(\''+this.Id+'\');">';
        textToAppend+= '<img src="' + this.SmallPhotoUrl + '" border="1" width="64" height="64" /><h3>' + htmlEscape(cleantext(this.FirstName)) + ' ' + htmlEscape(this.LastName) + '</h3><p>'+this.Email+'</p><p><strong>Login:</strong> '+numDaysString(this.LastLoginDate)+', <strong>Create:</strong> '+numDaysString(this.CreatedDate)+'</p>';
        textToAppend+= '</a></li>';
        });


    $j('#inactiveuserlist').append(textToAppend).trigger('create');
    $j('#inactiveUsersHeader').html(inactiveUsersRecords.length).show();
    
    $j('#showMoreRecordsInactive').remove();
    if(numInactiveUsersLoaded<inactiveUsersRecords.length){
       $j('#inactiveuserlist').append('<li id="showMoreRecordsInactive"><a href="javascript:void(0)" onclick="getUsersInactiveSubset();">Show more records</a></li>').trigger('create');;
    }
    
    $j('div#inactiveuserListDiv ul').listview('refresh');
    $j.mobile.hidePageLoadingMsg();
    if(callback != null) {  callback(); $j('#inactiveuserlist').listview('refresh');  }
}

function showNeverUsers(records, callback) {
    neverUsers.length = 0;
    for(var i = 0; i < records.length; i++) { neverUsers[records[i].Id] = records[i]; }
    
    var counter2 = 0;
    var textToAppend = '';

    $j.each(records,
        function() {
            counter2++;
        	//default 50 users per page block/load...if counter hits 51, stop
        	if(counter2>numUsersPerBlock){
        		return false;
        	}
        	numNeverUsersLoaded++;
        
        textToAppend+= '<li id="'+this.Id+'" >';
        textToAppend+= '<a href="javascript:void(0)" onclick="getUserDetailsNever(\''+this.Id+'\');">';
        textToAppend+= '<img src="' + this.SmallPhotoUrl + '" border="1" width="64" height="64" /><h3>' + htmlEscape(cleantext(this.FirstName)) + ' ' + htmlEscape(this.LastName) + '</h3><p>'+this.Email+'</p><p><strong>Login:</strong> '+numDaysString(this.LastLoginDate)+', <strong>Create:</strong> '+numDaysString(this.CreatedDate)+'</p>';
        textToAppend+= '</a></li>';
        });


    $j('#neveruserlist').append(textToAppend).trigger('create');
    $j('#neverUsersHeader').html(neverUsersRecords.length).show();
    
    $j('#showMoreRecordsNever').remove();
    if(numNeverUsersLoaded<neverUsersRecords.length){
       $j('#neveruserlist').append('<li id="showMoreRecordsNever"><a href="javascript:void(0)" onclick="getUsersNeverSubset();">Show more records</a></li>').trigger('create');;
    }
    
    $j('div#neveruserListDiv ul').listview('refresh');
    
    $j.mobile.hidePageLoadingMsg();
    
    if(callback != null) {  callback(); $j('#neveruserlist').listview('refresh');  }
}

function getUserDetailsActive(userId){
            $j.mobile.showPageLoadingMsg();
            //alert(currentUsers[userId].IsActive);
            $j('#UserFullName').html(cleantext(currentUsers[userId].FirstName) + ' ' + currentUsers[userId].LastName);
            $j('#UserUsername').html(currentUsers[userId].Username);
            $j('#UserDaysSinceLogin').html(numDaysString(currentUsers[userId].LastLoginDate));
            $j('#UserDaysSinceCreated').html(numDays(currentUsers[userId].CreatedDate));
            $j('#UserDepartment').html(currentUsers[userId].Department);
            $j('#UserDivision').html(currentUsers[userId].Division);
            $j('#UserCompanyName').html(currentUsers[userId].CompanyName);
            $j('#UserStreet').html(currentUsers[userId].Street);
            $j('#UserCity').html(currentUsers[userId].City);
            $j('#UserState').html(currentUsers[userId].State);
            $j('#UserPostalCode').html(currentUsers[userId].PostalCode);
            $j('#UserCountry').html(currentUsers[userId].Country);
            $j('#UserTitle').html(currentUsers[userId].Title);
            if(currentUsers[userId].ProfileId!=null){
               $j('#UserProfile').html(currentUsers[userId].Profile.Name);
               }
            if(currentUsers[userId].UserRoleId!=null){
               $j('#UserRole').html(currentUsers[userId].UserRole.Name);
            }   
            $j('#UserId').val(currentUsers[userId].Id);
            $j('#UserEmail').html('<a href="mailto:'+currentUsers[userId].Email+'?subject=Salesforce.com Inactivity">'+currentUsers[userId].Email+'</a>');
            $j('#UserPhone').html('<a href="tel:'+cleantext(currentUsers[userId].Phone)+'">'+cleantext(currentUsers[userId].Phone)+'</a>');
            
            $j('#UserMobilePhone').html('<a href="tel:'+cleantext(currentUsers[userId].MobilePhone)+'">'+cleantext(currentUsers[userId].MobilePhone)+'</a>');
            $j('#UserFullPicture').html('<img src="'+currentUsers[userId].FullPhotoUrl+'" border="1">');
 
            $j('#EmailUserNavHref').attr('href','mailto:'+currentUsers[userId].Email+'?subject=Salesforce.com Inactivity');
            
            if(currentUsers[userId].IsActive==true){
               $j('#deactivateLink').attr('href','#deactivateDialog');
               $j('#deactivateLink').text('Deactivate');
               $j('#userDetailBack').attr('href','#mainpage');
               $j('#userDetailBack').text('Active');
            }
            else{
            	$j('#deactivateLink').attr('href','#activateDialog');
                $j('#deactivateLink').text('Activate');
                $j('#userDetailBack').attr('href','#inactivepage');
                $j('#userDetailBack').text('Inactive');
            }
            
            $j.mobile.hidePageLoadingMsg();
            
            $j.mobile.changePage('#userdetailpage', {changeHash: true});
            
}

function getUserDetailsNever(userId){
            $j.mobile.showPageLoadingMsg();
            //alert(neverUsers[userId].IsActive);
            $j('#UserFullName').html(cleantext(neverUsers[userId].FirstName) + ' ' + neverUsers[userId].LastName);
            $j('#UserUsername').html(neverUsers[userId].Username);
            $j('#UserDaysSinceLogin').html(numDaysString(neverUsers[userId].LastLoginDate));
            $j('#UserDaysSinceCreated').html(numDays(neverUsers[userId].CreatedDate));
            $j('#UserDepartment').html(neverUsers[userId].Department);
            $j('#UserDivision').html(neverUsers[userId].Division);
            $j('#UserCompanyName').html(neverUsers[userId].CompanyName);
            $j('#UserStreet').html(neverUsers[userId].Street);
            $j('#UserCity').html(neverUsers[userId].City);
            $j('#UserState').html(neverUsers[userId].State);
            $j('#UserPostalCode').html(neverUsers[userId].PostalCode);
            $j('#UserCountry').html(neverUsers[userId].Country);
            $j('#UserTitle').html(neverUsers[userId].Title);
            if(neverUsers[userId].ProfileId!=null){
               $j('#UserProfile').html(neverUsers[userId].Profile.Name);
               }
            if(neverUsers[userId].UserRoleId!=null){
               $j('#UserRole').html(neverUsers[userId].UserRole.Name);
            }   
            $j('#UserId').val(neverUsers[userId].Id);
            $j('#UserEmail').html('<a href="mailto:'+neverUsers[userId].Email+'?subject=Salesforce.com Inactivity">'+neverUsers[userId].Email+'</a>');
            $j('#UserPhone').html('<a href="tel:'+cleantext(neverUsers[userId].Phone)+'">'+cleantext(neverUsers[userId].Phone)+'</a>');
            
            $j('#UserMobilePhone').html('<a href="tel:'+cleantext(neverUsers[userId].MobilePhone)+'">'+cleantext(neverUsers[userId].MobilePhone)+'</a>');
            $j('#UserFullPicture').html('<img src="'+neverUsers[userId].FullPhotoUrl+'" border="1">');
 
            $j('#EmailUserNavHref').attr('href','mailto:'+neverUsers[userId].Email+'?subject=Salesforce.com Inactivity');

            $j('#deactivateLink').attr('href','#deactivateNeverDialog');
            $j('#deactivateLink').text('Deactivate');
            $j('#userDetailBack').attr('href','#mainpage');
            $j('#userDetailBack').text('Active');

            $j.mobile.hidePageLoadingMsg();
            
            $j.mobile.changePage('#userdetailpage', {changeHash: true});
            
}

function getUserDetailsInactive(userId){
            $j.mobile.showPageLoadingMsg();
            $j('#UserFullName').html(cleantext(inactiveUsers[userId].FirstName) + ' ' + inactiveUsers[userId].LastName);
            $j('#UserUsername').html(inactiveUsers[userId].Username);
            $j('#UserDaysSinceLogin').html(numDaysString(inactiveUsers[userId].LastLoginDate));
            $j('#UserDaysSinceCreated').html(numDays(inactiveUsers[userId].CreatedDate));
            $j('#UserDepartment').html(inactiveUsers[userId].Department);
            $j('#UserDivision').html(inactiveUsers[userId].Division);
            $j('#UserCompanyName').html(inactiveUsers[userId].CompanyName);
            $j('#UserStreet').html(inactiveUsers[userId].Street);
            $j('#UserCity').html(inactiveUsers[userId].City);
            $j('#UserState').html(inactiveUsers[userId].State);
            $j('#UserPostalCode').html(inactiveUsers[userId].PostalCode);
            $j('#UserCountry').html(inactiveUsers[userId].Country);
            $j('#UserTitle').html(inactiveUsers[userId].Title);
            if(inactiveUsers[userId].ProfileId!=null){
               $j('#UserProfile').html(inactiveUsers[userId].Profile.Name);
               }
            if(inactiveUsers[userId].UserRoleId!=null){
               $j('#UserRole').html(inactiveUsers[userId].UserRole.Name);
            }   
            $j('#UserId').val(inactiveUsers[userId].Id);
            $j('#UserEmail').html('<a href="mailto:'+inactiveUsers[userId].Email+'?subject=Salesforce.com Inactivity">'+inactiveUsers[userId].Email+'</a>');
            $j('#UserPhone').html('<a href="tel:'+cleantext(inactiveUsers[userId].Phone)+'">'+cleantext(inactiveUsers[userId].Phone)+'</a>');
            
            $j('#UserMobilePhone').html('<a href="tel:'+cleantext(inactiveUsers[userId].MobilePhone)+'">'+cleantext(inactiveUsers[userId].MobilePhone)+'</a>');
            $j('#UserFullPicture').html('<img src="'+inactiveUsers[userId].FullPhotoUrl+'" border="1">');
 
            $j('#EmailUserNavHref').attr('href','mailto:'+inactiveUsers[userId].Email+'?subject=Salesforce.com Inactivity');
            
            if(inactiveUsers[userId].IsActive==true){
               $j('#deactivateLink').attr('href','#deactivateDialog');
               $j('#deactivateLink').text('Deactivate');
               $j('#userDetailBack').attr('href','#mainpage');
               $j('#userDetailBack').text('Active');
            }
            else{
            	$j('#deactivateLink').attr('href','#activateDialog');
                $j('#deactivateLink').text('Activate');
                $j('#userDetailBack').attr('href','#inactivepage');
                $j('#userDetailBack').text('Inactive');
            }

            $j.mobile.hidePageLoadingMsg();
            $j.mobile.changePage('#userdetailpage', {changeHash: true});
            
}

function getUserDetailsSearch(userId){
            $j.mobile.showPageLoadingMsg();
            $j('#UserFullName').html(cleantext(searchUsers[userId].FirstName) + ' ' + searchUsers[userId].LastName);
            $j('#UserUsername').html(searchUsers[userId].Username);
            $j('#UserDaysSinceLogin').html(numDaysString(searchUsers[userId].LastLoginDate));
            $j('#UserDaysSinceCreated').html(numDays(searchUsers[userId].CreatedDate));
            $j('#UserDepartment').html(searchUsers[userId].Department);
            $j('#UserDivision').html(searchUsers[userId].Division);
            $j('#UserCompanyName').html(searchUsers[userId].CompanyName);
            $j('#UserStreet').html(searchUsers[userId].Street);
            $j('#UserCity').html(searchUsers[userId].City);
            $j('#UserState').html(searchUsers[userId].State);
            $j('#UserPostalCode').html(searchUsers[userId].PostalCode);
            $j('#UserCountry').html(searchUsers[userId].Country);
            $j('#UserTitle').html(searchUsers[userId].Title);
            if(searchUsers[userId].ProfileId!=null){
               $j('#UserProfile').html(searchUsers[userId].Profile.Name);
               }
            if(searchUsers[userId].UserRoleId!=null){
               $j('#UserRole').html(searchUsers[userId].UserRole.Name);
            }   
            $j('#UserId').val(searchUsers[userId].Id);
            $j('#UserEmail').html('<a href="mailto:'+searchUsers[userId].Email+'?subject=Salesforce.com Inactivity">'+searchUsers[userId].Email+'</a>');
            $j('#UserPhone').html('<a href="tel:'+cleantext(searchUsers[userId].Phone)+'">'+cleantext(searchUsers[userId].Phone)+'</a>');
            
            $j('#UserMobilePhone').html('<a href="tel:'+cleantext(searchUsers[userId].MobilePhone)+'">'+cleantext(searchUsers[userId].MobilePhone)+'</a>');
            $j('#UserFullPicture').html('<img src="'+searchUsers[userId].FullPhotoUrl+'" border="1">');
 
            $j('#EmailUserNavHref').attr('href','mailto:'+searchUsers[userId].Email+'?subject=Salesforce.com Inactivity');
            
            if(searchUsers[userId].IsActive==true){
               $j('#deactivateLink').attr('href','#deactivateDialog');
               $j('#deactivateLink').text('Deactivate');
            }
            else{
            	$j('#deactivateLink').attr('href','#activateDialog');
                $j('#deactivateLink').text('Activate');
            }
            $j('#userDetailBack').attr('href','#searchpage');
            $j('#userDetailBack').text('Search');

            $j.mobile.hidePageLoadingMsg();
            $j.mobile.changePage('#userdetailpage', {changeHash: true});
            
}

function showProfiles(records, callback) {
    profiles.length = 0;
    for(var i = 0; i < records.length; i++) { profiles[records[i].Id] = records[i]; }

    $j.each(records,
        function() {
        $j('#profileForm').append('<option></option>');
        $j('#profileForm option:last')
        .attr('value',this.Id)
        .html(cleantext(this.Name))
        .appendTo('#profileForm');
        
        $j('#profileForm').selectmenu('refresh', true);
        });
    if(callback != null) {  callback(); $j('#profileForm').selectmenu('refresh', true);  }
}

function showRoles(records, callback) {
    userRoles.length = 0;
    for(var i = 0; i < records.length; i++) { userRoles[records[i].Id] = records[i]; }

    $j.each(records,
        function() {
        $j('#roleForm').append('<option></option>');
        $j('#roleForm option:last')
        .attr('value',this.Id)
        .html(cleantext(this.Name))
        .appendTo('#roleForm');
        
        $j('#roleForm').selectmenu('refresh', true);
        });
    if(callback != null) {  callback(); $j('#roleForm').selectmenu('refresh', true);  }
}


function showUserLicenses(records, callback) {
    userLicenses.length = 0;
    for(var i = 0; i < records.length; i++) { userLicenses[records[i].Id] = records[i]; }

    $j.each(records,
        function() {
        $j('#userlicenseForm').append('<option></option>');
        $j('#userlicenseForm option:last')
        .attr('value',this.Id)
        .html(cleantext(this.Name))
        .appendTo('#userlicenseForm');
        
        $j('#userlicenseForm').selectmenu('refresh', true);
        });
    if(callback != null) {  callback(); $j('#userlicenseForm').selectmenu('refresh', true);  }
}

function cleantext(thisText){
   if(thisText==null){
      thisText='';
   }
   return thisText;
}

function deactivateUser(){
   $j.mobile.showPageLoadingMsg();
   adoptionmanager.usermanagerController.deactivateUser($j('#UserId').val(), function(success, e) { deactivateUserFinal(success, $j.mobile.hidePageLoadingMsg()) }, {escape:true}); 
   return true;
}

function deactivateUserFinal(success, callback){
   if(success=="true"){
     alert('User has been deactivated');
     $j('#activeUsersHeader').html(parseInt($j('#activeUsersHeader').html())-1).show();
     $j.mobile.changePage('#mainpage', {changeHash: true});

    if($j('#' + $j('#UserId').val()).prev().attr('data-role')=='list-divider' && $j('#' + $j('#UserId').val()).next().attr('data-role')=='list-divider'){
    	//if there is a list divider before and after the item being removed, it means it is the only one in the category, so therefore remove the category
    	$j('#' + $j('#UserId').val()).prev().remove();
    }
    if($j('#' + $j('#UserId').val()).prev().attr('data-role')=='list-divider' && $j('#' + $j('#UserId').val())==$j('#activeuserlist li:last')){
    	//if there is a list divider before the item and there are no items after it, delete the previous header
    	$j('#' + $j('#UserId').val()).prev().remove();
    }
    
    $j('#' + $j('#UserId').val()).remove();
    
    $j.mobile.showPageLoadingMsg();
    getInactiveUsers(function(){
        $j.mobile.hidePageLoadingMsg();
    });
    
    $j.mobile.showPageLoadingMsg();
    getSearchPage(function(){
        $j.mobile.hidePageLoadingMsg();
    });
    
    $j('#userlist').listview('refresh');

    $j('#mainpage').page();
   }
   else{
     alert('An error occurred or you do not have the capability to deactivate users. Error - '+success);
     $j.mobile.changePage('#mainpage', {changeHash: true});
   }

   if(callback != null) {  callback(); }
}

function deactivateNeverUser(){
   $j.mobile.showPageLoadingMsg();
   adoptionmanager.usermanagerController.deactivateUser($j('#UserId').val(), function(success, e) { deactivateNeverUserFinal(success, $j.mobile.hidePageLoadingMsg()) }, {escape:true}); 
   return true;
}

function deactivateNeverUserFinal(success, callback){
   if(success=="true"){
     alert('User has been deactivated');
     $j('#neverUsersHeader').html(parseInt($j('#neverUsersHeader').html())-1).show();
     $j.mobile.changePage('#neverpage', {changeHash: true});

    $j('#' + $j('#UserId').val()).remove();
    
    $j.mobile.showPageLoadingMsg();
    getInactiveUsers(function(){
        $j.mobile.hidePageLoadingMsg();
    });
    
    $j.mobile.showPageLoadingMsg();
    getSearchPage(function(){
        $j.mobile.hidePageLoadingMsg();
    });
    
    $j('#neveruserlist').listview('refresh');
    //$j('#activeUsersHeader').html(parseInt($j('#activeUsersHeader').html())-1).show();
    
    $j('#neverpage').page();
   }
   else{
     alert('An error occurred or you do not have the capability to deactivate users. Error - '+success);
     $j.mobile.changePage('#neverpage', {changeHash: true});
   }

   if(callback != null) {  callback(); }
}

function activateUser(){
   $j.mobile.showPageLoadingMsg();
   //console.log('Calling Controller ActivateUser');
   adoptionmanager.usermanagerController.activateUser($j('#UserId').val(), function(success, e) { activateUserFinal(success, $j.mobile.hidePageLoadingMsg()) }, {escape:true}); 
   return true;
}

function activateUserFinal(success, callback){
   if(success=="true"){
     alert('User has been activated and notified by email with new password');
     $j('#inactivepage').page();
    $j('#mainpage').page();
    $j('#inactiveUsersHeader').html(parseInt($j('#inactiveUsersHeader').html())-1).show();
    $j.mobile.changePage('#inactivepage', {changeHash: true});
   
    
    $j('#' + $j('#UserId').val()).remove();
    
    $j.mobile.showPageLoadingMsg();
    getUsers(function(){
        $j.mobile.hidePageLoadingMsg();
    });
    
    //TODO: Find a way to prevent 2 queries
    $j.mobile.showPageLoadingMsg();
    getNeverUsers(function(){
        $j.mobile.hidePageLoadingMsg();
    });
    
    $j.mobile.showPageLoadingMsg();
    getSearchPage(function(){
        $j.mobile.hidePageLoadingMsg();
    });
    
    $j('#userlist').listview('refresh');
    
    $j('#mainpage').page();
    $j('#inactivepage').page();
   }
   else{
     alert('An error occurred or you do not have the capability to activate users.  Error - '+success);
     $j.mobile.changePage('#inactivepage', {changeHash: true});
   }

    if(callback != null) {  callback();  }
}

function sortList(listName){
	//sort list alphabetically
	var mylist = $j('#'+listName);
    var listitems = mylist.children('li').get();
    listitems.sort(function(a, b) {
       var compA = $j(a).text().toUpperCase();
       var compB = $j(b).text().toUpperCase();
       return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
    })
    $j.each(listitems, function(idx, itm) { mylist.append(itm); });
}

Tags: , , , , , , , ,
Posted in Salesforce Mobile, VisualForce, Web Development | Comments Off on Free JQuery Mobile Adoption Manager JavaScript Code

Sorry, comments for this entry are closed at this time.