// This javascript file contains the ajax functions required by the Project Management StarterAPP

/*****************************************************************************************/
/****************************** Begin Main Ajax Functions ********************************/
/*****************************************************************************************/

/* Instantiate Ajax Object */
var AJAXObject = CreateAjaxObject();

/* Declare Ajax Content Variables */
var URL;
var Params;
var ConfirmationMessage;
var RemovalConfirmationText;
var ErrorMessage;

/* Create Ajax Object */
function CreateAjaxObject()
{
    var xmlhttp = false;
    try
    {
        xmlhttp = new XMLHttpRequest();
    }
    catch(e1)
    {   try
        {
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e2)
        {   try
            {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e3)
            {
                xmlhttp = false;
            }
        }
    }
    if (xmlhttp === false)
    {
        ErrorMessage = "Your browser does not support this action.\n";
        ErrorMessage+= "Error: " + e3.name + "\n";
        ErrorMessage+= "Description: " + e3.message + "\n.";
        alert(ErrorMessage);
    }
    return xmlhttp;
}

/* Begin Ajax Object Preparation */
function AjaxGet(URL)
{
    AJAXObject.open("GET", URL, true);
    AJAXObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    AJAXObject.onreadystatechange = AjaxGetResponseHandler;
    AJAXObject.send(null);
}

function AjaxGetResponseHandler()
{
    if (AJAXObject.readyState == 1) 
    {
        ShowLoadingMessage();
    }
    if (AJAXObject.readyState == 4) 
    {
        HideLoadingMessage();
        
        if (AJAXObject.status == 200) 
        {
            /* Get succeeded; show results */
            document.getElementById('ActionContent').innerHTML = AJAXObject.responseText;
        }
        
        if (AJAXObject.status == 500)
        {
            /* Get failed; show error message */
            ErrorMessage = '<table id="AjaxResponseText">';
            ErrorMessage+= '<tbody>';
            ErrorMessage+= '<tr>';
            ErrorMessage+= '<td class="FailureImage"><img alt="Error!" title="Error!" src="css/images/error.png"/></td>';
            ErrorMessage+= '<td class="FailureMessage">Error [http status: ' + AJAXObject.status + ']</td>';
            /* Uncomment the line below for debugging purposes.  It shows the error...  To ugly to leave in... 
            ErrorMessage+= '<tr><td>message: ' + AJAXObject.responseText + ']</td></tr>'; */
            ErrorMessage+= '</tr>';
            ErrorMessage+= '</tbody>';
            ErrorMessage+= '</table>';
            document.getElementById('ActionContent').innerHTML = "";
            document.getElementById('ActionContent').innerHTML = ErrorMessage;
        }
    }
}     

function AjaxPost(URL, Params)
{
    AJAXObject.open("POST", URL, true);
    AJAXObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    AJAXObject.onreadystatechange = AjaxPostResponseHandler;
    AJAXObject.send(Params);
}

function AjaxPostResponseHandler()
{
    if (AJAXObject.readyState == 1) 
    {
        ShowLoadingMessage();
	}

    if (AJAXObject.readyState == 4) 
    {
        HideLoadingMessage();
        if (AJAXObject.status == 500)
        {
            /* Post failed; show error message */
            ErrorMessage = '<table id="AjaxResponseText">';
            ErrorMessage+= '<tbody>';
            ErrorMessage+= '<tr>';
            ErrorMessage+= '<td class="FailureImage"><img alt="Error!" title="Error!" src="css/images/error.png"/></td>';
            ErrorMessage+= '<td class="FailureMessage">Error [http status: ' + AJAXObject.status + ']</td>';
             /* Uncomment for debugging purposes.  It shows the error...  To ugly to leave in... 
            ErrorMessage+= '<tr><td>message: ' + AJAXObject.responseText + ']</td></tr>'; */
            ErrorMessage+= '</tr>';
            ErrorMessage+= '</tbody>';
            ErrorMessage+= '</table>';
            document.getElementById('ActionContent').innerHTML = "";
            document.getElementById('ActionContent').innerHTML = ErrorMessage;
        }
        if (AJAXObject.status == 200) 
        {
            if( trim(AJAXObject.responseText).indexOf("-2") == 0 ) {	
                 ErrorMessage = '<table id="AjaxResponseText">';
                ErrorMessage+= '<tbody>';
                ErrorMessage+= '<tr>';
                ErrorMessage+= '<td class="FailureImage"><img alt="Error!" title="Error!" src="css/images/error.png"/></td>';
                ErrorMessage+= '<td class="FailureMessage">Client already exists.</td>';
                 /* Uncomment for debugging purposes.  It shows the error...  To ugly to leave in... 
                ErrorMessage+= '<tr><td>message: ' + AJAXObject.responseText + ']</td></tr>'; */
                ErrorMessage+= '</tr>';
                ErrorMessage+= '</tbody>';
                ErrorMessage+= '</table>';													
                document.getElementById('ActionContent').innerHTML = ErrorMessage;
            }
            else {
                /* Post succeeded; show results */																				
                document.getElementById('ActionContent').innerHTML = ConfirmationMessage;
                document.getElementById('ClientsAndProjectsList').innerHTML = AJAXObject.responseText;
            }
        }
    }
}     

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}


/* End Ajax Object Preparation */

/* Begin Messages & Cancel Action */
function ShowLoadingMessage()
{
    document.getElementById('Actions').style.display = "block";
    document.getElementById('ActionContent').style.display = "none";
    document.getElementById('AjaxLoadingMessage').style.display = "block";
}
function HideLoadingMessage()
{
    document.getElementById('Actions').style.display = "block";
    document.getElementById('ActionContent').style.display = "block";
    document.getElementById('AjaxLoadingMessage').style.display = "none";
}
function CancelAction()
{
    document.getElementById('Actions').style.display = "none";
    document.getElementById('ActionContent').innerHTML = "";
    document.getElementById('ActionContent').style.display = "none";
}
/* End Messages & Cancel Action */

/*****************************************************************************************/
/****************************** End Main Ajax Functions **********************************/
/*****************************************************************************************/



/*****************************************************************************************/
/****************************** Begin Client Ajax Functions ******************************/
/*****************************************************************************************/
function ShowAddClientForm()
{
    AjaxGet("Actions/ProjectActions.aspx?mode=showaddclient");
}

function AddClient()
{
    /* Set the URL to add a client */
    URL = "Actions/ProjectActions.aspx?mode=addclient";
    /* Set the AddClient Post param - the client's name */
    Params = "ClientName=" + escape(document.forms[0].ClientName.value);
    /* Set the message to be displayed upon successful addition of client */
    ConfirmationMessage = '<table id="AjaxResponseText"><tbody><tr>';
    ConfirmationMessage+= '<td class="SuccessImage"><img alt="Client Added" title="Client Added" src="css/images/pawn_add.png"/></td>';
    ConfirmationMessage+= '<td class="SuccessMessage">Client Added</td>';
    ConfirmationMessage+= '</tr></tbody></table>';
    /* Execute the Ajax Post */
    AjaxPost(URL, Params);
}

function RemoveClient(ClientName, ClientID)
{
    RemovalConfirmationText = 'Remove client: ' + ClientName + '?\n\n';
    RemovalConfirmationText += 'This action will permanently delete this client and all project content.\n';
    RemovalConfirmationText += 'This action cannot be undone.';
    
    ConfirmationBox=confirm(RemovalConfirmationText);
    if (ConfirmationBox===true)
    {
        /* Set the URL to remove a client */
        URL = "Actions/ProjectActions.aspx?mode=removeclient";
        /* Set the RemoveClient Post param - the client's id */
        Params = 'ClientID=' + ClientID;
        /* Set the message to be displayed upon successful removal of client */
        ConfirmationMessage = '<table id="AjaxResponseText"><tbody><tr>';
        ConfirmationMessage+= '<td class="SuccessImage"><img alt="Client Removed" title="Client Removed" src="css/images/pawn_delete.png"/></td>';
        ConfirmationMessage+= '<td class="SuccessMessage">Client Removed</td>';
        ConfirmationMessage+= '</tr></tbody></table>';
        /* Execute the Ajax Post */
        AjaxPost(URL, Params);
    }
} 
/*****************************************************************************************/
/****************************** End Client Ajax Functions ********************************/
/*****************************************************************************************/


/******************************************************************************************/
/****************************** Begin Project Ajax Functions ******************************/
/******************************************************************************************/
function ShowAddProjectForm(ClientID)
{
    AjaxGet("Actions/ProjectActions.aspx?mode=showaddproject&ClientID=" + ClientID);
}

function AddProject()
{
    /* Set the URL to add a project */
    URL = 'Actions/ProjectActions.aspx?mode=addproject';
    /* Set the AddProject Post params - the client's ID, and the project's name */
    Params = 'ClientID=' + document.forms[0].ClientList.options[document.forms[0].ClientList.selectedIndex].value;
    Params += '&ProjectName=' + escape(document.forms[0].ProjectName.value);
    /* Set the message to be displayed upon successful addition of project */
    ConfirmationMessage = '<table id="AjaxResponseText"><tbody><tr>';
    ConfirmationMessage+= '<td class="SuccessImage"><img alt="Project Added" title="Project Added" src="css/images/box_add.png"/></td>';
    ConfirmationMessage+= '<td class="SuccessMessage">Project Added</td>';
    ConfirmationMessage+= '</tr></tbody></table>';
    /* Execute the Ajax Post */
    AjaxPost(URL, Params);
}

function RemoveProject(ProjectName, ProjectID, ClientID)
{
    RemovalConfirmationText = "Remove Project: " + ProjectName + "?\n\n";
    RemovalConfirmationText += "This action will permanently delete all Project content.\n";
    RemovalConfirmationText += "This action cannot be undone.";

    ConfirmationBox = confirm(RemovalConfirmationText);
    if (ConfirmationBox === true)
    {
        /* Set the URL to remove project */
        URL = "Actions/ProjectActions.aspx?mode=removeproject";
        /* Set the remove project post params - the project id and the client id */
        Params = 'ProjectID=' + ProjectID + '&ClientID=' + ClientID;
        /* Set the message to be displayed upon successful removal of client */
        ConfirmationMessage = '<table id="AjaxResponseText"><tbody><tr>';
        ConfirmationMessage+= '<td class="SuccessImage"><img alt="Project Removed" title="Project Removed" src="css/images/box_delete.png"/></td>';
        ConfirmationMessage+= '<td class="SuccessMessage">Project Removed</td>';
        ConfirmationMessage+= '</tr></tbody></table>';
        /* Execute the Ajax Post */
        AjaxPost(URL, Params);
    }
}
/******************************************************************************************/
/****************************** End Project Ajax Functions ********************************/
/******************************************************************************************/



/********************************************************************************************/
/****************************** Begin Project EXISTING Member Functions *********************/
/********************************************************************************************/

/* This function retrieves a list of existing Membership users */
/* A user is selected from this is and added to a Project via AddMember() */
function ShowAddMemberForm(ClientID)
{
    AjaxGet("Actions/ProjectActions.aspx?mode=showaddmember&ClientID=" + ClientID);
}

/* This funciton adds an existing memeber to a Project by the user's id */
function AddMember(ClientID, MemberID)
{
    /* Set the URL to add a project */
    URL = 'Actions/ProjectActions.aspx?mode=addmember';
    /* Set the AddMember Post param(s) - the client's ID, and the project's name */
    Params = "ClientID=" + document.forms[0].ClientList.options[document.forms[0].ClientList.selectedIndex].value;
    Params += "&MemberID=" + document.forms[0].MemberList.options[document.forms[0].MemberList.selectedIndex].value;
    /* Set the reponse message upon successful addition of project */
    ConfirmationMessage = '<table id="AjaxResponseText"><tbody><tr>';
    ConfirmationMessage += '<td class="SuccessImage"><img alt="Member Added" title="Member Added" src="css/images/user1_add.png"/></td>';
    ConfirmationMessage += '<td class="SuccessMessage">Member Added</td>';
    ConfirmationMessage += '</tr></tbody></table>';
    /* Execute the Ajax Post */
    AjaxPost(URL, Params);
}

/* This funciton adds an existing memeber to a Project by the user's email address */
function AddMemberByEmail(ClientID, MemberEmail)
{
    /* Set the URL to add a project */
    URL = 'Actions/ProjectActions.aspx?mode=addmemberbyemail';
    /* Set the AddMember Post param(s) - the client's ID, and the project's name */
    Params = "ClientID=" + ClientID;
    Params += "&MemberEmail=" + MemberEmail;
    /* Set the reponse message upon successful addition of project */
    ConfirmationMessage = '<table id="AjaxResponseText"><tbody><tr>';
    ConfirmationMessage += '<td class="SuccessImage"><img alt="Member Added" title="Member Added" src="css/images/user1_add.png"/></td>';
    ConfirmationMessage += '<td class="SuccessMessage">Member Added</td>';
    ConfirmationMessage += '</tr></tbody></table>';
    /* Execute the Ajax Post */
    AjaxPost(URL, Params);
}

/* This funciton removes a memeber from a Project */
function RemoveMember(ClientID, MemberID, MemberName)
{
    RemovalConfirmationText = "Remove member: " + MemberName + " from client?\n\n";
    RemovalConfirmationText += "This action will remove " + MemberName + " from the list of authorized members of this client.\n";
    RemovalConfirmationText += "This action will not delete the member's account.\n";
    RemovalConfirmationText += "You may re-add this member to this client's list of authorized members at any time.";
    
    ConfirmationBox = confirm(RemovalConfirmationText);
    if (ConfirmationBox === true)
    {
        /* Set the URL to add a client */
        URL = "Actions/ProjectActions.aspx?mode=removemember";
        /* Set the RemoveMember Post param(s) */
        Params = 'MemberID=' + MemberID;
        Params += '&ClientID=' + ClientID;
        /* Set the reponse message upon successful addition of client */
        ConfirmationMessage = '<table id="AjaxResponseText"><tbody><tr>';
        ConfirmationMessage+= '<td class="SuccessImage"><img alt="Member Removed" title="Member Removed" src="css/images/user1_delete.png"/></td>';
        ConfirmationMessage+= '<td class="SuccessMessage">Member Removed</td>';
        ConfirmationMessage+= '</tr></tbody></table>';
        /* Execute the Ajax Post */
        AjaxPost(URL, Params);
    }
}

/********************************************************************************************/
/****************************** End Project EXISTING Member Functions ***********************/
/********************************************************************************************/


/********************************************************************************************/
/****************************** Begin Project ADD NEW Member Functions **********************/
/********************************************************************************************/


/* This function retrieves the register new member form elements */
function ShowRegisterNewMemberForm(ClientID)
{
    AjaxGet("Actions/ProjectActions.aspx?mode=showregisternewmember&ClientID=" + ClientID);
}

/* This function tests to see if all required fields have a value */
/* If so, it enables the 'Add' Button */
function NewMemberFormRequirements()
{
    var EnableAddButton = false;
    EnableAddButton = ValidateRegisterNewMemberFormElement('RegisterNewMemberControl_FirstName');
    if (EnableAddButton == true) {EnableAddButton = ValidateRegisterNewMemberFormElement('RegisterNewMemberControl_LastName');}
    if (EnableAddButton == true) {EnableAddButton = ValidateRegisterNewMemberFormElement('RegisterNewMemberControl_Password');}
    if (EnableAddButton == true) {EnableAddButton = ValidateRegisterNewMemberFormElement('RegisterNewMemberControl_ConfirmPassword');}
    if (EnableAddButton == true) {EnableAddButton = ValidateRegisterNewMemberFormElement('RegisterNewMemberControl_EmailAddress');}
    if (EnableAddButton == true) {EnableAddButton = ValidateRegisterNewMemberFormElement('RegisterNewMemberControl_DisplayName');}
    /* Don't bother checking User Language */
    /* It is not required and has a default value anyway */
    if (EnableAddButton == true) 
        {document.forms[0].RegisterNewMemberControl_AddButton.disabled=false;}
    else
        {document.forms[0].RegisterNewMemberControl_AddButton.disabled=true;}
}
/* This function goes with NewMemeberFormRequirements() */
function ValidateRegisterNewMemberFormElement(ElementID)
{
    var EnableAddButton = false;
    if (document.getElementById(ElementID).value != "")
        {EnableAddButton=true;}
    else
        {EnableAddButton=false;}
    return EnableAddButton;
}

/* This funciton registers a new membership user */
function RegisterNewMember(ClientID, ClientName)
{
    if (document.getElementById('RegisterNewMemberControl_Password').value != document.getElementById('RegisterNewMemberControl_ConfirmPassword').value) 
    {
        alert("Passwords do not match");
    } else { 
        var FirstName = document.getElementById('RegisterNewMemberControl_FirstName').value;
        
        if (FirstName.indexOf('&') != -1)
        {
            alert('Firstname cannot contain \'&\'');
            return false;
        }
        
        var LastName = document.getElementById('RegisterNewMemberControl_LastName').value;
        
        if (LastName.indexOf('&') != -1)
        {
            alert('Lastname cannot contain \'&\'');
            return false;
        }
        
        var DisplayName = document.getElementById('RegisterNewMemberControl_DisplayName').value;
        
        if (DisplayName.indexOf('&') != -1)
        {
            alert('Displayname cannot contain \'&\'');
            return false;
        }
        
         var Email = document.getElementById('RegisterNewMemberControl_EmailAddress').value;
        
        if (Email.indexOf('&') != -1)
        {
            alert('Email cannot contain \'&\'');
            return false;
        }
        
        /* Set the URL to register a new member */
        URL = 'Actions/ProjectActions.aspx?mode=registermember';
        /* Set the RegisterMember Post param - the ID of the client that user originally clicked */
        Params = "FirstName=" + FirstName;
        Params += "&LastName=" + LastName;
        Params += "&Password=" + document.getElementById('RegisterNewMemberControl_Password').value;
        Params += "&Email=" + Email;
        Params += "&DisplayName=" + DisplayName;
        Params += "&UserLanguage=" + document.forms[0].UserLanguage.options[document.forms[0].UserLanguage.selectedIndex].value;
        Params += "&ClientID=" + ClientID;
        /* Execute the Ajax Post */
        AjaxRegisterNewMemberPost(URL, Params);
    }
}

function AjaxRegisterNewMemberPost(URL, Params)
{
    AJAXObject.open("POST", URL, true);
    AJAXObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    AJAXObject.onreadystatechange = AjaxRegisterNewMemberPostResponseHandler;
    AJAXObject.send(Params);
}

function AjaxRegisterNewMemberPostResponseHandler()
{
    if (AJAXObject.readyState == 1) 
    {
        ShowLoadingMessage();
	}
    if (AJAXObject.readyState == 4) 
    {
        HideLoadingMessage();
        if (AJAXObject.status == 500)
        {
            /* Post failed; show error message */
            ErrorMessage = '<table id="AjaxResponseText">';
            ErrorMessage+= '<tbody>';
            ErrorMessage+= '<tr>';
            ErrorMessage+= '<td class="FailureImage"><img alt="Error!" title="Error!" src="css/images/error.png"/></td>';
            ErrorMessage+= '<td class="FailureMessage">Error [http status: ' + AJAXObject.status + ']</td>';
             /* Uncomment the line below for debugging purposes.  It shows the error...  To ugly to leave in... 
            ErrorMessage+= '<tr><td>message: ' + AJAXObject.responseText + ']</td></tr>'; */
            ErrorMessage+= '</tr>';
            ErrorMessage+= '</tbody>';
            ErrorMessage+= '</table>';
            document.getElementById('ActionContent').innerHTML = "";
            document.getElementById('ActionContent').innerHTML = ErrorMessage;
        }
        if (AJAXObject.status == 200) 
        {
            /* Post succeeded; show results */																				
            document.getElementById('ActionContent').innerHTML = AJAXObject.responseText;
        }
    }
}     
/********************************************************************************************/
/****************************** End Project ADD NEW Member Functions ************************/
/********************************************************************************************/