 /************************************************************
          DEBUG FUNCTION
            * To see the debug output use DebugView
 ************************************************************/
function debug(message)
{
    if (message == null)
    {
        System.Debug.outputString("null");
    }
    else
    {
        System.Debug.outputString(message);
    }
}


/************************************************************
          MESSENGERGADGET OBJECT - CONSTRUCTORVER
 ************************************************************/
MessengerGadget = function(gadgetContainer)
{
	// initialize HTML Elements variables   by reference
	this.middle = document.getElementById("middle");
	this.top = document.getElementById("top");
	this.bottom = document.getElementById("bottom");
	this.body = document.body;
	
    var self = this;
	
	// CREATE SIGN-IN DIV
	this.divSignIn = document.createElement("div");
	this.divSignIn.className = "MessengerGadget_SignInArea";
	gadgetContainer.appendChild(this.divSignIn);
	
	// add sign-in button
	this.buttonSignIn = document.createElement("button");
	this.buttonSignIn.onclick = function() {self.onClickSignIn()};
	this.buttonSignIn.innerHTML = GadgetLocalizedConstants.LOC_SIGN_IN;
	this.divSignIn.appendChild(this.buttonSignIn);
	
	// add sign-in error
	this.divSignInError = document.createElement("div");
	this.divSignInError.className = "MessengerGadget_SignInError";
	this.divSignIn.appendChild(this.divSignInError);
	
	// CREATE STATUS DROP-DOWN
	this.statusDropDown = new StatusDropDownObj();
	this.statusDropDown.addOption(new OptionObj(GadgetLocalizedConstants.LOC_STATUS_ONLINE, MessengerConstants.MISTATUS_ONLINE));
	this.statusDropDown.addOption(new OptionObj(GadgetLocalizedConstants.LOC_STATUS_BUSY, MessengerConstants.MISTATUS_BUSY));
	this.statusDropDown.addOption(new OptionObj(GadgetLocalizedConstants.LOC_STATUS_BE_RIGHT_BACK, MessengerConstants.MISTATUS_BE_RIGHT_BACK));
	this.statusDropDown.addOption(new OptionObj(GadgetLocalizedConstants.LOC_STATUS_AWAY, MessengerConstants.MISTATUS_AWAY));
	this.statusDropDown.addOption(new OptionObj(GadgetLocalizedConstants.LOC_STATUS_IN_A_CALL, MessengerConstants.MISTATUS_ON_THE_PHONE));
	this.statusDropDown.addOption(new OptionObj(GadgetLocalizedConstants.LOC_STATUS_OUT_TO_LUNCH, MessengerConstants.MISTATUS_OUT_TO_LUNCH));
	this.statusDropDown.addOption(new OptionObj(GadgetLocalizedConstants.LOC_STATUS_INVISIBLE, MessengerConstants.MISTATUS_INVISIBLE));
	this.statusDropDown.addOption(new OptionObj(GadgetLocalizedConstants.LOC_STATUS_SIGN_OUT, MessengerConstants.MISTATUS_OFFLINE));
	this.statusDropDown.onclick = function() {self.onChangeMyStatus()};
	gadgetContainer.appendChild(this.statusDropDown.getDiv());
	
	this.updateMyStatusAndFriendlyName();
	
	// CREATE TOOLTIP DIV
	this.contactTooltip = new TooltipObj(true);
	
	// CREATE CONTACT AREA
	this.contactArea = document.createElement("div");
	this.contactArea.className = "contactArea";
	gadgetContainer.appendChild(this.contactArea);
	
	// create contact list area (visible area)
	this.contactListArea = document.createElement("div");
	this.contactListArea.className = "contactListArea";
	this.contactArea.appendChild(this.contactListArea);
	
	// create contact list div
	this.contactList = document.createElement("div");
	this.contactList.className = "contactList";
	this.contactListArea.appendChild(this.contactList);
	
	// add scrollbar
	this.contactListScrollBar = new ScrollBarObj(this.contactListArea, this.contactList);

	// other variables
    this.offlineInterval = null; //used to verify if Messenger is still runing
    this.tooltipTimer = null; //used to show tooltip after onMouseOver the contact
    this.updateAvailable = false;
	
	// create a global MessengerGadgetService object
	this.gadgetWebService = new MessengerGadgetWebService();

    // gadget plumbing
    System.Gadget.settingsUI = "settings.html";
    System.Gadget.onSettingsClosed = function() { self.onSettingsClosed() };
    System.Gadget.Flyout.onHide = function() { self.onFlyoutClosed() };
	
	// Check if x64 PROCESSOR_ARCHITECTURE
	var envPath = System.Environment.getEnvironmentVariable("PROCESSOR_ARCHITECTURE");
	//debug(envPath);
	if (envPath != "x86")
	{
		this.divSignInError.style.display = "block";
		this.divSignInError.innerHTML = GadgetLocalizedConstants.LOC_X64_ERROR;
		this.divSignInError.title = GadgetLocalizedConstants.LOC_X64_ERROR;
		
		this.buttonSignIn.disabled = true;	
	}
	else
	{
		debug("Running on x86 process... Good to go!");
	}
	
	// Add email counter
	this.emailCounter = new EmailCounterObj();
	this.emailCounter.ondblclick =  function() { self.onDoubleClickEmailCounter() };
	this.emailCounter.setTitle(GadgetLocalizedConstants.LOC_EMAIL_COUNTER_INSTRUCTIONS);
	gadgetContainer.appendChild(this.emailCounter.getDiv());
	this.updateEmailCounter();
	
	// load gadget settings from registry
	this.gadgetSettings = new MessengerGadgetSettingsObj();
	this.gadgetSettings.loadGadgetSettings();
	this.updateGadgetAppearance();
	
	// signIn is shown by default so switch to contact list view if connected
	try
	{
		if (MessengerConstants.MISTATUS_OFFLINE != messenger.MyStatus)
		{
			// shows the contact list, loads user settings and generates contact list
			this.showContactList();
		}
	}
	catch (ex)
	{
		debug("MessengerGadget(" + gadgetContainer + ") exception thrown: " + ex);
	}
	
	this.updateBar = new InfoBarObj(this.contactArea, GadgetLocalizedConstants.LOC_UPDATE_AVAILABLE);
	this.updateBar.onclick = function() { self.onClickUpdateBar() };
	this.updateBar.resizeDiv = this.contactListArea;
	
	// In case the user clicks the sign-in button and the messenger is not running it will reload the page and here it will sign-in
	if (System.Gadget.Settings.readString("autoSignIn") ==  "true")
	{
		debug("found reload");
		System.Gadget.Settings.writeString("autoSignIn", "false");
		this.onClickSignIn();
	}
	
	if (this.gadgetSettings.gadgetGetUpdateNotifications)
	{
		// Fix to show info bar
		setTimeout(function() { self.gadgetWebService.checkForUpdate(System.Gadget.version, self.onUpdateCheckCompleted)}, GadgetConstants.CHECK_UPDATE_AVAILABLE_DELAY);
	}
	
	
}

/**********************************************************************************
 * Parameters:
 *   <status> - contact's status
 * 
 * Description:
 *   Returns true if the status received is not connected. 
 **********************************************************************************/
MessengerGadget.isOfflineStatus = function(status)
{
    return (MessengerConstants.MISTATUS_LOCAL_FINDING_SERVER <= status || MessengerConstants.MISTATUS_OFFLINE >= status);
}

/**********************************************************************************
 * Parameters:
 *   <p> - d
 * 
 * Description:
 *   D. 
 **********************************************************************************/
MessengerGadget.isMsgrRunning = function()
{
	var objWMIService = GetObject("winmgmts:\\\\.\\root\\CIMV2");
    var colItems = objWMIService.ExecQuery("SELECT * FROM Win32_Process WHERE Name = 'msnmsgr.exe'", "WQL", WMIConstants.WBEM_FLAG_RETURN_INMMEDIATELY | WMIConstants.WBEM_FLAG_FORWARD_ONLY);
    var enumItems = new Enumerator(colItems);
    return !enumItems.atEnd();
}

/**********************************************************************************
 * Parameters:
 *   <p> - d
 * 
 * Description:
 *   D. 
 **********************************************************************************/
MessengerGadget.insertEmoticons = function(text, containerDiv)
{
	containerDiv.innerHTML = "";
    for (var emoticonString in EmoticonConstants)
	{
		///TODO: Make this more efficient
		var tempRegExp = new RegExp(emoticonString, "i");
		while (text.search(tempRegExp) > -1)
		{
			text = text.replace(tempRegExp, "<img src=\"/icons/emoticons/" + EmoticonConstants[emoticonString] +  ".png\" style=\"vertical-align:middle\" height=16 width=16 />");
		}
	}
	
	// Match text
	var regex = /<img[^>]+\/>/g; 
	var lastIndex = 0;
	var arr;
	while ((arr = regex.exec(text)) != null)
	{
		containerDiv.appendChild(document.createTextNode(text.substring(lastIndex, arr.index)));
		containerDiv.innerHTML += arr;
		lastIndex = arr.lastIndex;
	}
	containerDiv.appendChild(document.createTextNode(text.substring(lastIndex, text.length)));
}

/**********************************************************************************
 * Parameters:
 *   <statusConst> - a constant representing a status
 * 
 * Description:
 *   Returns the text that represents the received status constant. 
 **********************************************************************************/
MessengerGadget.getStatusTextFromConstant = function(statusConst)
{
    switch(statusConst)
    {
        case MessengerConstants.MISTATUS_ONLINE:
            return GadgetLocalizedConstants.LOC_STATUS_ONLINE;
        case MessengerConstants.MISTATUS_BUSY:
            return GadgetLocalizedConstants.LOC_STATUS_BUSY;
        case MessengerConstants.MISTATUS_BE_RIGHT_BACK:
            return GadgetLocalizedConstants.LOC_STATUS_BE_RIGHT_BACK;
        case MessengerConstants.MISTATUS_IDLE:
            return GadgetLocalizedConstants.LOC_STATUS_AWAY;
        case MessengerConstants.MISTATUS_AWAY:
            return GadgetLocalizedConstants.LOC_STATUS_AWAY;
        case MessengerConstants.MISTATUS_ON_THE_PHONE:
            return GadgetLocalizedConstants.LOC_STATUS_IN_A_CALL;
        case MessengerConstants.MISTATUS_OUT_TO_LUNCH:
            return GadgetLocalizedConstants.LOC_STATUS_OUT_TO_LUNCH;
        case MessengerConstants.MISTATUS_INVISIBLE:
            return GadgetLocalizedConstants.LOC_STATUS_INVISIBLE;
        case MessengerConstants.MISTATUS_OFFLINE:
            return GadgetLocalizedConstants.LOC_STATUS_SIGN_OUT;
        case MessengerConstants.MISTATUS_UNKNOWN:
            return GadgetLocalizedConstants.LOC_STATUS_UNKNOWN;
        case MessengerConstants.MISTATUS_LOCAL_FINDING_SERVER:
            return GadgetLocalizedConstants.LOC_STATUS_FINDING_SERVER;
        case MessengerConstants.MISTATUS_LOCAL_CONNECTING_TO_SERVER:
            return GadgetLocalizedConstants.LOC_STATUS_CONNECTING;
        case MessengerConstants.MISTATUS_LOCAL_SYNCHRONIZING_WITH_SERVER:
            return GadgetLocalizedConstants.LOC_STATUS_SYNCHRONIZING;
        case MessengerConstants.MISTATUS_LOCAL_DISCONNECTING_FROM_SERVER:
            return GadgetLocalizedConstants.LOC_STATUS_DISCONNECTING;
        default:
            return GadgetLocalizedConstants.LOC_ERROR;
    }  
}

/************************************************************
          MESSENGERGADGET OBJECT - MEMBERS
 ************************************************************/
MessengerGadget.prototype =
{   
    updateGadgetAppearance:function()
    {      
        this.top.src = GadgetConstants.BG_IMAGES_PATH + "Top-" + this.gadgetSettings.gadgetColor + GadgetConstants.BG_IMAGES_EXTENSION;
        
    	var bodyHeight = this.body.currentStyle.height;
        bodyHeight = Number(bodyHeight.replace(/px/, ""));        

        var heightDelta = this.gadgetSettings.gadgetHeight - bodyHeight;
	    var contactListDiff = 0;
        this.body.style.pixelHeight = bodyHeight + heightDelta;
	    
		if (this.updateBar != undefined)
		{
			updateBarHeight = this.updateBar.height
		}
		else
		{
			updateBarHeight = 0;
		}
	    this.contactListArea.style.pixelHeight = this.body.style.pixelHeight - (SettingsConstants.DEFAULT_GADGET_SIZE - SettingsConstants.DEFAULT_CONTACTLIST_SIZE) - updateBarHeight; 
	    this.contactArea.style.pixelHeight = this.body.style.pixelHeight - (SettingsConstants.DEFAULT_GADGET_SIZE - SettingsConstants.DEFAULT_CONTACT_AREA_SIZE);  
        this.middle.style.pixelHeight = this.middle.offsetHeight + heightDelta;
        this.bottom.style.pixelTop = this.bottom.offsetTop + heightDelta;
		
		if (this.contactArea.style.display == "block" && this.gadgetSettings.showEmailCounter != GadgetConstants.SHOW_EMAIL_COUNTER_NEVER)
		{
			if ((this.gadgetSettings.showEmailCounter == GadgetConstants.SHOW_EMAIL_COUNTER_ONLY_WHEN_UNREAD && this.emailCounter.getValue() > 0) || this.gadgetSettings.showEmailCounter == GadgetConstants.SHOW_EMAIL_COUNTER_ALWAYS)
			{
				this.emailCounter.show();
			}
			else
			{
				this.emailCounter.hide();
			}
		}
		else
		{
			this.emailCounter.hide();
		}
    },
	
	updateEmailCounter:function(newCount)
	{
		try
		{
			if (newCount === undefined || newCount == null)
			{
				newCount = messenger.UnreadEmailCount(MessengerConstants.MUAFOLDER_INBOX);
			}
			
			this.emailCounter.setValue(newCount);
			
			if (this.contactArea.style.display == "block" && this.gadgetSettings.showEmailCounter != GadgetConstants.SHOW_EMAIL_COUNTER_NEVER)
			{
				if ((this.gadgetSettings.showEmailCounter == GadgetConstants.SHOW_EMAIL_COUNTER_ONLY_WHEN_UNREAD && this.emailCounter.getValue() > 0) || this.gadgetSettings.showEmailCounter == GadgetConstants.SHOW_EMAIL_COUNTER_ALWAYS)
				{
					this.emailCounter.show();
				}
				else
				{
					this.emailCounter.hide();
				}
			}
			else
			{
				this.emailCounter.hide();
			}
		}
		catch (ex)
		{
			debug("updateEmailCounter(" + newCount + ") exception thrown: " + ex);
		}
	},

	/**********************************************************************************
	 * Parameters:
	 *   none
	 * 
	 * Description:
	 *   Function called when the user has changed gadget settings to load new user settings and generate contact list
	 *   is a change that requires it occured (all changes except chagned in gadget height). 
	 **********************************************************************************/
    onSettingsClosed:function()
    {
		var needGadgetRefresh = System.Gadget.Settings.readString("needGadgetRefresh");

		if (needGadgetRefresh != null && needGadgetRefresh == "true")
		{
			this.gadgetSettings.loadGadgetSettings();
			this.updateGadgetAppearance();
			this.generateContactList();
		}
    },

	/**********************************************************************************
	 * Parameters:
	 *   <newStatus> - new status for the messenger
	 * 
	 * Description:
	 *   Change the current status to the received status of signs out if the received status is offline. 
	 **********************************************************************************/
    changeMyStatus:function(newStatus)
    {
		try
		{
	        if (MessengerConstants.MISTATUS_OFFLINE == newStatus)
	        {
	            messenger.Signout();   
	        }
	        else
	        {
	            messenger.MyStatus = newStatus;
	        }
		}
		catch (ex)
		{
			debug("changeMyStatus(" + newStatus + ") exception thrown: " + ex);
		}
    },

	/**********************************************************************************
	 * Parameters:
	 *   none
	 * 
	 * Description:
	 *   Calls the AutoSignIn function to sign in with the current user if the credentials are stored. 
	 **********************************************************************************/
    messengerSignIn:function()
    {
        try
        {
            messenger.AutoSignin();
        }
        catch (ex)
        {
			debug("messengerSignIn() exception thrown: " + ex);
		    
			this.divSignInError.style.display = "block";
    		
		    if (MessengerGadget.isMsgrRunning())
		    {
			    debug("messenger.AutoSignin() failed - msgr running");
			    this.divSignInError.innerHTML = GadgetLocalizedConstants.LOC_SIGN_IN_ERROR_RUNNING;
				this.divSignInError.title = GadgetLocalizedConstants.LOC_SIGN_IN_ERROR_RUNNING;
		    }
		    else
		    {
				debug("messenger.AutoSignin() failed - msgr not running");
			    this.divSignInError.innerHTML = GadgetLocalizedConstants.LOC_SIGN_IN_ERROR_NOT_RUNNING;
				this.divSignInError.title = GadgetLocalizedConstants.LOC_SIGN_IN_ERROR_NOT_RUNNING;
				System.Gadget.Settings.writeString("autoSignIn", "true");
				location.href = "gadget.html";
		    }
        }
    },

	/**********************************************************************************
	 * Parameters:
	 *   none
	 * 
	 * Description:
	 *   Called when SORT_BY_STATUS == sortContactsBy to get contact information to sort contacts by status.
	 *   Creates groups Online, Mobile and Offline and hides contacts or groups that should not be showing.
	 **********************************************************************************/
    organizeContactsByStatus:function()
    {
		try
		{
	        var contactGroupsList = new Array();   

	        // 3 groups to be used when sort is by status
	        var onlineGroup = new MsgrGroup("Online");
	        var mobileGroup = new MsgrGroup("Mobile");
	        var offlineGroup = new MsgrGroup("Offline");
	        
	        // fill each group with their respective contacts
	        for (var i = 0; i < messenger.MyContacts.Count; i++)
	        {
	            var currContact = messenger.MyContacts.Item(i);
				//debug("Status = " + messenger.MyContacts.Item(i).Status);
	            var newMsgrContact = new MsgrContact("Online", currContact, this.gadgetSettings);

	            if (newMsgrContact.isOffline())
	            {
	                if (newMsgrContact.isMobile())
	                {
	                    mobileGroup.contacts[mobileGroup.contacts.length] = newMsgrContact;
	                }
	                else
	                {
	                    offlineGroup.contacts[offlineGroup.contacts.length] = newMsgrContact;
	                }
	            }
	            else
	            {
	                onlineGroup.contacts[onlineGroup.contacts.length] = newMsgrContact;
	            }
			}
			
	        // sort contacts on their respective groups
	        onlineGroup.contacts.sort(MsgrContact.compare);
	        mobileGroup.contacts.sort(MsgrContact.compare);
	        offlineGroup.contacts.sort(MsgrContact.compare);
	        
	        // add groups to the cached contact list
	        contactGroupsList[0] = onlineGroup;
	        contactGroupsList[1] = mobileGroup;
	        contactGroupsList[2] = offlineGroup;
	        
	        return contactGroupsList;
		}
		catch (ex)
		{
			debug("organizeContactsByStatus() exception thrown: " + ex);
		}
    },

	/**********************************************************************************
	 * Parameters:
	 *   <ref_contactGroupsList> - list of groups
	 *   <ref_contactList> - list of contacts
	 * 
	 * Description:
	 *   Called when SORT_BY_GROUPS == sortContactsBy to get contact information
	 **********************************************************************************/
    organizeContactsByGroups:function()
    {
		try
		{
	        var contactGroupsList = new Array();
	        var contactList = new Array();
	        
	        // array for all those contacts that do belong to a group
	        var groupedContacts = new Array();
	        // create special groups 
	        var mobileGroup = new MsgrGroup("Mobile");
	        var ungroupedGroup = new MsgrGroup("Other Contacts");    
	        var offlineGroup = new MsgrGroup("Offline");

	        // get the content of each groups
	        for (var i = 0; i < messenger.MyGroups.Count; i++)
	        {
	            var currGroup = messenger.MyGroups.Item(i);
	            var newMsgrGroup = new MsgrGroup(currGroup.Name);

	            // get individual contacts in each group
	            for (var j = 0; j < currGroup.Contacts.Count; j++)
	            {
	                var currContact = currGroup.Contacts.Item(j);
	                var newMsgrContact = new MsgrContact(newMsgrGroup.name, currContact, this.gadgetSettings);
	                groupedContacts[groupedContacts.length] = newMsgrContact;

	                if (newMsgrContact.isOffline() && newMsgrContact.isMobile() && this.gadgetSettings.groupMobile)
	                {
	                    mobileGroup.contacts[mobileGroup.contacts.length] = newMsgrContact;
	                }
	                else if (newMsgrContact.isOffline() && !newMsgrContact.isMobile() && this.gadgetSettings.groupOffline)
	                {
	                    offlineGroup.contacts[offlineGroup.contacts.length] = newMsgrContact;
	                }
	                else
	                {
	                    newMsgrGroup.contacts[newMsgrGroup.contacts.length] = newMsgrContact;
	                }
	            }

	            newMsgrGroup.contacts.sort(MsgrContact.compare);
	            contactGroupsList[i] = newMsgrGroup;
	        }

	        contactGroupsList.sort(MsgrGroup.compare);

	        ungroupedGroup.contacts = this.organizeUngroupedContacts(ungroupedGroup.name, groupedContacts, offlineGroup, mobileGroup);
			
	        ungroupedGroup.contacts.sort(MsgrContact.compare);
	        
	        if (this.gadgetSettings.groupMobile)
	        {
	            mobileGroup.contacts.sort(MsgrContact.compare);
	            contactGroupsList[contactGroupsList.length] = mobileGroup;
	        }

	        if (this.gadgetSettings.groupOffline)
	        {
	            offlineGroup.contacts.sort(MsgrContact.compare);
	            contactGroupsList[contactGroupsList.length] = offlineGroup;
	        }

	        contactGroupsList[contactGroupsList.length] = ungroupedGroup;
	        
	        return contactGroupsList;
		}
		catch (ex)
		{
			debug("organizeContactsByGroups() exception thrown: " + ex);
		}
    },

	/**********************************************************************************
	 * Parameters:
	 *   <groupName> - name of ungrouped contacts
	 *   <groupedContacts> - array that contains reference to all groups with their
	 *       their reespective contacts
	 *   <offlineGroup> - list of offline contacts
	 *   <mobileGroup> - list of mobile contacts
	 * 
	 * Description:
	 *   Looks through all the contacts for those that do not belong to a group.
	 **********************************************************************************/
    organizeUngroupedContacts:function(groupName, groupedContacts, offlineGroup, mobileGroup)
    {
		try
		{
	        var ungroupedContacts = new Array();
	        
	        // go through all messenger contacs
	        for (var i = 0; i < messenger.MyContacts.Count; i++)
	        {
	            var currContact = messenger.MyContacts.Item(i);
	            
	            // verify if contact is already in a group
	            if (null == MsgrContact.findMsgrContactByContactObj(groupedContacts, currContact))
	            {
	                var newMsgrContact = new MsgrContact(groupName, currContact, this.gadgetSettings);
	            
	                if (newMsgrContact.isOffline() && newMsgrContact.isMobile() && this.gadgetSettings.groupMobile)
	                {
	                    mobileGroup.contacts[mobileGroup.contacts.length] = newMsgrContact;
	                }
	                else if (newMsgrContact.isOffline() && !newMsgrContact.isMobile() && this.gadgetSettings.groupOffline)
	                {
	                    offlineGroup.contacts[offlineGroup.contacts.length] = newMsgrContact;
	                }
	                else
	                {
	                    ungroupedContacts[ungroupedContacts.length] = newMsgrContact;
	                }
	            }
	        }
	        
	        return ungroupedContacts;
		}
		catch (ex)
		{
			debug("organizeUngroupedContacts() exception thrown: " + ex);
		}
    },

	/************************************************************
			  UI FUNCTIONS
	 ************************************************************/
	/**********************************************************************************
	* Parameters:
	*   <p> - 
	* 
	* Description:
	*   d.
	**********************************************************************************/
    generateContactList:function()
    {   
        this.contactList.innerHTML = "";

        var sortedContacts = null;
        var currentGroup = null;
        var currentImage = null;
        var currentContact = null;    
        var currentGroupContactList = null;
        
        var groupedContacts = null;
        
        if (MessengerConstants.SORT_BY_STATUS == this.gadgetSettings.sortContactsBy)
        {
            groupedContacts = this.organizeContactsByStatus();
        }
        else if (MessengerConstants.SORT_BY_GROUP == this.gadgetSettings.sortContactsBy)
        {
            groupedContacts = this.organizeContactsByGroups();
        }

        for (var i = 0; i < groupedContacts.length; i++)
        {
            // Add group div to contactList div    
            currentGroup = this.generateGroupHTML(groupedContacts[i]);       
            this.contactList.appendChild(currentGroup);

            // Add group contact list inside contactList div
            currentGroupContactList = this.generateGroupContactListHTML(groupedContacts[i]);
            this.contactList.appendChild(currentGroupContactList);

            sortedContacts = groupedContacts[i].contacts;
            for (var j = 0; j < sortedContacts.length; j++)
            {   
                currentContact = this.generateContactHTML(sortedContacts[j]);              
                currentGroupContactList.appendChild(currentContact);  
            } 
        }
        
        if (MessengerConstants.FILTER_SHOW_ONLINE_ONLY == this.gadgetSettings.filterContactsBy)
        {
            if (MessengerConstants.SORT_BY_STATUS == this.gadgetSettings.sortContactsBy || this.gadgetSettings.groupMobile)
            {
                document.getElementById("Mobile").style.display = "none";
                document.getElementById("Mobile_GROUP_CONTACTS").style.display = "none";
            }
            if (MessengerConstants.SORT_BY_STATUS == this.gadgetSettings.sortContactsBy || this.gadgetSettings.groupOffline)
            {
                document.getElementById("Offline").style.display = "none";
                document.getElementById("Offline_GROUP_CONTACTS").style.display = "none";
            }
        }
		debug("list generated");
    },

	/**********************************************************************************
	 * Parameters:
	 *   <p> - 
	 * 
	 * Description:
	 *   d.
	 **********************************************************************************/
    generateGroupHTML:function(msgrGroup)
    {
        var groupDiv = null;
        var groupImage = null;

	    // create the group div element
        groupDiv = document.createElement("div");
        groupDiv.id = msgrGroup.name;
        groupDiv.className = "group";
		groupDiv.onmouseenter = this.onMouseEnterGroup;
        groupDiv.onmouseleave = this.onMouseLeaveGroup;
        groupDiv.onclick = this.onClickGroup;
		groupDiv.ondblclick = this.onClickGroup;

	    // create the image element
        groupImage = document.createElement("img");
        groupImage.id = msgrGroup.name + "_GROUP";
        groupImage.src = "../icons/arrow-down.png";
        groupImage.style.verticalAlign = "middle";

        // add img inside group div
        groupDiv.appendChild(groupImage);
        
		// add the name of the group to the group div
	    var groupDisplayName = "";
		
	    switch (msgrGroup.name)
	    {
		    case "Online":
			    groupDisplayName = GadgetLocalizedConstants.LOC_GROUP_NAME_ONLINE;
			    break;
		    case "Offline":
			    groupDisplayName = GadgetLocalizedConstants.LOC_GROUP_NAME_OFFLINE;
			    break;
		    case "Mobile":
			    groupDisplayName = GadgetLocalizedConstants.LOC_GROUP_NAME_MOBILE;
			    break;
		    case "Other Contacts":
			    groupDisplayName = GadgetLocalizedConstants.LOC_GROUP_NAME_OTHER_CONTACTS;
			    break;
		    default:
			    groupDisplayName = msgrGroup.name;
			    break;
	    }
        groupDiv.appendChild(document.createTextNode(groupDisplayName));
        
        return groupDiv;
    },

	/**********************************************************************************
	 * Parameters:
	 *   <p> - 
	 * 
	 * Description:
	 *   d.
	 **********************************************************************************/
    generateGroupContactListHTML:function(msgrGroup)
    {
        var groupContactListDiv = null;

        groupContactListDiv = document.createElement("div");
        groupContactListDiv.id = msgrGroup.name + "_GROUP_CONTACTS";
        groupContactListDiv.style.display = "block";
        
        return groupContactListDiv;
    },

	/**********************************************************************************
	 * Parameters:
	 *   <p> - 
	 * 
	 * Description:
	 *   d.
	 **********************************************************************************/
    generateContactHTML:function(msgrContact)
    {
        var contactDiv = null;
        var contactImage = null;
		var contactName = null;

        // Add contacts to group
        contactDiv = document.createElement("div");
        contactDiv.id = msgrContact.contact.SigninName;
        contactDiv.msgrContact = msgrContact;
        contactDiv.group = msgrContact.group;
        contactDiv.className = "contact";
        contactDiv.onmouseenter = this.onMouseEnterContact;
        contactDiv.onmouseleave = this.onMouseLeaveContact;
        contactDiv.ondblclick = this.onDoubleClickContact;
        contactDiv.gadget = this;
    	
	    if (msgrContact.isOffline() && MessengerConstants.FILTER_SHOW_ONLINE_ONLY == this.gadgetSettings.filterContactsBy)
	    {
		    contactDiv.style.display = "none";
	    }
            
        // Add status image to contact
        contactImage = document.createElement("img");
        contactImage.id = msgrContact.contact.SigninName + "_IMG";
        contactImage.src = "../icons/" + msgrContact.getImage() + ".png";
        contactImage.style.verticalAlign = "middle";
        contactDiv.appendChild(contactImage);
		
		contactName = document.createElement("span");
		contactDiv.appendChild(contactName);
		
        if (MessengerConstants.VIEW_BY_DISPLAY_NAME == this.gadgetSettings.viewContactsBy)
        {
            MessengerGadget.insertEmoticons(msgrContact.contact.FriendlyName, contactName);
        }
        else
        {
            contactName.appendChild(document.createTextNode(msgrContact.contact.SigninName));
        }
        
        return contactDiv;
    },

	/**********************************************************************************
	 * Parameters:
	 *   <p> - 
	 * 
	 * Description:
	 *   d.
	 **********************************************************************************/
	updateMyStatusAndFriendlyName:function()
    {
		try
		{
			this.statusDropDown.setCurrentValue(messenger.MyStatus);
			this.statusDropDown.setFixedText(messenger.MyFriendlyName);
		}
		catch (ex)
		{
			this.statusDropDown.setFixedText("");
			debug("updateMyStatusAndFriendlyName() exception thrown: " + ex);
		}
    },
	
	/**********************************************************************************
	 * Parameters:
	 *   <p> - 
	 * 
	 * Description:
	 *   d.
	 **********************************************************************************/
    showSignIn:function()
    {
	    this.divSignInError.style.display = "none";
	    this.contactArea.style.display = "none";
        this.contactTooltip.hide();
        this.divSignIn.style.display = "block";
        this.buttonSignIn.disabled = false;
		this.emailCounter.hide();
    },

	/**********************************************************************************
	 * Parameters:
	 *   <p> - 
	 * 
	 * Description:
	 *   d.
	 **********************************************************************************/
    showContactList:function()
    {
		debug("showContactList()");
		this.contactArea.style.display = "block";
		this.contactTooltip.hide();
		this.divSignIn.style.display = "none";
		this.gadgetSettings.loadGadgetSettings();
		this.updateGadgetAppearance();
		this.generateContactList();
		this.updateMyStatusAndFriendlyName();
		this.updateEmailCounter();
    },

	/**********************************************************************************
	 * Parameters:
	 *   <p> - 
	 * 
	 * Description:
	 *   d.
	 **********************************************************************************/
    updateContactStatusIcon:function(msgrContact)
    {
        var img = document.getElementById(msgrContact.contact.SigninName + "_IMG");
        if (null != img)
        {
            img.src = "../icons/" + msgrContact.getImage() + ".png";
        }
    },

	/**********************************************************************************
	 * Parameters:
	 *   <p> - 
	 * 
	 * Description:
	 *   d.
	 **********************************************************************************/
    updateContactFriendlyName:function(msgrContact)
    {
        var contactDiv = document.getElementById(msgrContact.contact.SigninName);
        if (null != contactDiv)
        {
            //contactDiv.replaceAdjacentText("beforeEnd", msgrContact.contact.FriendlyName);
			contactDiv.innerHTML = "";
			
			// Add status image to contact
	        contactImage = document.createElement("img");
	        contactImage.id = msgrContact.contact.SigninName + "_IMG";
	        contactImage.src = "../icons/" + msgrContact.getImage() + ".png";
	        contactImage.style.verticalAlign = "middle";
	        contactDiv.appendChild(contactImage);
			
			contactName = document.createElement("span");
			contactDiv.appendChild(contactName);
			
	        if (MessengerConstants.VIEW_BY_DISPLAY_NAME == this.gadgetSettings.viewContactsBy)
	        {
				MessengerGadget.insertEmoticons(msgrContact.contact.FriendlyName, contactName);
	        }
	        else
	        {
				contactName.appendChild(document.createTextNode(msgrContact.contact.SigninName));
	        }
        }
    },

	/**********************************************************************************
	 * Parameters:
	 *   <contactDivToBeMoved> - reference to the contact's div to be repositioned
	 * 
	 * Description:
	 *   Moves the contact's div from its current position into the appropriate group position.
	 **********************************************************************************/
    moveContactDiv:function(contactDivToBeMoved)
    {
	    // verify if contact needs to be invisible (display = none)
        if (MessengerConstants.FILTER_SHOW_ONLINE_ONLY == this.gadgetSettings.filterContactsBy && contactDivToBeMoved.msgrContact.isOffline())
        {
			// contact is now offline and offline contacts are being filtered - change to display = none
			contactDivToBeMoved.style.display = "none";
        }
        else
        {
		    // in case this contact was offline previously and not visible
		    contactDivToBeMoved.style.display = "block";
	    }
            
	    // find out where the contact should be positioned
	    var newGroupName = null;
    	
	    if (contactDivToBeMoved.msgrContact.isOffline() && contactDivToBeMoved.msgrContact.isMobile() && (MessengerConstants.SORT_BY_STATUS == this.gadgetSettings.sortContactsBy || (MessengerConstants.SORT_BY_GROUP == this.gadgetSettings.sortContactsBy && this.gadgetSettings.groupMobile)))
	    {
		    newGroupName = "Mobile";
	    }
	    else if (contactDivToBeMoved.msgrContact.isOffline() && (MessengerConstants.SORT_BY_STATUS == this.gadgetSettings.sortContactsBy || (MessengerConstants.SORT_BY_GROUP == this.gadgetSettings.sortContactsBy && this.gadgetSettings.groupOffline)))
	    {
		    newGroupName = "Offline";
	    }
	    else
	    {
		    newGroupName = contactDivToBeMoved.group;
	    }
    	
	    // find contact's positino in new group
	    var referenceDivId = newGroupName + "_GROUP_CONTACTS";
	    var groupDiv = document.getElementById(referenceDivId).getElementsByTagName("div");        
	    var referenceMsgrContact = null;
	    // Go through all the contacts in new group to find out the new positions
	    var skipped = false;
    	
	    for (var i = 0; i < groupDiv.length; i++)
	    {
		    if (groupDiv[i].msgrContact.compareTo(contactDivToBeMoved.msgrContact) > 0)
		    {
			    // found position
			    referenceMsgrContact = groupDiv[i];
			    break;
		    }
	    }
    	
	    // insert the contact in correct place
	    if (null == referenceMsgrContact)
	    {
		    // no reference contact means that the contact should be placed at the end of the group
		    document.getElementById(referenceDivId).insertAdjacentElement("beforeEnd", contactDivToBeMoved);
	    }
	    else
	    {
		    // contact should be placed before the reference contact
		    referenceDivId = referenceMsgrContact.msgrContact.contact.SigninName;
		    document.getElementById(referenceDivId).insertAdjacentElement("beforeBegin", contactDivToBeMoved);
	    }
    },

	/************************************************************
			  UI EVENTS
	 ************************************************************/
	/**********************************************************************************
	 * Parameters:
	 *   <p> - 
	 * 
	 * Description:
	 *   d.
	 **********************************************************************************/
    onDoubleClickEmailCounter:function()
    {
		try
		{
	        messenger.OpenInbox();
		}
		catch (ex)
		{
			debug(" onDoubleClickEmailCounter() exception thrown: " + ex);
		}
    },
	
	/**********************************************************************************
	 * Parameters:
	 *   <p> - 
	 * 
	 * Description:
	 *   d.
	 **********************************************************************************/
    onDoubleClickContact:function()
    {
		try
		{
	        var msgrContact = this.msgrContact;
	        if (msgrContact.isOffline() && msgrContact.isMobile())
	        {
	            messenger.Page(msgrContact.contact);
	        }
	        else
	        {
	            messenger.InstantMessage(msgrContact.contact);
	        }
		}
		catch (ex)
		{
			debug("onDoubleClickContact() exception thrown: " + ex);
		}
    },

	/**********************************************************************************
	 * Parameters:
	 *   <p> - 
	 * 
	 * Description:
	 *   d.
	 **********************************************************************************/
    onMouseEnterContact:function()
    {
        this.style.backgroundImage = "url('../bg/contactBackground.png')";
        this.style.color = "white";
        this.style.cursor = "default";
    	
		/// TODO: Fix to show on top of cursor if at the bottom
		this.gadget.contactTooltip.showDelayed(GadgetConstants.TOOLTIP_LEFT, window.event.clientY+12, this.msgrContact.contact.FriendlyName + " (" + MessengerGadget.getStatusTextFromConstant(this.msgrContact.contact.Status) + ")<" + this.id + ">");
    },

	/**********************************************************************************
	 * Parameters:
	 *   <p> - 
	 * 
	 * Description:
	 *   d.
	 **********************************************************************************/
    onMouseLeaveContact:function()
    {
        this.style.backgroundImage = "";
        this.style.color = "black";
        this.style.cursor = "";
        
        try
	    {
		    clearTimeout(this.gadget.tooltipTimer);
	    }
	    catch (e)
	    {
		    // tooltip time was already triggered
	    }
	    
		this.gadget.contactTooltip.hide();
    },

	/**********************************************************************************
	 * Parameters:
	 *   <p> - 
	 * 
	 * Description:
	 *   d.
	 **********************************************************************************/
    onMouseEnterGroup:function()
    {
        var groupDiv = document.getElementById(this.firstChild.id + "_CONTACTS");
        if ("block" == groupDiv.style.display)
        {
            this.firstChild.src = "../icons/arrow-down-onmouseover.png";
        }
        else
        {
            this.firstChild.src = "../icons/arrow-right-onmouseover.png";
        }
    },

	/**********************************************************************************
	 * Parameters:
	 *   <p> - 
	 * 
	 * Description:
	 *   d.
	 **********************************************************************************/
    onMouseLeaveGroup:function()
    {
        var groupDiv = document.getElementById(this.firstChild.id + "_CONTACTS");
        if ("block" == groupDiv.style.display)
        {
            this.firstChild.src = "../icons/arrow-down.png";
        }
        else
        {
            this.firstChild.src = "../icons/arrow-right.png";
        }
    },

	/**********************************************************************************
	 * Parameters:
	 *   <p> - 
	 * 
	 * Description:
	 *   d.
	 **********************************************************************************/
    onClickGroup:function()
    {
        var groupDiv = document.getElementById(this.firstChild.id + "_CONTACTS");
        if ("block" == groupDiv.style.display)
        {
            groupDiv.style.display = "none";
            this.firstChild.src = "../icons/arrow-right-onmouseover.png"
        }
        else
        {
            groupDiv.style.display = "block";
            this.firstChild.src = "../icons/arrow-down-onmouseover.png"
        }
    },

	/**********************************************************************************
	 * Parameters:
	 *   <p> - 
	 * 
	 * Description:
	 *   d.
	 **********************************************************************************/
    onChangeMyStatus:function()
    {
        this.changeMyStatus(this.statusDropDown.value);
    },

	/**********************************************************************************
	 * Parameters:
	 *   <p> - 
	 * 
	 * Description:
	 *   d.
	 **********************************************************************************/
    onClickSignIn:function()
    {
		this.buttonSignIn.disabled = true;
        this.messengerSignIn();
    },

	/**********************************************************************************
	 * Parameters:
	 *   <p> - 
	 * 
	 * Description:
	 *   d.
	 **********************************************************************************/
    onClickUpdateBar:function()
    {
	    System.Gadget.Flyout.file = "update.html";	
        System.Gadget.Flyout.show = true;
    },

	/**********************************************************************************
	 * Parameters:
	 *   <p> - 
	 * 
	 * Description:
	 *   d.
	 **********************************************************************************/
    onUpdateCheckCompleted:function(soapRequest, soapResponse)
    {
		try
		{
		    if (soapRequest.error != null)
		    {
		        debug(soapRequest.error);
		    }
		    else
		    {
		        updateAvailable = soapResponse.updateAvailable;
				if (updateAvailable == "true")
				{
					System.Gadget.Settings.writeString("updateURL", soapResponse.updateURL);
					g_messengerGadget.updateBar.show();
				}
		    }
		}
		catch (ex)
		{
			debug("onUpdateCheckCompleted() throwed exception: " + ex);
		}
    },

	/**********************************************************************************
	 * Parameters:
	 *   <p> - 
	 * 
	 * Description:
	 *   d.
	 **********************************************************************************/
    onFlyoutClosed:function()
    {
        var hideUpdateBar = System.Gadget.Settings.readString("hideUpdateBar");
        
        if (hideUpdateBar != null && hideUpdateBar == "true")
        {
            updateAvailable = false;
            this.updateBar.hide();
        }
    }
}

//g_messengerGadget = new MessengerGadget();

/************************************************************
          MSGRGROUP OBJECT
 ************************************************************/
/**********************************************************************************
 * Parameters:
 *   <p> - 
 * 
 * Description:
 *   d.
 **********************************************************************************/
function MsgrGroup(name)
{
    this.name = name;
    this.contacts = new Array();
}

/**********************************************************************************
 * Parameters:
 *   <group1> - first group to be compared
 *   <group2> - second group to be compared
 * 
 * Description:
 *   Compares groups by name. 
 **********************************************************************************/
MsgrGroup.compare = function(group1, group2) 
{
    return group1.name.localeCompare(group2.name);
}

/************************************************************
          MSGRCONTACT OBJECT - CONSTRUCTOR
 ************************************************************/
/**********************************************************************************
 * Parameters:
 *   <p> - 
 * 
 * Description:
 *   d.
 **********************************************************************************/
MsgrContact = function(group, contact, settings)
{
    this.group = group;
    this.contact = contact;
	this.settings = settings;
}

MsgrContact.compare = function(contact1, contact2) 
{
    return contact1.compareTo(contact2);
}

/**********************************************************************************
 * Parameters:
 *   <msgrContactList> - contains a list of messengerContact objects
 *   <Contact> - contact object to find inside msgrContactList
 * 
 * Description:
 *   Returns null if the contact is not found or an object of type messengerContact
 *   that contains a reference to the messenger's contact object and the name of 
 *   the group to whom the contact belongs. 
 **********************************************************************************/
MsgrContact.findMsgrContactByContactObj = function(msgrContactList, contact)
{
    var result = null;
    
    for (var i = 0; i < msgrContactList.length; i++)
    {
        if (msgrContactList[i].contact == contact)
        {
            result = msgrContactList[i];
            break;
        }
    }
    
    return result;
}

/************************************************************
          MSGRCONTACT OBJECT - MEMBERS
 ************************************************************/
MsgrContact.prototype =
{
    /**********************************************************************************
     * Parameters:
     *   <other> - contact to compare to
     * 
     * Description:
     *   Function returns 1 if contact 1 > contact 2, -1 if the opposite or 0 if both are the same. This function considers
     *   an offline item to greater than a mobile item and a mobile item greater than an online item. This is so that we can
     *   use this to sort contacts inside a group and the contacts would be organized alphabetically (either by friendly
     *   name, email or first and last name) and with online, mobile and offline in that order.
     **********************************************************************************/
    compareTo:function(other)
    {
        if (!this.isOffline() && other.isOffline())
        {
	        return -1;
        }
        else if (this.isOffline() && !other.isOffline())
        {
	        return 1;
        }
        else if (this.isMobile() && !this.isMobile())
        {
	        return -1;
        }
        else if (!this.isMobile() && this.isMobile())
        {
	        return 1;
        }
        else
        {
            if (MessengerConstants.VIEW_BY_DISPLAY_NAME == this.settings.viewContactsBy)
            {
                return this.contact.FriendlyName.localeCompare(other.contact.FriendlyName);
            }
            else if (MessengerConstants.VIEW_BY_EMAIL == this.settings.viewContactsBy)
            {
                return this.contact.SigninName.localeCompare(other.contact.SigninName);
            }
            
        }
		debug("ERROR!!!");
    },

	/**********************************************************************************
	 * Parameters:
	 *   <contact> - user's contact object
	 * 
	 * Description:
	 *   Returns true if the status of the contact's object received is not connected. 
	 **********************************************************************************/
    isOffline:function()
    {
        return MessengerGadget.isOfflineStatus(this.contact.Status);
    },

	/**********************************************************************************
	 * Parameters:
	 *   <contact> - user's contact object
	 * 
	 * Description:
	 *   Returns true if CanPage is true. 
	 **********************************************************************************/
    isMobile:function()
    {
        return this.contact.CanPage;
    },
	
	isBlocked:function()
	{
		return this.contact.Blocked;
	},
    
	/**********************************************************************************
	 * Parameters:
	 *   <contact> - contact object
	 * 
	 * Description:
	 *   Retrives the name of the image for a given contact depending on its Status and CanPage properties. 
	 **********************************************************************************/
    getImage:function()
    {
        if (this.isOffline() && this.isBlocked())
        {
            return ("blockedOffline");
        }
		else if (this.isOffline() && this.isMobile())
		{
            return ("mobile");
        }
		if (!this.isOffline() && this.isBlocked())
        {
            return ("blockedOnline");
        }
        else
        {
            switch(this.contact.Status)
            {
                case MessengerConstants.MISTATUS_UNKNOWN:
                    return ("offline");
                case MessengerConstants.MISTATUS_OFFLINE:
                    return ("offline");
                case MessengerConstants.MISTATUS_ONLINE:
                    return ("online");
                case MessengerConstants.MISTATUS_INVISIBLE:
                    return ("offline");
                case MessengerConstants.MISTATUS_BUSY:
                    return ("busy");
                case MessengerConstants.MISTATUS_BE_RIGHT_BACK:
                    return ("away");
                case MessengerConstants.MISTATUS_IDLE:
                    return ("away");
                case MessengerConstants.MISTATUS_AWAY:
                    return ("away");
                case MessengerConstants.MISTATUS_ON_THE_PHONE:
                    return ("busy");
                case MessengerConstants.MISTATUS_OUT_TO_LUNCH:
                    return ("away");
                default:
                    return ("other");
            } 
        }       
    }
}

/************************************************************
          MESSENGER EVENTS
 ************************************************************/

/**********************************************************************************
 * Parameters:
 *   <hr> - 
 *   <mMyStatus> - 
 * 
 * Description:
 *   d.
 **********************************************************************************/

function messenger::OnMyStatusChange(hr, mMyStatus)
{
	try
	{
		g_messengerGadget.updateMyStatusAndFriendlyName();
	}
	catch (ex)
	{
		debug("messenger::OnMyStatusChange() exception thrown: " + ex);
	}
}

/**********************************************************************************
 * Parameters:
 *   <p> - 
 * 
 * Description:
 *   d.
 **********************************************************************************/
function messenger::OnSignout()
{
	try
	{
		debug("messenger::OnSignout()");
	    g_messengerGadget.showSignIn();
	}
	catch (ex)
	{
		debug("messenger::OnSignout() exception thrown: " + ex);
	}
}

/**********************************************************************************
 * Parameters:
 *   <p> - 
 * 
 * Description:
 *   d.
 **********************************************************************************/
function messenger::OnContactStatusChange(pMContact, mStatus)
{
	try
	{
	    debug("messenger::OnContactStatusChange(pMContact, mStatus):" + "("+MessengerGadget.getStatusTextFromConstant(mStatus)+","+MessengerGadget.getStatusTextFromConstant(pMContact.Status)+"):"+pMContact.FriendlyName);
	    if (MessengerConstants.MISTATUS_UNKNOWN != pMContact.Status)
	    {
	        var tempMsgrContact = new MsgrContact("", pMContact, g_messengerGadget.gadgetSettings);
	        
	        if (MessengerGadget.isOfflineStatus(mStatus) ^ tempMsgrContact.isOffline())
	        {
	            var contactDivToMove = document.getElementById(tempMsgrContact.contact.SigninName);
	            g_messengerGadget.moveContactDiv(contactDivToMove);
	        }
			
	        g_messengerGadget.updateContactStatusIcon(tempMsgrContact);
			g_messengerGadget.updateContactFriendlyName(tempMsgrContact);
	    }    
	}
	catch (ex)
	{
		debug("messenger::OnContactStatusChange(" + MessengerGadget.getStatusTextFromConstant(mStatus)+","+MessengerGadget.getStatusTextFromConstant(pMContact.Status) +") exception thrown: " + ex);
	}
}

/**********************************************************************************
 * Parameters:
 *   <p> - 
 * 
 * Description:
 *   d.
 **********************************************************************************/
function messenger::OnSignin()
{
	try
	{
		debug("messenger::OnSignin()");
	    g_messengerGadget.showContactList();
	    
		debug("g_messengerGadget.updateBar.isHidden() = " + g_messengerGadget.updateBar.isHidden())
	    if (g_messengerGadget.gadgetSettings.gadgetGetUpdateNotifications && g_messengerGadget.updateBar.isHidden())
	    {
	        setTimeout(function() {g_messengerGadget.gadgetWebService.checkForUpdate(System.Gadget.version, g_messengerGadget.onUpdateCheckCompleted)}, GadgetConstants.CHECK_UPDATE_AVAILABLE_DELAY);
	    }  
	}
	catch (ex)
	{
		debug("messenger::OnSignin() exception thrown: " + ex);
	}
}

/**********************************************************************************
 * Parameters:
 *   <p> - 
 * 
 * Description:
 *   d.
 **********************************************************************************/
function messenger::OnUnreadEmailChange(mFolder, cUnreadEmail, pBoolfEnableDefault)
{
	try
	{
	    debug("messenger::OnContactStatusChange(mFolder, cUnreadEmail, pBoolfEnableDefault):" + "(" + mFolder + ", " + cUnreadEmail + ", " + pBoolfEnableDefault + ")");
	    if (mFolder == MessengerConstants.MUAFOLDER_INBOX)
		{
			g_messengerGadget.updateEmailCounter(cUnreadEmail);
		}
	}
	catch (ex)
	{
		debug("messenger::OnContactStatusChange(mFolder, cUnreadEmail, pBoolfEnableDefault):" + "(" + mFolder + ", " + cUnreadEmail + ", " + pBoolfEnableDefault + ") exception thrown: " + ex);
	}
}
