/**
 * Ajax.js
 *By Nagendra nath nayak
 * Collection of Scripts to allow in page communication from browser to (struts) server
 * ie can reload part instead of full page
 *
 * How to use
 * ==========
 * 1) Call makeHttpRequest from the relevant event on the HTML page (e.g. onclick)
 * 2) Pass the url to contact (e.g. Struts Action) and the name of the HTML form to post
 * 3) When the server responds ...
 *		 - the script loops through the response , looking for <span id="name">newContent</span>
 * 		 - each <span> tag in the *existing* document will be replaced with newContent
 *
 * NOTE: <span id="name"> is case sensitive. Name *must* follow the first quote mark and end in a quote
 *		 Everything after the first '>' mark until </span> is considered content.
 *		 Empty Sections should be in the format <span id="name"></span>
 */

//global variables
var req;
var which;
var modename;

/**
 * Get the contents of the URL via an Ajax call
 * url - to get content from (e.g. /struts-ajax/com.pdl.profile.do?ask=COMMAND_NAME)
 * nodeToOverWrite - when callback is made
 * nameOfFormToPost - which form values will be posted up to the server as part
 *					of the request (can be null)
 */


function compose(url, nameOfFormToPost, mode){
	var flag=true;
    modename=mode;
    if(document.getElementById('compose.receipient').value != "") {
        makeHttpRequest(url, nameOfFormToPost);
		var recipientObj = document.getElementById("compose.receipient");
		var subjectObj = document.getElementById("compose.subject");
		var messageObj = document.getElementById("compose.messages");
		
		if (recipientObj != null)
        document.getElementById("compose.receipient").value="";

		if (subjectObj != null)
		document.getElementById("compose.subject").value="";
			
		if (messageObj != null)
		document.getElementById("compose.messages").value="";
	}
    else
        alert('Please enter recipient id');
}


function updateProfile(url, nameOfFormToPost,mode){
    var flag=true;
    modename=mode;
    if(document.getElementById('displayName').value == "")
        alert("Name should not be left blank");
    else if(document.getElementById('zipcode').value == "")
        alert("Zipcode should not be left blank");
    else if(document.getElementById('birthDay.month').value == "00" ||
        document.getElementById('birthDay.day').value == "00" ||
        document.getElementById('birthDay.year').value == "0000")
        alert("Birthday should not be left blank");
    else{
        profileView();
        makeHttpRequest(url, nameOfFormToPost);

    }
}

function profileView(){

    document.getElementById("profileshow").style.display = "block";
    document.getElementById("profileedit").style.display = "none";
}
function profileEdit(){

    document.getElementById("profileshow").style.display = "none";
    document.getElementById("profileedit").style.display = "block";
}

function makeHttpRequest(url, nameOfFormToPost) {
    var params = null;
    if (nameOfFormToPost) {
        //get the (form based) params to push up as part of the POST request
        params = getFormAsString(nameOfFormToPost);
    }

    //Do the Ajax call
    staticbar();
    req = false;
    if (window.XMLHttpRequest) { // Non-IE browsers
        req = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // IE
        try {
            req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (E) {
                req = false;
            }
        }
    }
    if (!req) {
         alert('Cannot create XMLHTTP instance');
         return false;
    }

    req.onreadystatechange = processStateChange;
    req.open('POST', url, true);
    req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    req.setRequestHeader("Content-length", params.length);
    req.setRequestHeader("Connection", "close");
    req.send(params);
}

/*
 * Set as the callback method for when XmlHttpRequest State Changes
 * used by makeHttpRequest
 */
function processStateChange() {
    if (req.readyState == 4) { // Complete
        if (req.status == 200) { // OK response
            if(modename=="comment"){
                displayCommentStatus();
            } else if(modename=="myProfile"){
                replaceprofielsValues();
            } else if (modename=="commitment"){
                displayCommitmentStatus();
            } else if (modename=="saveContent") {
                displaySaveContentStatus();
            } else if (modename=="invitefriend") {
            	alert("Your invite has been sent.");
			 } else if (modename=="sendmail") {
            	displayMailStatus();	
            }else {
                //Split the text response into Span elements
                spanElements = splitTextIntoSpan(req.responseText);

                //Use these span elements to update the page
                replaceExistingWithNewHtml(spanElements);
            }
        } else {
			document.getElementById("loading").style.visibility="hidden";
            if(modename=="comment"){
                 alert('There was a problem submitting your comment.');
            }else if (modename=="commitment"){
                alert('There was a problem submitting your commitment.');
            } else if (modename=="saveContent") {
                alert('There was a problem saving this content to your profile.');
            } else if (modename=="sendmail") {
            	alert('Please enter a valid userid in the To field');
            }else {
                alert("Problem with server response:\n " + req.statusText);
            }
        }
        document.getElementById("loading").style.visibility="hidden";
        modename="";
    }
}

/**
 * gets the contents of the form as a URL encoded String
 * suitable for appending to a url
 * @param formName to encode
 * @return string with encoded form values , beings with &
 */
function getFormAsString(formName) {
    //Setup the return String
    returnString = "";
    //Get the form values
    formElements = document.forms[formName].elements;
    //loop through the array , building up the url
    //in the form /strutsaction.do&name=value
    for (var i = formElements.length - 1; i >= 0; --i) {
        //we escape (encode) each value
        returnString = returnString + "&" + encodeURIComponent(formElements[i].name) + "=" + encodeURIComponent(formElements[i].value);
    }
    //return the values
    return returnString;
}

/**
 * Splits the text into <span> elements
 * @param the text to be parsed
 * @return array of <span> elements - this array can contain nulls
 */
function splitTextIntoSpan(textToSplit) {
    //Split the document
    returnElements = textToSplit.split("</span>")
    //Process each of the elements
    for (var i = returnElements.length - 1; i >= 0; --i) {
        //Remove everything before the 1st span
        spanPos = returnElements[i].indexOf("<span");
        //if we find a match , take out everything before the span
        if (spanPos > 0) {
            subString = returnElements[i].substring(spanPos);
            returnElements[i] = subString;
        }
    }
    return returnElements;
}

/*
 * Replace html elements in the existing (ie viewable document)
 * with new elements (from the ajax requested document)
 * WHERE they have the same name AND are <span> elements
 * @param newTextElements (output of splitTextIntoSpan)
 *					in the format <span id=name>texttoupdate
 */
function replaceExistingWithNewHtml(newTextElements) {
    //loop through newTextElements
    for (var i = newTextElements.length - 1; i >= 0; --i) {
        //check that this begins with <span
        if (newTextElements[i].indexOf("<span") > -1) {
            //get the name - between the 1st and 2nd quote mark
            startNamePos = newTextElements[i].indexOf('"') + 1;
            endNamePos = newTextElements[i].indexOf('"', startNamePos);
            name = newTextElements[i].substring(startNamePos, endNamePos);
            //get the content - everything after the first > mark
            startContentPos = newTextElements[i].indexOf('>') + 1;
            content = newTextElements[i].substring(startContentPos);
            //Now update the existing Document with this element
            //check that this element exists in the document
            if (document.getElementById(name)) {
                //alert("Replacing Element:"+name);
                document.getElementById(name).innerHTML = content;
            } else {
        //alert("Element:"+name+"not found in existing document");
        }
        }
    }
}

function replaceprofielsValues() {
    var jsonData = req.responseText;
    var profileReturnObject = eval('(' + jsonData + ')');
    document.getElementById("profile_displayName").innerHTML = profileReturnObject.profileContent.displayName;
    document.getElementById("profile_gender").innerHTML = profileReturnObject.profileContent.gender;
    document.getElementById("profile_relationshipStatus").innerHTML = profileReturnObject.profileContent.relationshipStatus;
    //    document.getElementById("profile_hometown").innerHTML = profileReturnObject.profileContent.homeTown;
    document.getElementById("profile_city").innerHTML = profileReturnObject.profileContent.city;
    document.getElementById("profile_state").innerHTML = profileReturnObject.profileContent.state;
    document.getElementById("profile_zip").innerHTML = profileReturnObject.profileContent.zip;
    //    document.getElementById("profile_Birthday").innerHTML = profileReturnObject.profileContent.birthDay;
    //   document.getElementById("profile_PublicBirthday").innerHTML=profileReturnObject.profileContent.publicBirthday;
    document.getElementById("profile_MemberSince").innerHTML=profileReturnObject.profileContent.memberSince;
    document.getElementById("profile_Website").innerHTML=profileReturnObject.profileContent.website;
    document.getElementById("profile_Blog").innerHTML=profileReturnObject.profileContent.blog;
    document.getElementById("profile_Church").innerHTML=profileReturnObject.profileContent.church;
    document.getElementById("profile_Denomination").innerHTML=profileReturnObject.profileContent.denomination;
    document.getElementById("profile_Pastor").innerHTML=profileReturnObject.profileContent.pastor;
    document.getElementById("profile_Occupation").innerHTML=profileReturnObject.profileContent.occupation;
    document.getElementById("profile_Education").innerHTML=profileReturnObject.profileContent.education;
    //  alert("profile_HighSchool"+profileReturnObject.profileContent.techHigh);
    //    document.getElementById("profile_HighSchool").innerHTML=profileReturnObject.profileContent.techHigh;
    document.getElementById("profile_FavoriteInspirationalVerse").innerHTML=profileReturnObject.profileContent.favoriteInspirationalVerse;
    document.getElementById("profile_FavoriteBook").innerHTML=profileReturnObject.profileContent.favoriteBook;
    document.getElementById("profile_FavoriteMusic").innerHTML=profileReturnObject.profileContent.favoriteMusic;
    document.getElementById("profile_FavoriteMovies").innerHTML=profileReturnObject.profileContent.favoriteMovies;
    document.getElementById("profilecompletenesscount").innerHTML=profileReturnObject.profileContent.profileCompleteness+"%";
    document.getElementById("profilecompletenessimage").width=profileReturnObject.profileContent.profileBarCompleteness;
}

function inviteFriendByAjax(url, nameOfFormToPost, mode){
    var flag=true;
    modename=mode;
    makeHttpRequest(url, nameOfFormToPost);
}

function postComment(url, nameOfFormToPost,mode){
    var flag=true;
    modename=mode;
    makeHttpRequest(url, nameOfFormToPost);
    var titleObj = document.getElementById("cmTitle");
    var commentObj = document.getElementById("cmComment");

    if (titleObj != null)
        document.getElementById("cmTitle").value="";

    if (commentObj != null)
        document.getElementById("cmComment").value="";
}

function postCommitment(url, nameOfFormToPost) {
    modename='commitment';
    makeHttpRequest(url, nameOfFormToPost);
}

function saveContentToProfile(url, nameOfFormToPost) {
    modename='saveContent';
    makeHttpRequest(url, nameOfFormToPost);
}

function displayCommentStatus() {
    var jsonData = req.responseText;
    var commentReturnObject = eval('(' + jsonData + ')');
    var commentStatus = commentReturnObject.userComment.status;
    if (commentStatus == 'notLoggedIn') {
        alert('Please sign in or register to submit your comment.');
    } else if (commentStatus == 'success') {
		document.getElementById("loading").style.visibility="hidden";
        alert('Your comment was submitted successfully.');
    } else {
        alert('There was a problem submitting your comment.');
    }
}

function displayCommitmentStatus() {
    var jsonData = req.responseText;
    var commitmentReturnObject = eval('(' + jsonData + ')');
    var commitmentStatus = commitmentReturnObject.myCommitment.status;
    if (commitmentStatus == 'notLoggedIn') {
        alert('Please sign in or register to submit your commitment.');
    } else if (commitmentStatus == 'success') {
		document.getElementById("loading").style.visibility="hidden";
        alert('Your commitment was successfully added to your profile.');
    } else {
        alert('There was a problem submitting your commitment.');
    }
}

function displaySaveContentStatus() {
    var jsonData = req.responseText;
    var saveContentReturnObject = eval('(' + jsonData + ')');
    var status = saveContentReturnObject.saveContent.status;
    if (status == 'notLoggedIn') {
        alert('Please sign in or register to save content to your profile.');
    } else if (status == 'success') {
		document.getElementById("loading").style.visibility="hidden";
        alert('This content was successfully saved to your profile.');
    } else {
        alert('There was a problem saving this content to your profile.');
    }
}

function displayMailStatus() {
    var jsonData = req.responseText;
    var mailReturnObject = eval('(' + jsonData + ')');
    var status = mailReturnObject.profileContent.composestatus;
    if (status == 'notLoggedIn') {
        alert('Please sign in or register to send a mail.');
    } else if (status == 'Mail Sent successfully') {
        document.getElementById("messagesucess").style.display='block';
		setTimeout("clearMessage();",4000);
    } else {
        alert('Please enter a valid userid in the To field');
    }
}
function clearMessage(){
	document.getElementById("messagesucess").style.display='none';
}