//
// Show or hide the target footer popup div
//
function footerPopupToggle( showMenu ) {

    // Get the popup element
    var popupDiv = document.getElementById( 'footer_locale' );

    // Do we want to show?
    if ( showMenu ) {

        // Yes, then show it
        popupDiv.style.visibility = 'visible';
    }
    else {

        // No, then hide it
        popupDiv.style.visibility = 'hidden';
    }
}

//
// Select new locale
//
function footerSelectLocale( locale ) {

    // Hide menu
    footerPopupToggle( false );

    // Set the cookie
    var today = new Date();
    var expire = new Date();
    expire.setTime( today.getTime() + 3600000 * 24 * 365 );
    document.cookie = 'locale=' + locale + ";expires=" + expire.toGMTString() + ';path=/';

    // Reload the window
    window.location.reload();
}

//
// Report a problem
//
function footerReportProblem() {

    // Set width
    var initialWidth = 920;

    // Set height
    var initialHeight = 450;

    // Set left
    var initialLeft = ( screen.width - initialWidth ) / 2;

    // Set top
    var initialTop = ( screen.height - initialHeight ) / 2;

    // Set url
    var url = '/support/report_problem.php?insim=yes';
    
    // Show the document
    window.open( url, '_blank', 'width=' + initialWidth + ', height=' + initialHeight + ', left=' + initialLeft + ', top=' + initialTop + ', resizable=no, scrollbars=no', true );
}

//
// Report that Flash is not supported on this platform
//
function noFlashWarning( companyName ) {
	
	// Note that Flash is not supported on this platform
	alert( 'Adobe Flash is currently not supported by this browser and ' + companyName + ' simulations cannot run without Flash.' );
}

//
// Open company document popup
//
function openCompanyDocumentPopup( url ) {

    // Set width
    var initialWidth = ( screen.width / 4 ) * 3;

    // Set height
    var initialHeight = ( screen.height / 4 ) * 3;

    // Set left
    var initialLeft = ( screen.width - initialWidth ) / 2;

    // Set top
    var initialTop = ( screen.height - initialHeight ) / 3;

    // Show the document
    window.open( url, '_blank', 'width=' + initialWidth + ', height=' + initialHeight + ', left=' + initialLeft + ', top=' + initialTop + ', resizable=yes, scrollbars=yes', true );
}

//
// iFrame load 
//
function iFrameLoad( iframeID ) {
	
	// Do we have a parent?
	if ( window.parent ) {
		
		// Yes, try to get the parent iFrame control
		var parentIframe = window.parent.document.getElementById( iframeID );
		
		// Did we find it?
		if ( parentIframe != null ) {
			
			// Yes, then make sure it is visible
			parentIframe.style.display = 'block';
			parentIframe.style.visibility = 'visible';
		}
	}
}

//
// Open company document popup
//
function openPracticeDocumentPopup( url ) {

    // Set width
    var initialWidth = 980;

    // Set height
    var initialHeight = ( screen.height / 4 ) * 3;

    // Set left
    var initialLeft = ( screen.width - initialWidth ) / 2;

    // Set top
    var initialTop = ( screen.height - initialHeight ) / 3;

    // Show the document
    window.open( url, '_blank', 'width=' + initialWidth + ', height=' + initialHeight + ', left=' + initialLeft + ', top=' + initialTop + ', location=no, status=no, resizable=yes, scrollbars=yes', true );
}

//
// Open session document popup window
//
function openSessionDocumentPopup( url, initialWidth, initialHeight, allowScroll ) {

    // Did we get a height passed?
	if ( initialHeight ) {
		
    	// Yes, set default width if required
    	initialWidth = ( initialWidth ) ? initialWidth : 800;
	}
	
	else {
		
    	// No, set large size
    	initialHeight = ( screen.height / 4 ) * 3;
    	initialWidth  = ( screen.width  / 8 ) * 7;
	}

	// Set left
	var initialLeft = ( screen.width - initialWidth ) / 2;

	// Set top
	var initialTop = ( screen.height - initialHeight ) / 3;
	
    // Set window options
    var windowOptions = ', location=no, status=no, resizable=yes, ';
    if ( allowScroll ) {
    	windowOptions += 'scrollbars=yes'
    }
    else {
    	windowOptions += 'scrollbars=no'
    }
    
    // Show the topic reply window
    window.open( url, '_blank', 'width=' + initialWidth + ', height=' + initialHeight + ', left=' + initialLeft + ', top=' + initialTop + windowOptions, true );
}

//
// Open hearing impaired window
//
function openHearingImpairedWindow( url ) {

    // Set width
    var initialWidth = 400;
    
    // Set height
    var initialHeight = 300;

    // Set left
    var initialLeft = ( screen.width - initialWidth ) / 5;

    // Set top
    var initialTop = ( screen.height - initialHeight ) / 3;

    // Show the topics window
    window.open( url, 'hearing_impaired', 'width=' + initialWidth + ', height=' + initialHeight + ', left=' + initialLeft + ', top=' + initialTop + ', location=no, status=no, resizable=yes, scrollbars=yes', true );
}

//
// Open generic href
//
function openHref( url, location ) {

    // Transfer to this window
    return window.open( url, location );
}

//
// Open href from button
//
function openHrefFromButton( buttonElementId, url, location ) {

    // Get the popup element
    var buttonElement = document.getElementById( buttonElementId );
	
    // Did we get one?
    if ( buttonElement != null ) {
    	
    	// Yes, disable it to prevent another click
		buttonElement.disabled = true;
    }
	
    // Now transfer to this new url
    return window.open( url, location );
}

//
// Open topics window
//
function openTopics( url ) {

    // Set width
    var initialWidth = 900;
    
    // Set height
    var initialHeight = ( screen.height / 4 ) * 3;

    // Set left
    var initialLeft = ( screen.width - initialWidth ) / 2;

    // Set top
    var initialTop = ( screen.height - initialHeight ) / 3;

    // Show the topics window
    window.open( url, 'dm_topic_list', 'width=' + initialWidth + ', height=' + initialHeight + ', left=' + initialLeft + ', top=' + initialTop + ', location=no, status=no, resizable=yes, scrollbars=yes', true );
}

//
// Open topic popup window
//
function openTopicPopup( imageElementId, url, initialHeight, textElements, threadParentElementId ) {

	// Reset topic display row
	resetTopicDisplayRow( imageElementId, textElements, threadParentElementId );

    // Set width
    var initialWidth = 960;
    
    // Set left
    var initialLeft = ( screen.width - initialWidth ) / 2;

    // Set top
    var initialTop = ( screen.height - initialHeight ) / 3;

    // Show the topic reply window
    window.open( url, '_blank', 'width=' + initialWidth + ', height=' + initialHeight + ', left=' + initialLeft + ', top=' + initialTop + ', location=no, status=no, resizable=yes, scrollbars=yes', true );
}

//
// Reset topic display row
//
function resetTopicDisplayRow( imageElementId, textElements, threadParentElementId ) {

    // Do we have an image element ID?
    if ( imageElementId != null ) {

        // Yes, get the element
        var element = document.getElementById( imageElementId );

        // Did we find it?
        if ( element != null ) {
        	
	        // Yes, Is this element already hidden?
	        if ( element.style.visibility == 'hidden' ) {
	        	
	        	// Yes, then just exist
	        	return;
	        }
	        
	        // Otherwise, hide it
	        element.style.visibility = 'hidden';
        }
        
        else {
        	
        	// No, then just exist
        	return;        	
        }

        // Do we have text elements?
        if ( textElements != null ) {

            // Yes, break up string into array of strings
            textElements = textElements.split( ',' );

            // Try and reset font weight on each text elements
            for ( var textCounter = 0; textCounter < textElements.length; textCounter++ ) {

                // Get the element
                element = document.getElementById( textElements[textCounter] );

                // Did we find it?
                if ( element != null ) {
                	
                	// Yes, reset font weight
                	element.style.fontWeight = 'normal';
                }
            }
        }
        
        // Do we have a thread parent element?
        if ( threadParentElementId != null ) {
        	
        	// Yes, then adjust unread replies
        	var threadParentElement = document.getElementById( threadParentElementId );
        	
        	// Did we find it?
        	if ( threadParentElement != null ) {
        	
	        	// Yes, check for leading paren
	        	var leftParen = threadParentElement.innerHTML.lastIndexOf( '(' );
	        	
	        	// Did we find it?
	        	if ( leftParen >= 0 ) {
	        		
	        		// Yes, strip off first part of string
	        		var totalReplies = threadParentElement.innerHTML.substr( 0, leftParen - 1 );
	        		
	        		// Find right paren
	        		var rightParen = threadParentElement.innerHTML.lastIndexOf( ')' );
	        		 
	        		// Did we find it?
	        		if ( rightParen >= 0 && rightParen > leftParen ) {
	        			
	        			// Yes, get number
	        			var currentCount = threadParentElement.innerHTML.substr( leftParen + 1, rightParen - leftParen - 1 );
	        			
	        			// Bump it down
	        			var newCount = parseInt( currentCount ) - 1;
	        			
	    				// Reset display	
	        			threadParentElement.innerHTML = ( newCount > 0 ) ? totalReplies + ' ' + '(' + newCount + ')' : totalReplies;
	        		}
	        	}
        	}
        }
    }
}

//
// setWaitCursor function
//
function setWaitCursor () {
	
	// Reset body cursor
	window.document.body.style.cursor = 'wait';

    // Get html tag
    var htmlTags = document.getElementsByTagName( 'html' );

    // Get length of array
    var numHtml = htmlTags.length;

    // Loop through and reset cursor as required
    for ( var i = 0; i < numHtml; i++ ) {
        htmlTags[i].style.cursor = 'wait';
    }

    // Get a tags
    var aTags = document.getElementsByTagName( 'a' );

    // Get length of array
    var numATags = aTags.length;

    // Loop through and reset cursor as required
    for ( var i = 0; i < numATags; i++ ) {
        aTags[i].style.cursor = 'wait';
    }
    
    // Get button tags
    var buttonTags = document.getElementsByTagName( 'button' );

    // Get length of array
    var numButtonTags = buttonTags.length;

    // Loop through and reset cursor as required
    for ( var i = 0; i < numButtonTags; i++ ) {
        buttonTags[i].style.cursor = 'wait';
    }
    
    // Get th tags
    var thTags = document.getElementsByTagName( 'th' );

    // Get length of array
    var numThTags = thTags.length;

    // Loop through and reset cursor as required
    for ( var i = 0; i < numThTags; i++ ) {
        thTags[i].style.cursor = 'wait';
    }
}

//
// Refresh opener from popup function
//
function refreshOpenerFromPopup( url ) {

    // Open new parent
    window.opener.location = url;

    // Set focus
    window.opener.focus();

    // Close this window
    window.close();
}

//
// Refresh opener parent from popup function
//
function refreshOpenerParentFromPopup( url ) {

    // Open new parent
    window.opener.parent.location = url;

    // Set focus
    window.opener.parent.focus();

    // Close this window
    window.close();
}

var dm_checkForNewChatSession_sessionId = 0;
var dm_checkForNewChatSession_userId = 0;

//
// Check for new chat session  function
//
function checkForNewChatSession( sessionId, userId ) {

	// Update global variables 
	dm_checkForNewChatSession_sessionId = sessionId;
	dm_checkForNewChatSession_userId = userId;	
	
	// Do we have DM http?
	if ( window.DM_Http != null ) {
		
        // Yes, check for chat
        DM_Http.getText( '/lms/chat/chat_new_check.php?session=' + sessionId + '&user=' + userId, startChatSessionWithPrompt );        
	}
}

//
// Start chat session function
//
function startChatSession( returnValue ) {
	
	// Did we get a return?
	if ( returnValue != null ) {
		
		// Yes, got a url?
		if ( returnValue.length > 0 ) {
			
			// Yes, open new chat window
			openChatWindow( returnValue, true );
		}
	}
}

//
// Start chat session with prompt function
//
function startChatSessionWithPrompt( returnValue ) {
	
	// Did we get a return?
	if ( returnValue != null ) {
		
		// Yes, got a url?
		if ( returnValue.length > 0 ) {
			
			// Yes, set up to prompt user
			var invitingUserOffset = returnValue.search( "inviting_user=" );
			
			// Default inviting user
			var invitingUser = 'Unknown';
			
			// Did we find it?
			if ( invitingUserOffset >= 0 ) {
				
				// Yes, get inviting user
				invitingUser = returnValue.substr( invitingUserOffset + "inviting_user=".length );
				invitingUser = DM_Http.urldecode( invitingUser );
			}
			
    		// Does user want to run chat?
    		if ( window.confirm( "You have received a chat session invitation from another course participant ( " + invitingUser + " ). Do you want to accept it?" ) ) {
    			
				// Yes, open new chat window
				openChatWindow( returnValue, false );
    		}
    		
    		else {
    			
    			// No, then reject it
    			
    			// Replace url page
    			returnValue = returnValue.replace( 'chat_session.php', 'chat_user_reject.php' );
    			
				// Reject the request
        		DM_Http.getText( returnValue, null );    			
    		}
    		
	    	// Set to check again in 10 seconds
			setTimeout( 'checkForNewChatSession( ' + dm_checkForNewChatSession_sessionId + ', ' + dm_checkForNewChatSession_userId + ' );', 10000 );        
		}
	
		else {
			
	    	// No, set to check again in 10 seconds
			setTimeout( 'checkForNewChatSession( ' + dm_checkForNewChatSession_sessionId + ', ' + dm_checkForNewChatSession_userId + ' );', 10000 );        
		}
	}
	
	else {
		
    	// No, set to check again in 10 seconds
		setTimeout( 'checkForNewChatSession( ' + dm_checkForNewChatSession_sessionId + ', ' + dm_checkForNewChatSession_userId + ' );', 10000 );        
	}
}

//
// Start new chat
//
function startNewChat( sessionId, chatId, userId, inviteUserId ) {
	    
	// Do we have DM http?
	if ( window.DM_Http != null ) {

		// Yes, invite the user 
        DM_Http.getText( '/lms/chat/chat_user_invite.php?session=' + sessionId + '&chat=' + chatId + '&user=' + userId + '&invite=' + inviteUserId, startChatSession );
	}	
}

//
// Open chat window
//
function openChatWindow( url, startingNewChat ) {

    // Set width
    var initialWidth = 900;
    
    // Set height
    var initialHeight = 580;

    // Set left
    var initialLeft = ( screen.width - initialWidth ) / 2;

    // Set top
    var initialTop = ( screen.height - initialHeight ) / 3;

    // Show the chat window
    var popupAllowed =  window.open( url, '_blank', 'width=' + initialWidth + ', height=' + initialHeight + ', left=' + 
    								 initialLeft + ', top=' + initialTop + ', location=no, status=no, resizable=yes, scrollbars=yes', true );
    								 
    // Did it work?		
    if ( !popupAllowed ) {
    	
		// Yes, replace url page
		url = url.replace( 'chat_session.php', 'chat_user_exit.php' );

		// Exit chat
        DM_Http.getText( url + '&popup=yes', null );
    	
		// Issue error
		alert( 'Your chat session failed to start because popup windows are blocked for this site.' );
    }						 
}

//
// Add chat message
//
function chatAddMessage( currentUserName, sessionId, chatId, userId ) {
	
    // Get message
    var messageValue = document.forms.f1.chat_comment.value;

    // Do we have a value?
    if ( messageValue.length == null || messageValue.length == 0 ) {
    	
    	// No, then issue error
    	alert( 'A comment is required to add to this chat session.' );
    	
    	// Set focus
    	document.forms.f1.chat_comment.focus();
    
    	// Exit
    	return;
    }
    
    // Clear message 
    document.forms.f1.chat_comment.value = '';
    document.forms.f1.chat_comment.select();
    document.forms.f1.chat_comment.focus();
    
    // Get message iframe
    iFrameElement = document.getElementById( 'iframe_messages' );

    // Did we get it?
    if ( iFrameElement != null ) {
    	
    	// Yes, does it have a document?
    	if ( iFrameElement.contentWindow.document != null ) {
    		
    		// Yes, reference the document
    		var iFrameDocument = iFrameElement.contentWindow.document;
    		
    		// Get the message table and tbody
			var messageTable = iFrameDocument.getElementById( 'messages' );
			var tBody = messageTable.getElementsByTagName( 'tbody' )[0];
			
			// Output message
			var messageText = '<b>(' + currentUserName + ')</b> ' + DM_Http.htmlentities( messageValue );						
			var newTR = iFrameDocument.createElement( 'tr' );
			var newTD = iFrameDocument.createElement( 'td' );
			newTD.style.padding = '4px';
			newTD.innerHTML = messageText;
			newTR.appendChild( newTD );
			tBody.appendChild( newTR );		

			// Scroll it to bottom	
			iFrameElement.contentWindow.scrollTo( 0, 99999999 );										
    	}
    }
    
	// Do we have DM http?
	if ( window.DM_Http != null ) {
		
        // Yes, add message 
        messageValue = encodeURI( messageValue );
        DM_Http.getText( '/lms/chat/chat_add_message.php?session=' + sessionId + '&chat=' + chatId + '&user=' + userId + '&message=' + messageValue, null );
	}	
}

//
// Chat user exit function
//
function chatUserExit( sessionId, chatId, userId ) {
	    
	// Do we have DM http?
	if ( window.DM_Http != null ) {
		
        // Yes, notify of user exit 
        setWaitCursor();
        DM_Http.getText( '/lms/chat/chat_user_exit.php?session=' + sessionId + '&chat=' + chatId + '&user=' + userId, chatUserExitResponse );
	}	
}

//
// Start chat exit response function
//
function chatUserExitResponse( returnValue ) {

	// Now we can close the window
	window.close();
}

//
// Chat user invite
//
function chatUserInvite( sessionId, chatId, userId, inviteUserId ) {
	    
	// Do we have DM http?
	if ( window.DM_Http != null ) {
		
        // Yes, invite user
        DM_Http.getText( '/lms/chat/chat_user_invite.php?session=' + sessionId + '&chat=' + chatId + '&user=' + userId + '&invite=' + inviteUserId, null );
        
        // Note that the user is invited
		var userImageTd = document.getElementById( 'user_image_' + inviteUserId );
		if ( userImageTd != null ) {
			userImageTd.innerHTML = '<img src="/images/simulation/object_complete.gif" style="padding-top: 1px; vertical-align: -1px;" title="Student is in this chat session"/>';
		}
		var userStatusTd = document.getElementById( 'user_status_' + inviteUserId );
		if ( userStatusTd != null ) {
			userStatusTd.innerHTML = 'Invited';
			userStatusTd.setAttribute( 'title', '' );
		}			
	}	
}

