// JavaScript Document
/*
 * Returns a new XMLHttpRequest object, or false if this browser
 * doesn't support it
 */
function newXMLHttpRequest() {
  var xmlreq = false;

  if (window.XMLHttpRequest) {
    // Create XMLHttpRequest object in non-Microsoft browsers
    xmlreq = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    // Create XMLHttpRequest via MS ActiveX
    try {
      // Try to create XMLHttpRequest in later versions
      // of Internet Explorer
      xmlreq = new ActiveXObject("Msxml2.XMLHTTP");

    } catch (e1) {
      // Failed to create required ActiveXObject
      try {
        // Try version supported by older versions
        // of Internet Explorer
        xmlreq = new ActiveXObject("Microsoft.XMLHTTP");

      } catch (e2) {
        // Unable to create an XMLHttpRequest with ActiveX
      }
    }
  }

  return xmlreq;
}

function emailPassword(userId, messageDiv) {
  if (jQuery.trim(userId).length == 0) {
    messageDiv[0].innerHTML = "<span class='ErrorMessage'>Please enter your <b>login name</b> to retrieve the password for.</span>";
    return;
  }

  // Try and retrieve the password to email out.
  $.ajax({
    url: 'reset_password_submit.event',
    type: 'post',
    dataType: 'json',
    data: "username=" + unescape( encodeURIComponent(userId)),
    timeout: 10000,
    beforeSend: function(request){
      messageDiv[0].innerHTML = "<span class='ErrorMessage'>Attempting to retrieve the password for: <b>" + userId + "</b>.</span>";
    },
    error: function(){
      messageDiv[0].innerHTML = "<span class='ErrorMessage'>Error retrieving the password information.</span>";
    },
    success: function(json){
      // Check to see if the JSON object contains an error object.
      // If so, then we had an error on the back end, so show it.
      if  (typeof json.error == "undefined") {
        // Process the returned result set.
        messageDiv[0].innerHTML = "<span class='SuccessMessage'>" + unescape(json.message) + "</span>";
      } else {
        messageDiv[0].innerHTML = "<span class='ErrorMessage'>" + unescape(json.error) + "</span>";
      }
  }
});

}

function toggleRecordingState(recordingId, iconId) {
  var searchFilter="returnType=json&recordingId=" + recordingId;
  $.ajax
  (
    {
      url: 'hide_show_recording.html',
      type: 'post',
      dataType: 'json',
      data: searchFilter,
      timeout: 10000,
      error: function() {
        $('#ErrorMessage')[0].innerHTML="<span class='ErrorMessage'>" + json.error + "</span>";
      },
      success: function(json){
      if (typeof json.error == "undefined") {
        if (json.state == 0) {
          iconId.src="images/btn_hide.gif";
          iconId.tooltipText="This recording is accessable from a public page.";
        } else {
          iconId.src="images/btn_details.gif";
          iconId.tooltipText="This recording is not accessable from a public page.";
        }
      } else {
        messageDiv[0].innerHTML = "<span class='ErrorMessage'>" + json.error + "</span>";
      }
    }
  }
  );
}

function getSessionDetails (sessionId, sessionDiv, sessionSpaceDiv, iconId) {
  // Check the state of the session detail  expansion

  var sessionStatus = sessionDetailsArray[sessionId];

  if (typeof sessionStatus == "undefined") {
    var searchFilter = "returnType=html&meetingId=" + sessionId;
    var spacerHtml = sessionSpaceDiv[0].innerHTML;
    $.ajax({
      url: 'sessionDetails.html',
      type: 'post',
      dataType: 'html',
      data: searchFilter,
      timeout: 10000,
      beforeSend: function(request){
        sessionSpaceDiv[0].innerHTML = "Retrieving session details...";
      },
      error: function(){
		  	sessionSpaceDiv.html("");
        alert('Error retrieving the session details.');
      },
      success: function(html){
        // Check to see if the HTML object contains an error object.
        // If so, then we had an error on the back end, so show it.
        redirectOnHTMLErrorResponse(html);
        sessionDiv[0].innerHTML = html;
        toggleEntityDetails(0, sessionDiv, sessionSpaceDiv, iconId, 'session');
        sessionSpaceDiv[0].innerHTML = spacerHtml;
        sessionDetailsArray[sessionId] = 1;
      }
    });
  } else {
    toggleEntityDetails(sessionStatus, sessionDiv, sessionSpaceDiv, iconId, 'session');
    sessionDetailsArray[sessionId] = Math.abs(sessionStatus - 1);
  }
}

function toggleEntityDetails(state, entityDiv, entitySpaceDiv, iconId, toolTipLabel) {
  entitySpaceDiv.toggle();
  entityDiv.slideToggle("normal");

  if (state == 0) {
  	var toolTipText = "Hides additional " + toolTipLabel + " details.";
    iconId.src="images/btn_collapse.gif";
    iconId.tooltipText=toolTipText;
  } else {
    iconId.src = "images/btn_expand.gif";
    iconId.tooltipText="Expands panel.";
   }
}

function getScheduledReportDetails (reportId, reportDiv, reportSpaceDiv, iconId) {

  var reportStatus = reportDetailsArray[reportId];
  // Check the state of the report detail  expansion
  if (typeof reportStatus == "undefined") {
    var searchFilter = "returnType=html&selectedReport=" + reportId;
    var spacerHtml = reportSpaceDiv[0].innerHTML;
    $.ajax({
      url: 'scheduledReportDetails.html',
      type: 'post',
      dataType: 'html',
      data: searchFilter,
      timeout: 10000,
      beforeSend: function(request){
        reportSpaceDiv[0].innerHTML = "Retrieving report details...";
      },
      error: function(){
      	reportSpaceDiv.html('');
        alert('Error retrieving the report details.');
      },
      success: function(html){
        // Check to see if the HTML object contains an error object.
        // If so, then we had an error on the back end, so show it.
        redirectOnHTMLErrorResponse(html);
        reportDiv[0].innerHTML = html;
        toggleEntityDetails(0, reportDiv, reportSpaceDiv, iconId, 'report');
        reportSpaceDiv[0].innerHTML = spacerHtml;
        reportDetailsArray[reportId] = 1;
      }
    });
  } else {
    toggleEntityDetails(reportStatus, reportDiv, reportSpaceDiv, iconId, 'report');
    reportDetailsArray[reportId] = Math.abs(reportStatus - 1);
  }

}

function getUserIds (srcListBox) {
	var retValue = "";
	var sep = "";

  for (var i = (srcListBox.options.length - 1); i >= 0; i--) {
    var option = srcListBox.options[i];
    retValue += sep + option.value;
    sep=","
	}
	return retValue;
}

function validateUserSearchFilter (minFilterLength) {
	var errorMessage = "";
	var sep = "";
	//if ($('#searchType')[0].value == 0)
	if ($('#rbSearch')[0].checked)
	{
		// basic search
		var filterValue = $('#userFilter')[0].value;
		var filterTrimmed = jQuery.trim(filterValue);
		if (filterTrimmed.length != filterValue.length)
        {
          	errorMessage += sep + "Search criteria with leading or trailing whitespace is not valid.";
          	sep = "<br>";
        }
        else if (filterValue.length < minFilterLength)
		{
			errorMessage += sep + "Minimum search criteria length is "+minFilterLength+".";
          	sep = "<br>";
		}
    }
    else
	{
		// advanced search
		var valueLoginName = $('#userLoginName')[0].value;
		var valueFirstName = $('#userFirstName')[0].value;
		var valueLastName  = $('#userLastName')[0].value;
		var valueEmail	   = $('#userEmail')[0].value;

		var trimmedLoginName = jQuery.trim(valueLoginName);
		var trimmedFirstName = jQuery.trim(valueFirstName);
		var trimmedLastName  = jQuery.trim(valueLastName);
		var trimmedEmail     = jQuery.trim(valueEmail);

		if ( (trimmedLoginName.length != valueLoginName.length) || (trimmedFirstName.length != valueFirstName.length) || (trimmedLastName.length != valueLastName.length) || (trimmedEmail.length != valueEmail.length))
        {
          	errorMessage += sep + "Search criteria with leading or trailing whitespace is not valid.";
          	sep = "<br>";
        }
        else if ( (valueLoginName.length < minFilterLength) & (valueFirstName.length < minFilterLength) & (valueLastName.length < minFilterLength)& (valueEmail.length < minFilterLength))
		{
			errorMessage += sep + "Minimum search criteria length is "+minFilterLength+".";
          	sep = "<br>";
		}
	}
	return errorMessage;
}

function searchSessionUsers(trgListBox, invitedModListBox, invitedPartListBox, errorDiv, noteDiv, minFilterLength, groupUserSearchTimeout ) {
  var errorMessage = validateUserSearchFilter(minFilterLength);
	if (errorMessage.length > 0)
	{
		errorDiv.html(errorMessage);
	}
	else
	{
  		var searchFilter = "returnType=html&groups=yes&searchType=";
		if ($('#rbSearch')[0].checked) {
			// this is a basic search, so set the filters.
			searchFilter += "0&searchFilter=" + encodeURIComponent($('#userFilter')[0].value)
		} else {
			// This is an advanced search
			searchFilter +="1";
  			var domainId = $('#userSearchDomain')[0];
  			if (typeof domainId != "undefined") {
    			searchFilter +="&domainId=" + domainId.value
  			}
			searchFilter +="&loginName=" + encodeURIComponent($('#userLoginName')[0].value) + "&firstName=" + encodeURIComponent($('#userFirstName')[0].value) + "&lastName=" + encodeURIComponent($('#userLastName')[0].value) + "&email=" + encodeURIComponent($('#userEmail')[0].value)
		}

		// Now get the invited users
		var mods = getUserIds(invitedModListBox);
		var parts = getUserIds(invitedPartListBox);
		if ((mods.length > 0) && (parts.length > 0))
		{
  			mods += ","
		}
		mods += parts;

		if (mods.length > 0)
		{
		searchFilter += "&invitedUsers=" + mods;
		}

		$.ajax({
    		url: 'searchUsers.html',
    		type: 'get',
    		dataType: 'html',
    		contentType: "text/html; charset=utf-8",
   			data: searchFilter,
   			cache: false,
    		timeout: groupUserSearchTimeout*1000,
    		beforeSend: function(request){
		  		errorDiv.html("Processing search request...");
		  		noteDiv.html("");
				},
    		error: function(){
		  		errorDiv.html("");
        	alert('Error retrieving user list.');
    		},
    		success: function(html){
      		searchUsersSuccessHandler(html, errorDiv, noteDiv, trgListBox)
  			}
		});
	}

}

function searchGroupUsers(availableMembersListBox, selectedMemberListBox, currentGroupId, errorDiv, noteDiv, minFilterLength, groupUserSearchTimeout ) {
	var errorMessage = validateUserSearchFilter(minFilterLength);
	if (errorMessage.length > 0)
	{
		errorDiv.html(errorMessage);
	}
	else
	{
		var searchFilter = "returnType=html&groups=yes&searchType=";
  		if ($('#rbSearch')[0].checked) {
   		 // this is a basic search, so set the filters.
    	searchFilter += "0&searchFilter=" + encodeURIComponent($('#userFilter')[0].value)
  		} else {
    	// This is an advanced seach
    	searchFilter +="1&loginName=" + encodeURIComponent($('#userLoginName')[0].value) + "&firstName=" + encodeURIComponent($('#userFirstName')[0].value) + "&lastName=" + encodeURIComponent($('#userLastName')[0].value) + "&email=" + encodeURIComponent($('#userEmail')[0].value
)
  		}

  		// Now get the invited users
  		var parts = getUserIds(selectedMemberListBox);
  		if (parts.length > 0) {
    		parts += ",";
  		}
  		parts += "*" + currentGroupId;
  		searchFilter += "&invitedUsers=" + parts;

  		$.ajax({
    		url: 'searchUsers.html',
    		type: 'get',
    		dataType: 'html',
    		contentType: "text/html; charset=utf-8",
    		data: searchFilter,
   			cache: false,
    		timeout: groupUserSearchTimeout*1000,
    		beforeSend: function(request){
      		errorDiv.html("Processing search request...");
      		noteDiv.html("");
    		},
    		error: function(){
		  		errorDiv.html("");
        	alert('Error retrieving user list.');
   	 		},
    		success: function(html){
      		searchUsersSuccessHandler(html, errorDiv, noteDiv, availableMembersListBox)
    		}
  		});
	}
}

function searchUsersSuccessHandler(html, errorDiv, noteDiv, selectBox) {
  var response = $(html);
  if(response.is('#error')) {
    var errorMessage = response.filter('#error');
    errorDiv.html(errorMessage);
  } else {
    errorDiv.html("");
    noteDiv.html("Names prefixed with an * are distribution lists.");
  }
  var options = $('select>option', response);
  selectBox.html(options)
}

	function listBoxHasOptions(listBox) {
		return (listBox != null && listBox.options != null);
	}

	function removeAllListBoxOptions(fromListBox) {
		if (!listBoxHasOptions(fromListBox)) {
			return;
		}
		for (var i = (fromListBox.options.length - 1); i >= 0; i--) {
			fromListBox.options[i] = null;
		}
		fromListBox.selectedIndex = -1;
	}

	function addOptionToListBox(listBox, text, value) {
		if (listBoxHasOptions(listBox)) {
			listBox.options[listBox.options.length] = new Option(text, value, false, false);
		}
	}

