﻿// *************** beginning of Post methods *************************
// ******************************************************************************************



postObj.prototype.build = function buildPost()
{

    //this.catGroup = +($("postList").options[$("postList").selectedIndex].value);
    this.catGroup = getPostCGid();
    this.cat = getCheckBoxes("postCB"+this.catGroup, "post");   //getCheckBoxes is defined in the Query build object
    this.lat = $("postLat").value;
    this.lon = $("postLon").value;
    matchAgeRanges(); this.ages = getCheckBoxes("postAge", "cbAge");   
    this.ageStr = getAgeRange();//$("postAgeStr").value;
    this.title = $("postTitle").value.trims();
    this.description = encTxtUpdate($("postDescription").value.trims());  //I encode existing updates ie "--- UPDATE (" into "!xyz1tk!"
    this.update = $("postPrayerUpdateText").value.trims()
    if ($("postPrayerAnswerCB").checked == true) {this.status = 1} else {this.status = 0}
    this.notifyMe = $("postNotifyMeCB").checked
    this.createdBy = myUser.memberID;
    //this.createdOn =                          //the date will be put in by the server
    this.web = $("postWeb").value.trims();   //need to do some http validation here
    //this.phone = $("postPhone").value.trims();
    //this.cost = $("postCost").value.trims();
    //this.time = $("postTime").value.trims();   
    
    this.dates = new Array();    //verify that I can pass an empty date array to server
    this.newFriends = new Array(); //need to create an array as this is passed to the server
    
    if ((this.catGroup == 10) || (this.catGroup == 60)){
        if ($("dateInputPost2").value == null || $("dateInputPost2").value == "")   // exact dates have been selected
        {
            var str = $("postDates").value;
            //str = str.slice(0,str.lastIndexOf(","))  //stripping the last comma
            var arr = new Array()
            arr = str.split(",")
            for (i=0; i<arr.length; i++)
            {
                if (i>=1){arr[i] = arr[i].slice(1)}  //strip the white space
                this.dates.push(Date.parseString(arr[i], "M/d/y"))
            }
            this.dateMin = new Date(); //returns today's date and time
            this.dateMin.setFullYear("1900")  
            this.dateMax = new Date(); //returns today's date and time
            this.dateMax.setFullYear("1900")                 
        }
        else
        {
            this.dateMin = Date.parseString($("dateInputPost2").value, "M/d/y")
            this.dateMax = Date.parseString($("dateInputPost3").value, "M/d/y")
            
            var arr = getCheckBoxes("postDay","cbDay");  //remove prefix cbDay from ids
            if (arr.length == 7) 
            {
                this.days = "";    //send an empty string if all check boxes are checked
            }
            else
            {
                this.days = arr.join(",")
            }          
        }    
    }
    else
    {
        this.dateMin = new Date();
        this.dateMax = new Date();
    }
    
    if (this.catGroup == 60)  //this code is also in find.js (sendToFriend())
    {
        // handle existing friends
        var arrID = getCheckBoxes("postFriendsCB", "cbFriend")
        this.friendsID = arrID
        
        //friendsEmail array will be passed to the server for sending email to friends
        var arrFriendEmail = getCheckBoxes("postFriendsCB", "")
        for (i=0; i<arrFriendEmail.length; i++)
        {
            arrFriendEmail[i] = $(arrFriendEmail[i]).className;   //the email is stored in the class attribute of the check box
        }
        this.friendsEmail = arrFriendEmail        
    
        
        // handle new friends
        if ($("postPDemails").value.trims() != "") //avoid email processing if user just typed a blank space
        {
            this.newFriends = $("postPDemails").value.split(",")
            for (i=0;i<this.newFriends.length;i++)    //trims leading and trailing white spaces in emails 
            {
                this.newFriends[i] = this.newFriends[i].trims()
            } 
                               
            //scrub new friends against friends list and eliminate dupes;  
            var arrEmail = getCheckBoxes("postFriendsCB", "")    //array of existing friends emails to be passed so the server can send email to them
            for (i=0;i<arrEmail.length;i++) 
            {
                arrEmail[i] = $(arrEmail[i]).className;   //the email is stored in the class attribute of the check box
            }            
            for (i=0;i<this.newFriends.length;i++)     
            {
                for (j=0;j<arrEmail.length;j++)
                {
                    if (this.newFriends[i] == arrEmail[j])
                    {
                        this.newFriends.splice(i,1)   //removes the element at index i from the array
                        break;
                    }
                }      
            }
        }
        else
        {
            this.newFriends = new Array();  //creating an array since the server expects one
        }
    }
}

function getAgeRange()
{
    var minIndex = $("minAgeList").selectedIndex  
    var minAge = $("minAgeList").options[minIndex].value
    var maxIndex = $("maxAgeList").selectedIndex  
    var maxAge = $("maxAgeList").options[maxIndex].value

    var ageRange = minAge + "," + maxAge;   //ageRange has already been validated
    return ageRange     
}

function setAgeRange(age)   //used in edit Post mode
{
        if (age == "") //reset age lists
        {
            $("minAgeList").selectedIndex = 0
            $("maxAgeList").selectedIndex = 0
        }
        var arr = age.split(",")
        for (i=0;i<$("minAgeList").options.length;i++)
        {
            if ($("minAgeList").options[i].value == arr[0])
            {
                $("minAgeList").selectedIndex = i;
                break
            }
        }
        for (i=0;i<$("maxAgeList").options.length;i++)
        {
            if ($("maxAgeList").options[i].value == arr[1])
            {
                $("maxAgeList").selectedIndex = i;
                break
            }
        }
}

function validateAgeRange()
{
    var valid = true
    var minIndex = $("minAgeList").selectedIndex  
    var minAge = $("minAgeList").options[minIndex].value
    var maxIndex = $("maxAgeList").selectedIndex  
    var maxAge = $("maxAgeList").options[maxIndex].value
    
    if (minAge == "100") {return valid}  //always valid in this vase
    if (maxAge == "-1") {return valid}  //always valid in this vase    
    if (+minAge > +maxAge)  //the plus sign converts a string to int and ensure the comparison works
    {
        valid = false;
    }
    return valid
}

function createAgeText(age)
{
    var ageText
    var arr = age.split(",")
    if (arr.length == 1) {ageText = arr[0]; return ageText}//legacy text that is not in the form "ageMin, ageMax", we just display it
    if (arr[0] == "100") {ageText = "all"; return ageText}
    if (arr[1] == "-1") {ageText = arr[0]; return ageText}
    if (arr[1] == "13") {ageText = arr[0] + " and up"; return ageText}
    if (arr[0] == arr[1]){ageText = arr[0]; return ageText}
    //else
    ageText = arr[0] + " to " + arr[1]
    return ageText
}

function matchAgeRanges()
{
    var minIndex = $("minAgeList").selectedIndex  
    var minAge = $("minAgeList").options[minIndex].value
    var maxIndex = $("maxAgeList").selectedIndex  
    var maxAge = $("maxAgeList").options[maxIndex].value
    
    var ageArray = document.getElementsByName("postAge")   //array of check boxes age ranges
    
    if (minAge == "100")   //we check all age rage check boxes and exit
    {
        for (i=0;i<ageArray.length;i++)
        {
            ageArray[i].checked = true;           
        }
        return
    }
    
    if (maxAge == "-1") {maxAge = minAge}  //if no maxAge specified, then minAge is the range becomes the exact age, ie minAge
    
    for (i=0;i<ageArray.length;i++)                                    //for each cb age range, see if the select minAge and maxAge match
    {
        ageArray[i].checked = false; //reset check box to empty
        var range = ageArray[i].value.split(",")            // the cb age range is stored in the attr Value, ex: Value = "2,3"
        var minB = range[0]  //check box min age
        var maxB = range[1]  //check box max age
    
        if ((+minAge <= +maxB) && (+maxAge >= +minB))     //the plus sign converts a string to int and ensure the comparison works
        { 
            ageArray[i].checked = true 
        }
    } 

}

/* function unused
function extractEmail(str)
{
    if (str.lastIndexOf(")") != -1)  // -1 is case of not found ie email only. ex: "john@msn.com"   //else case of name + email. ex: "John (john@msn.com)"
    {
        str = str.slice(0,str.lastIndexOf(")"))
        str = str.slice(str.lastIndexOf("(")+1)
    }
    return str
}
*/

/*
    str = "<div id='cttCtnr'>"
    str += "<div id='cttSum'>"
        str += "<div id='cttHeadr'>"
            str += "<div id='cttRating'><div id='cttCtrl'></div><div id='cttRateAct'></div></div>"
            str += "<div id='cttTitle'></div></div>"
        str += "</br><div id='cttDesc'><div id='cttPhotoCtnr'><div id='cttPhoto'></div><div id='cttPhotoMenu'></div></div><div id='cttTxt'></div></div>"
        str += "<div id='cttDtls'></div></div>"
    str += "<div id='cttCmt'><span id='cttCmtHdr'>No review yet.</span><a id='reviewLink' class='link' href='javascript:newReview(\""+CG+"\","+mapID+",\""+escape(postsTbl.rows[0].title)+"\")'>add review</a>"
    str += "<div id='cttReviews'></div></div></div>"

    resultDiv.innerHTML = str
*/

postObj.prototype.preview = function preview()
{
 
    //map.Clear();
    clearMbrPane()
    
    var str = "<div id='cttCtnr'>"
    
    str += "<div id='cttSum' style=\"filter:progid:DXImageTransform.Microsoft.Gradient(endColorstr='#f7fcfe', startColorstr='#E7F1F8', gradientType='0');\">"
    
    str += "<div id='cttHeadr'>"
    str += "<span id='cttTitle'>" 
    str += this.title 
    str += "</span>"
    str += "<nobr><span id='cttRating'>"
    if (this.catGroup != 60){ //don't insert rating control for playdate view
        str += "<span id='cttCtrl'><img src='icons/StarOffBlue.png'/>"
        str += "</span>"  
        str += "<span id='cttRateAct'>"
        if (this.status != 1) {
        str += "<a class='link' href='javascript:msgBox(escape(\"Preview message\"),escape(\"First submit your prayer request and you will then be able to light candles.\"),300,300);'>first to light a candle!</a>"
        } else { str += "Prayer Answered" }
        str += "</span>"
    }
    str += "</span></nobr>"     
    str += "</div>"  //end headr div
    
    str += "<div id='cttDesc'><div class='cttPhotoCtnr'><div id='cttPhoto'>"
    str += "<img src='"+photoFolder+"/"+defaultPhoto+"'/></div>"
    str += "<div id='cttPhotoMenu'><a class='link' href='javascript:msgBox(escape(\"Preview message\"),escape(\"First submit your prayer request and you will then be able to add photos.\"),300,300);'><img src='icons/icon-photo.gif' class='navIcon'/>add photo</a>"
    str += "</div></div>"    
    str += "<div id='cttTxt'>"
    if (this.update != "") 
    {
        var myDate = new Date();
        var currentDate = myDate.format("MMM d, yyyy")
        str += decHtmUpdate(this.description) + "<div class='update'>update <span>(" + currentDate + ")</span></div>" + this.update 
    }
    else {
        str += decHtmUpdate(this.description)  
    }
    str += "</div></div>"
    
    str += "<div id='cttDtls'><br/>"
    
    if ((this.catGroup == 10) || (this.catGroup == 60))   //Event case
    {
        str += "<div class='dtlDiv'><span class='dtlTitle'>dates: </span><span class='dtlValue'>"
        if ($("dateInputPost2").value == null || $("dateInputPost2").value == "")  //case of exact dates
        {            
            str += $("postDates").value
        }
        else    //case of date range
        {
            str += $("dateInputPost2").value + " to " + $("dateInputPost3").value                                        
            var arr = getCheckBoxes("postDay","cbDay");  //remove prefix cbDay from ids
            if (arr.length != 7) 
            {
                for (i=0;i<arr.length;i++) {arr[i] = dayName(arr[i])}
                str += " (" + arr.join(",") + ")"
            }        
        }
        str += "</span></div>"
    }
   
        if ((this.time != null) && (this.time != ""))        
    {str += "<div class='dtlDiv'><span class='dtlTitle'>time: </span><span class='dtlValue'>"+this.time+"</span></div>"}     
    //    if ((this.ageStr != null) && (this.ageStr != ""))
    //{str += "<div class='dtlDiv'><span class='dtlTitle'>age: </span><span class='dtlValue'>"+createAgeText(this.ageStr)+"</span></div>"} 
        if ((this.cost != null) && (this.cost != ""))
    {str += "<div class='dtlDiv'><span class='dtlTitle'>cost: </span><span class='dtlValue'>"+this.cost+"</span></div>"}  
        if ((this.phone != null) && (this.phone != ""))
    {str += "<div class='dtlDiv'><span class='dtlTitle'>phone: </span><span class='dtlValue'>"+this.phone+"</span></div>"}  
        if ((this.web != null) && (this.web != ""))
    {var link = createLink(this.web);
    str += "<div class='dtlDiv'><span class='dtlTitle'>link: </span><span class='dtlValue'>"+link+"</span></div>"}   
    
    str += "</div>"   //end div cttDtls  
    
    str += "<div id='cttSumBottom'><div id='cttCreatedBy'>"
    str += "prayer request from: <a class='mbrLink' href='javascript:msgBox(escape(\"Preview message\"),escape(\"First submit your prayer request and you will then be able to view your profile from it.\"),300,300);'>"+myUser.display+"</a>"
    str += "</div>"  //end cttCreatedBy
    
    if (this.catGroup != 60){
        // add send to friend and bookmark links
    str += "<div id='cttTopMenu'>"
    str += "<a id='stfLink' class='link' href='javascript:msgBox(escape(\"Preview message\"),escape(\"First submit your prayer request and you will then be able to share it with friends.\"),300,300);'><img src='icons/icon-mail.gif' class='navIcon'/>send to friend</a>";
    //str += "<br/><a id='bookmarkLink' class='link' href='javascript:msgBox(escape(\"Preview message\"),escape(\"First submit your prayer request and you will then be able to bookmark it.\"),300,300);'><img src='icons/icon-bookmark.gif' class='navIcon'/>bookmark</a>"
    str += "</div>"
    }
    else { str += "<div id='cttTopMenu'>"
        str += "<a id='pdReplyBut' class='link' href='javascript:msgBox(escape(\"Preview message\"),escape(\"First submit your post and you will then be able to edit your reply.\"),300,300);'>Reply</a>"    
        str += "</div>" 
    }
        
    str += "</div></div>"   //end divs cttSumBottom, cttSum
    if (this.catGroup != 60){ 
    str += "<div id='cttCmt'><div id='cttCmtHdr'>First to respond...</div><span id='cttNewReview'>"
    }else{
    str += "<div id='cttCmt'><span id='cttCmtHdr'>"
    replyEmpty = 0; replyYes = 1; replyMaybe = 0; replyNo = 0; 
    str += "Replies:  "+ replyYes + "<img class='icon' src='icons/dotGreen.png'/>, "+ replyMaybe +"<img class='icon' src='icons/dotYellow.png'/>, " + replyNo + "<img class='icon' src='icons/dotRed.png'/>, "+ replyEmpty + "<img class='icon' src='icons/dotWhite.png'/>" ;
    str+= "</span><span id='cttNewReview'>"
    }
    if (this.catGroup != 60){
    if (this.status != 1){    
    str += "<a class='reviewPrayBut' href='javascript:msgBox(escape(\"Preview message\"),escape(\"First submit your prayer request and you will then be able to add a response\"),300,300);'>Pray</a>"
        } else { str += "<div class='PrayerAnsweredDiv'>Prayer Answered !</div>" }    
    } else{
    //str += "<a id='pdReplyBut' class='link' href='javascript:msgBox(escape(\"Preview message\"),escape(\"First submit your new post and you will then be able to edit your reply.\"),300,300);'>Reply</a>"    
    }
    str += "</span>"
    
    if (this.catGroup == 60)
    { 
        str += "<div id='cttReviews'>"   
                //add organizer
            thumbnail = photoFolder+"/"+mbrDefaultThumbnail    
            str += "<hr class='cmtLine'/><div class='cttReview'><div class='mbrBit'><img src='"+thumbnail+"'/><div></div></div><div class='rvwBlock'>"
            str += "<span class='rvwTitle'>"+myUser.display+" (organizer)</span><span id='rvwRating"+i+"'>"+createReply(1)+"</span><div class='rvwDesc'></div></div></div>"
        
            reviewStr = "";
               //add each member comment
            for(var i = 0; i < this.friendsEmail.length; i++)
            {
                reviewStr += "<hr class='cmtLine'/>"
                reviewStr += "<div class='cttReview'>"
                reviewStr += "<div class='mbrBit'><img src='"+thumbnail+"'/><div></div></div>"
                reviewStr += "<div class='rvwBlock'>"         
                reviewStr += "<span class='rvwTitle'>"+this.friendsEmail[i]+"</span>"
                reviewStr += "<span>"+createReply(0)+"</span>"
                reviewStr += "</div></div>"   
            }
            for(var i = 0; i < this.newFriends.length; i++)
            {
                reviewStr += "<hr class='cmtLine'/>"
                reviewStr += "<div class='cttReview'>"
                reviewStr += "<div class='mbrBit'><img src='"+thumbnail+"'/><div></div></div>"
                reviewStr += "<div class='rvwBlock'>"         
                reviewStr += "<span class='rvwTitle'>"+this.newFriends[i]+"</span>"
                reviewStr += "<span>"+createReply(0)+"</span>"
                reviewStr += "</div></div>"   
            }

        str += reviewStr    
        str += "</div>"
    } //end playdate case
    
    str += "</div></div>"

    //we now need to create a temp div to it can be rounded with Nifty and its content passed to the pin description  
    //padding the string str above directly to the addPin function will not show rouned corners
    
      //create temp div
    var tempDiv = document.createElement("div")
    tempDiv.id = "delmeDiv"
    tempDiv.className = "myPopUpDiv"
    tempDiv.lang= "pv"                      // pv is the preview pin id
    $("wrapper").appendChild(tempDiv)
    $("delmeDiv").innerHTML = str
    
      //round temp div
    Nifty("div#delmeDiv", "top transparent");   //BUG BUG: ironically without Nifty, the pop up does not display cttSum content...
    Nifty("div#cttSum", "transparent");
    Nifty("div#cttCtnr", "top transparent");
    if (document.all)  {  // round buttons for IE only (Firefox forces a left float on the anchor which makes the buttons uncentered. Attenpts to center on Firefox didn't work
        Nifty("a.reviewPrayBut", "small transparent")   //round the Reply button - need to use 'small' rouding otherwise this makes the text inside the button disappear
    }
     
      //add pin with description  
    var str1 = "<div class='myPopUpDiv' id='delmeDiv' lang='pv'>"
    str1 += escape($("delmeDiv").innerHTML)
    str1 += "</div>"
    addPin("pv", this.lat, this.lon, str1)
    var VElatlon = new VELatLong(this.lat, this.lon)
    map.SetCenterAndZoom(VElatlon, 5)
    mapPrayerRequest("pv", this.lat, this.lon)  
    
      //delete temp div  
    $("delmeDiv").parentNode.removeChild($("delmeDiv"))    
       
}
/*
function postPinHover(x, y, title, details)   //this method to create a custom VE pop up comes from the article: http://www.soulsolutions.com.au/Articles/PopupContentonDemand/tabid/98/Default.aspx
{
    var pinID = title;
    //var CGmapID = details;
    var divID = "VPOP" + pinID;
    var e=$(pinID+"_"+map.GUID);
    if(e!=null&&e!="undefined")
    {    
        //window.ero.setBoundingArea(new Microsoft.Web.Geometry.Point(0,0), new Microsoft.Web.Geometry.Point(document.body.clientWidth, document.body.clientHeight));
        window.ero.setContent("<div class='myPopUpDiv' id='" + divID + "'></div>");  //if I set the ero content directly with details, the pop shows the info about the pin, while in this case it will show it below which is consistent with the find pinhover function
        window.ero.dockToElement(e);
 
        var resultDiv = $(divID);
        resultDiv.innerHTML = details;
 
        Nifty("div.myPopUpDiv", "top transparent");   //BUG BUG: ironically without Nifty, the pop up does not display cttSum content...
        Nifty("div#cttSum", "transparent");
        Nifty("div#cttCtnr", "top transparent");
        if (document.all)  {  // round buttons for IE only (Firefox forces a left float on the anchor which makes the buttons uncentered. Attenpts to center on Firefox didn't work
            Nifty("a.reviewPrayBut", "small transparent")   //round the Reply button - need to use 'small' rouding otherwise this makes the text inside the button disappear
        }

    }
} */

postObj.prototype.send = function send()
{
   
    //checks have already been performed during wizard progression
    
    disableBut("postSubmitBut")     
    PageMethods.postNewEntry(myUser.memberID, myUser.email, myUser.display, this.catGroup, myUser.lat, myUser.lon, this.cat, this.ages, this.title, this.description, this.notifyMe, this.web, this.cost, this.ageStr, this.phone, this.time, this.days, this.dates, this.dateMin, this.dateMax, this.friendsID, this.newFriends, this.friendsEmail, $("postPDEmailSuject").value.trims(), $("postPDEmailBody").value.trims(), $("postCCme").checked, onPostResult, onPostError);
    
}
     
        function onPostResult(resultTable)              //columns CGmapID, lat, lon, title, description, primaryPic  (CGmapID column contains mapID)
        {
            //alert("New post was added successfully; " + success); 
            CGid  = getPostCGid();
            clearPostPane();
            var CG = "PR"
            var mapID = resultTable.rows[0].mapID
            var title = resultTable.rows[0].title
            var title1 = escape(resultTable.rows[0].title)
            var description = resultTable.rows[0].description
            var lat = resultTable.rows[0].lat
            var lon = resultTable.rows[0].lon
            var thumbnail = mbrPic(myUser.primaryPic)
            
            if (CGid != 60)  //case of regular post, not a playdate
            {
                var contentStr = "Your request has been added to Faithmap and soon our caring community will pray with you."
                contentStr += "<br/><br/>Your request is also available under the 'My Faithmap' button, where you can update it, add photos and view prayer responses." 
                contentStr += "<br/><br/>If you'd like to send your prayer request to your friends so they can pray with you, <a class='' href='javascript:closeMsgBox();pickFriends(\""+CG+"\","+mapID+",\""+title1+"\");'>click here</a>."
                contentStr += "<br/><br/>Also please consider praying for others on Faithmap. Everyone is welcome to pray and every prayer counts.<br/>Blessings"
                msgBox1("Thank you", contentStr, 300, 200);
                myUser.postCount += 1;
                if ((App.myMap) && ($("myMapNavBut").className == "activelink"))            //if the myMap code has been downloaded (ie user has already clicked on myMap button and the button is active (this guarantees that it's the user's profile and not another's user
                {
                    try{$("tabberDiv").getElementsByTagName("ul")[0].getElementsByTagName("a")[0].firstChild.nodeValue = "Prayer Requests"// ("+myUser.postCount+")"
                    }catch(err){}  //updating post tab title         
                    getPosts(myUser.memberID)          // I should replace this with a client update of the myMap page based on the post returned by this function to ovoid querying the server again
                }              
            }
            else
            {
                disablePlaydateWiz()
                msgBox("Congratulation!", "Your playdate has been successfully created and sent to your friends! <br/><br/>You can now see it by mousing over the pin on the map. Your playdate is also kept under the 'My petiteMap' playdate tab where you can come back to check your friends replies, add photos and make updates.", 300, 200);
                myUser.playdateCount += 1;
                if ((App.myMap) && ($("myMapNavBut").className == "activelink"))            //if the myMap code has been downloaded (ie user has already clicked on myMap button and the button is active (this guarantees that it's the user's profile and not another's user
                {
                    try{$("tabberDiv").getElementsByTagName("ul")[0].getElementsByTagName("a")[3].firstChild.nodeValue = "Playdates"// ("+myUser.playdateCount+")"
                    }catch(err){}  //updating post tab title         
                    getPlaydates()          // I should replace this with a client update of the myMap page based on the post returned by this function to ovoid querying the server again
                }                 
            }
            
            mapResults(resultTable);
            
            //need to clear the infobox so it requeries the server and show the prayer response
            var id = CG + mapID
            //clearInfoBox(id);
             // redisplay the infobox so user can see their prayer request
            var myShape = getShapeByLinkID(id);
            displayInfoBox(myShape);
            
            //add newest prayer to most recent prayer list so user doesn't have to refresh/requery the prayer list               
            var myTabber = $('tabberDivFind').tabber;
            var j = getTabberIndex(myTabber)     
            if (j == 0) //only add prayer item if most recent tab is active.
            {    
                var divID = "findRequests"+j   //this is how the id was constructed when the prayer list was built (see createPrayerList())              
                var prayerList = $(divID) 

                if (prayerList)
                {
                    newItem = createPrayerItem(divID, myUser.memberID, myUser.display, thumbnail, lat, lon, mapID, title, description, 0)                
                    var firstItem = prayerList.firstChild
                    prayerList.insertBefore(newItem, firstItem)
                }
             }       
            
            findButton()
            
            enableBut("postSubmitBut");
            
        }
         
         
        function onPostError()
        {
            msgBox("Oops!", "Could not add this new prayer request.", 300);
        }



//UI mechanics Post panel functions


function findLocPin()   //same as the findLoc function (in ui.js) except that it also adds a pin on the map
{
    map.Clear();
    map.ShowDisambiguationDialog(false);
    //map.FindLocation($('postAddrInput').value, onFoundResultsPin);
    map.Find(null,$('postAddrInput').value,null,null,null,null,null,null,false,null,onFoundResultsPin);
}

    function onFoundResultsPin(ShapeLayer,FindResult,Place,HasMore)
    {
        if (Place.length > 1)
        {
            var results="More than one result were found on the map. Please pick one:<ul>";
            for (x=0; x<Place.length; x++)
            {
               results+="<li><a href='javascript:closeMsgBox();checkPostDupes(\""+Place[x].Name+"\",\""+Place[x].LatLong.Latitude+"\",\""+Place[x].LatLong.Longitude+"\");'>"+Place[x].Name+"</a></li>";
            }
            results+="</ul>";
            msgBox("Faith Map", results, 300, 100);

         }
         else
         { checkPostDupes(Place[0].Name,Place[0].LatLong.Latitude,Place[0].LatLong.Longitude)  }
    }

    function checkPostDupes(address, lat, lon)
    {
        CGid = getPostCGid()   //the CGid will be converted into a CG on the server
        if (CGid == 60)  //in case of playdate we don't check for dupes, so add pin directly
        {
            addLocPin(address, lat, lon)
            $("postWiz1").style.display = "none"
            $("postWiz2").style.display = "block"
            $("postTitle").focus();   
        }
        else
        {
            PageMethods.checkPostDuplicates(CGid, lat, lon, address, onPostDupesResult, onPostDupesError)  
        }
    }
    
        function onPostDupesResult(table)  //returns CG, mapID, lat, lon, title, address
        {
            if (table.rows.length > 1)
            {
                var str = "One or more pinpost was already created for this address. Click on the link(s) below to display and review existing pinpost(s) for that address and make sure you are not creating a duplicate pinpost.<br/><br/>" 
                str += "If a pinpost already exists, you can add a review for it by selecting 'add review' inside the pinpost popup balloon.<br/><br/>"
                str += "Close this dialog and the Post dialog to cancel your new pinpost creation, or click on the Next button to continue creating a new pinpost for that address.<br/><br/><ul>"
                for (i=0; i<(table.rows.length - 1); i++)   //the last row is the user new address returned
                {
                    CGmapID = table.rows[i].CG + table.rows[i].mapID;                           
                    str += "<li><a href='javascript:addPin(\""+CGmapID+"\", \""+table.rows[i].lat+"\", \""+table.rows[i].lon+"\", null)'>"+table.rows[i].title+" ("+table.rows[i].address+")</a></li>"; 
                }
                str += "</ul>"
                //str += "<<br/><br/>a id='cancelNewPost' class='but' href='javascript:cancelNewPost();'>Cancel</a><a id='continueNewPost' class='but' href='javascript:addLocPin(\""+table.rows[i].address+"\", \""+table.rows[i].lat+"\", \""+table.rows[i].lon+"\")'>Continue</a>";
                msgBox("petite map", str, 250);
                //Nifty ("a#cancelNewPost","transparent");     //rounding buttons
                //Nifty ("a#continueNewPost","transparent");
            } 
            //the last row is the newly creating address (on the server side I manually added the new address as a way to get it back on the client and continue the post entry)
            n = (table.rows.length - 1)
            addLocPin(table.rows[n].address, table.rows[n].lat, table.rows[n].lon)
            
            $("postWiz1").style.display = "none"
            $("postWiz2").style.display = "block"
            $("postTitle").focus();
        
        }
        
        function onPostDupesError()
        {
          msgBox("Oops!", "Could not verify if items already exist for this address.", 300);      
        }
        
    
    
    function addLocPin(address, lat, lon)
    {
        
        map.Find(null,address,null,null,null,null,null,null,false,null,null)
        //map.FindLocation(address) //ensures that the map centers on address
        var latlong = new VELatLong(lat, lon)
        //var pin = new VEPushpin(pinID, latlong, null, "<span style='color:#4d5aaf'>Address:</span>", address)
        //VEPushpin.ShowDetailOnMouseOver = true;             //important since this was set to false in Find mode
        
        var str = "<div id='cttCtnr'><div id='cttSum'>" + address + "</div></div>"
        
        var pin = new VEPushpin(pinID, latlong, null, pinID + "", str);    // pinID + "" converts mapID into a string type
        VEPushpin.ShowDetailOnMouseOver = false;       
        VEPushpin.OnMouseOverCallback = postPinHover;      

        map.AddPushpin(pin);
        pinID++;
        $("postLat").value = lat;   //stores the lat and lon on the form for later retrieval when creating the query
        $("postLon").value = lon;
    }




function fillPostCat()
{
    //this function will fill the Categories area in the Post pane with all category names and their checkboxes
    //another function will then hide the irrelevant cats based on the user cat group selection.
    //it uses the two arrays, CatDesc and CatID that are dynamically created and sent on by the server on page load
    var mycheckbox;
    var mycheckboxname; //category group name of the check box so I can later retrieve them according to selected group (in above list box)
    var myspan;
    var mycbtext;
    var spanid;
    var lb;
    var mydiv
    var str
    
    for (i in CatID)
    {
        //each checkbox gets the category database id and category group name for future reference
        mycheckboxname = "postCB"+CatID[i].toString().charAt(0)+"0"         //name is different than the checkboxes in the Find dialog
        //mycheckbox = document.createElement("<input id='post"+CatID[i]+"' name='"+mycheckboxname+"' type='checkbox'>")  //Firefox errors on the html inside createElement
        //mycheckbox = document.createElement('input')          //getElementByName(), IE does not recognize the check box name when created this way!
        mycheckbox = createElementWithName("input", mycheckboxname)
        mycheckbox.type = "checkbox"
        mycheckbox.id = "post"+CatID[i]
        //mycheckbox.name = mycheckboxname

        //create a span so I can style checkbox text specifically 
        myspan = document.createElement('span')
        myspan.id = "postSpan"+CatID[i];
        //create checkbox text within the span
        mycbtext = document.createTextNode(CatDesc[i]);
        mycbdiv = document.createElement('div')
        mycbdiv.id = "div"+CatID[i]

        mydiv = $("postCheckCat");
        
        mydiv.appendChild(mycbdiv)
        mycbdiv.appendChild(mycheckbox);
        mycbdiv.appendChild(myspan);        
        myspan.appendChild(mycbtext);

    }

}

function showPostCat(CGid)
{
    if (CGid == 60) {return}  //case of playdate, we don't diplay the category section since it is not used
    
    for (i in CatID)
    {
        var n = CGid.toString().charAt(0)
        
        if (CatID[i].toString().charAt(0) == n)
        {
            $("div"+CatID[i]).style.display = "block"
        }
        else { $("div"+CatID[i]).style.display = "none" }
    }
}

/*function showPostCat()
{

    for (i in CatID)
    {
        var index=$("postList").selectedIndex
        var n=$("postList").options[index].value.charAt(0)
        
        if (CatID[i].toString().charAt(0) == n)
        {
            $("div"+CatID[i]).style.display = "block"
        }
        else { $("div"+CatID[i]).style.display = "none" }
    }
}*/


function updateDates()
{
    if ($("postDates").value.charAt(0) == "-")  //this is to clear the help text which starts with "- click..."
    {
        $("postDates").value = ""; 
        $("postDates").value += $("dateInputPost1").value;
        clearDateRange();  //make sure the date range fields are clear since user is entering exact dates.
    }
    else  //there's already a date and we add to it separating with a comma
    {
        $("postDates").value += ", " +$("dateInputPost1").value;
    }
    $("postDates").style.color = "black";

}

function clearDateExact()
{
    $("postDates").value = "- click calendar icon ->";
    $("postDates").style.color = "gray"
}

function clearDateRange()
{
    $("dateInputPost2").value = "";
    $("dateInputPost3").value = "";
    arr = getCheckBoxes("postDay","")
    for (i=0;i<arr.length;i++)
    {
        $(arr[i]).checked = false;
    }
}

function nextWizPage0()
{
    CGid = getPostCGid();
    if (CGid == null) {msgBox("Oops!", "Please select a category type.", 300); return;}
    showPostCat(CGid);
    $("postWiz0").style.display = "none"
    $("postWiz1").style.display = "block"
    $("postAddrInput").focus();
   
}

function getPostCGid()
{
    var arr = new Array();
    arr = document.getElementsByName("postCG")
    for (i=0;i<arr.length;i++)
    {
        if (arr[i].checked)
        {
            CGid = arr[i].value
            return CGid    
        }
    } 
    return null;
}       


function nextWizPage1()
{
    //check that address field is not empty
    if (isEmpty($("postAddrInput")))
    {
        msgBox("Oops!", "Please first fill out the address field.", 300, 100);
        return
    }
    
    findLocPin()
    
}

function nextWizPage2()
{
    //verfiy that the title and description are not empty
    if (isEmpty($("postTitle")))
    {
        msgBox("Oops!", "Please provide a title.", 300);
        return
    }
    if (isEmpty($("postDescription")))
    {
        msgBox("Oops!", "Please provide a description.", 300);
        return
    }    
    CGid  = getPostCGid();
    if ((CGid == 10) || (CGid == 60))  //in case of event or playdate we show the date fields
    {$("postDatesDiv").style.display = "block"}
    else {$("postDatesDiv").style.display = "none"}
  
    $("postWiz2").style.display = "none"
    $("postWiz3").style.display = "block"

}

function backWizPage1()
{
    $("postWiz0").style.display = "block"
    $("postWiz1").style.display = "none"
}


function backWizPage2()
{
    $("postWiz1").style.display = "block"
    $("postWiz2").style.display = "none"
}

function backWizPage3()
{
    $("postWiz2").style.display = "block"
    $("postWiz3").style.display = "none"
}

function backWizPage4()
{
    //CGid  = getPostCGid();
    //if (CGid == 60) {$("postWizPD").style.display = "block"}//in case of playdate, go back to friends wiz page
    //else{ $("postWiz3").style.display = "block"}
    
    $("postWiz2").style.display = "block"
    $("postWiz4").style.display = "none"
    
    //remove preview pin from map
    var myShape = getShapeByLinkID("pv");
    if (myShape) {map.DeleteShape(myShape); CustomHideInfoBox(myShape)}
}

function preview(PD)
{
    $("postCG20").checked = true  //make sure prayer request group is selected (ie 20)
    $("postLat").value = myUser.lat;   //stores the lat and lon on the form for later retrieval when creating the query
    $("postLon").value = myUser.lon;

        //verfiy that the title and description are not empty
    if (isEmpty($("postTitle")))
    {
        msgBox("Oops!", "Please provide a title.", 300);
        return
    }
    if (isEmpty($("postDescription")))
    {
        msgBox("Oops!", "Please provide a description.", 300);
        return
    }    
    
    if (PD) {valid = validateWizPD()} //checks that user entered correct emails etc
    else {valid = validateWiz3();}  //checks that user entered categories, ages and dates
    
    if (valid) {    
        myPost = new postObj();
        myPost.build();
        myPost.preview();
        $("postWiz2").style.display = "none"  //PR change
        $("postWiz3").style.display = "none"
        $("postWizPD").style.display = "none"
        $("postWiz4").style.display = "block"
    }
}

function validateWiz3()
{
    //verify that categories and ages have been chosen (same code as in the build() function
    //CG = +($("postList").options[$("postList").selectedIndex].value);
    valid = true;
    
    CGid = getPostCGid();
    var cat = new Array();
    var ages = new Array();
    cat = getCheckBoxes("postCB"+CGid, "post"); 
    if (cat.length == 0) {msgBox("Oops!", "Please select one or more category for this item.", 300);valid = false;return valid}
    //ages = getCheckBoxes("postAge", "cbAge");   
    //if (ages.length == 0) {msgBox("Oops!", "Please select one or more age range for this item.", 300);valid = false;return valid}
    var ageCheck = validateAgeRange()
    if (!ageCheck) {msgBox("Oops!", "This age range is not valid. Please correct the selected ages.", 300);valid = false;return valid}
    //check dates
    if ((CGid == 10) || (CGid == 60))
    {
        var days = getCheckBoxes("postDay","");   
        if (($("postDates").value.charAt(0) == "-") && (days.length == 0) && ($("dateInputPost2").value == "") && ($("dateInputPost3").value == ""))
        {msgBox("Oops!", "Please select a timeframe for this event either by picking one or more dates, or by specifying a time interval and applicable week days.", 300);valid = false;return valid}
        if ($("postDates").value.charAt(0) == "-")
        {
            if (days.length == 0) {msgBox("Oops!", "Please select one or more day for this event.", 300);valid = false;return valid}
            if ($("dateInputPost2").value == "") {msgBox("Oops!", "Please select a start date for this event.", 300);valid = false;return valid}
            if ($("dateInputPost3").value == "") {msgBox("Oops!", "Please select an end date for this event.", 300);valid = false;return valid}
        }
    }
    return valid;
}

function postNew()
{
    myPost = new postObj();
    myPost.build();
    myPost.send();
}   

function cancelNewPost()
{
    /*  this is now moved into clearPostPane()
    CGid = getPostCGid();
    if (CGid == 60) //case of playdate
    {
            disablePlaydateWiz();   //morph wiz back to pinpost mode
    }  
    */
    //remove preview pin from map
    var myShape = getShapeByLinkID("pv");
    if (myShape) {map.DeleteShape(myShape); CustomHideInfoBox(myShape)}
    clearPostPane()
}

function cancelEditPost()
{    
    //revert wizard modifications (made for edit)
    $("myMapPane").style.display = "block";
    deactivateNavButtons()
    $("myMapNavBut").className = "activelink";
    //$("postList").disabled = "";
    //$("postWiz2BackBut").style.display = "block";
    $("postSubmitBut").href = "javascript:postNew();";
    //$("postSubmitBut").onclick = function(){postNew();}; 
    
    $("postCloseBut").href = "javascript:cancelNewPost();";   
    //$("postCancelBut1").onclick = function(){cancelNewPost();};    
    //$("postCancelBut2").onclick = function(){cancelNewPost();}; 
    //$("postCancelBut3").onclick = function(){cancelNewPost();}; 
    //$("postCancelBut4").onclick = function(){cancelNewPost();}; 
    
    disablePlaydateEdit()
    
    //remove preview pin from map
    var myShape = getShapeByLinkID("pv");
    if (myShape) {map.DeleteShape(myShape); CustomHideInfoBox(myShape)}
    
    clearPostPane()
}

function dateRange(action, days, dateMin, dateMax)   //creating a dateRange object so it can be passed by reference to the comparePost function
{
    this.action = action            //int telling the server what to do - 1:add, 2:change, 3:delete
    this.days = days                // postObj.days
    this.dateMin = dateMin
    this.dateMax = dateMax
}

function postEdit()
{
    myPost = new postObj();
    myPost.build();
    
    var main = new Array();    //array containing the main post fieds that have changed, ie title and/or description
    var mainRef = new Array();     //array references that includes the fields name (as opposed to values) so the server know what value correspond to what field name (ex: title/Marymoor)
    var details = new Array();      //array containing the post fields details that have changed, ie ageStr, time, cost, phone, web
    var detailsRef = new Array();
    var catDel = new Array();       //categories to delete
    var catAdd = new Array();       //categories to add
    var ageDel = new Array();       //ages to delete
    var ageAdd = new Array();
    var dateExactAdd = new Array();
    var dateExactDel = new Array();
    
    var myDateRange = new dateRange(0, "", new Date(), new Date());
    
    //var dateRangeAction = 0            //int telling the server what to do - 1:add, 2:change, 3:delete, 0:nothing (ignore dateRange parameters)
    //var days = ""   //string
    //var dateMin = new Date();
    //var dateMax = new Date();
    
    var friendAdd = new Array();
    var friendEmailAdd = new Array();
    var notifyOldFriends = getNotification();  // 0: notify new friends only;  1:notify all friends
    var oldFriendsID = new Array();  //this array and array below are either empty (if user chooses not to notify original invitees or equal to postRef.friendsID
    var oldFriendsEmail = new Array();
    var emailSubject = $("postPDEmailSuject").value.trims()
    var emailBody = $("postPDEmailBody").value.trims()
    var ccMe = $("postCCme").checked
    var updated //bool passed to the server so we know to send email to subscribers to that prayer request
    if (myPost.update == "") {updated = false} else {updated = true}
    
    if (comparePost(postRef, myPost, main, mainRef, details, detailsRef, catDel, catAdd, ageDel, ageAdd, dateExactDel, dateExactAdd, myDateRange, friendAdd, friendEmailAdd, notifyOldFriends, oldFriendsID, oldFriendsEmail))
    {   
        disableBut("postSubmitBut");
        PageMethods.updatePost(myUser.memberID, myUser.email, myUser.display, postRef.catGroup, postRef.mapID, main, mainRef, details, detailsRef, catDel, catAdd, ageDel, ageAdd, dateExactDel, dateExactAdd, myDateRange.action, myDateRange.days, myDateRange.dateMin, myDateRange.dateMax, friendAdd, friendEmailAdd, myPost.newFriends, oldFriendsID, oldFriendsEmail, emailSubject, emailBody, ccMe, updated, onUpdatePostResult, onUpdatePostError) 
        
        postUpdated = myPost  //storing the current post so we can add refresh the prayer list on at end of call back below
        postUpdated.mapID = postRef.mapID  //mapID was not set when building myPost
        postUpdated.ratingTotal = postRef.ratingTotal  //ratingTotal was not set when building myPost
    }   
    else {msgBox("Oops", "No changes have been detected. To close this window, click the close (x) button.", 300) }

} 

    function onUpdatePostResult()
    {
        CGid = getPostCGid();  //this needs to happen before clearPostPane() or all category options are cleared
        clearPostPane();
        $("myMapPane").style.display = "block";  //bring back the MyMap window
        
        if (CGid != 60)
        {
            msgBox("Thank you", "Your prayer request has been updated.", 300);
            mapMyMapItems("Posts") //show the edited item on the map (the check box is still selected when I bring the MyMap window back)
            
            getPosts(myUser.memberID)          // I should replace this with a client update of the myMap page based on the post returned by this function to ovoid querying the server again

        }
        else  //case of playdate
        {
            msgBox("congrats!", "Your playdate was successfully updated.", 300);
            mapMyMapItems("Playdates") //show the edited item on the map (the check box is still selected when I bring the MyMap window back)

        }
        //revert wizard modifications (made for edit)
        $("myMapPane").style.display = "block";
          //switch active button
        deactivateNavButtons()
        $("myMapNavBut").className = "activelink";
        //$("postList").disabled = "";
        //$("postWiz2BackBut").style.display = "block";
        $("postSubmitBut").href = "javascript:postNew();";
        //$("postSubmitBut").onclick = function(){postNew();}; 
        $("postCloseBut").href = "javascript:cancelNewPost();";   
        //$("postCancelBut1").onclick = function(){cancelNewPost();};    
        //$("postCancelBut2").onclick = function(){cancelNewPost();}; 
        //$("postCancelBut3").onclick = function(){cancelNewPost();}; 
        //$("postCancelBut4").onclick = function(){cancelNewPost();}; 

        //refresh post title in MyMap posts tab
        
        //disablePlaydateWiz()
        //disablePlaydateEdit()
        
        //add updated prayer to top most recent prayer list so user doesn't have to refresh/requery the prayer list               
        var updated //bool passed to the server so we know to send email to subscribers to that prayer request
        if (postUpdated.update == "") {updated = false} else {updated = true}
        if ((updated) && (!(postUpdated.status == 1)))  //if post has been updated and prayer is not answered
        {
            //remove existing item from prayer list if there
            var prayerItem = $("prayerfindRequests0PR"+postUpdated.mapID)
            if (prayerItem)  //don't add if the prayer item is not present
            { 
                prayerItem.parentNode.removeChild(prayerItem);
                //add it to the prayer list
                var myTabber = $('tabberDivFind').tabber;
                var j = getTabberIndex(myTabber)     
                if (j == 0) //only add prayer item if most recent tab is active.
                {    
                    var divID = "findRequests"+j   //this is how the id was constructed when the prayer list was built (see createPrayerList())              
                    var prayerList = $(divID) 

                    if (prayerList)
                    {
                        newItem = createPrayerItem(divID, myUser.memberID, myUser.display, mbrPic(myUser.primaryPic), myUser.lat, myUser.lon, postUpdated.mapID, postUpdated.title, postUpdated.description, postUpdated.ratingTotal)                
                        var firstItem = prayerList.firstChild
                        prayerList.insertBefore(newItem, firstItem)
                    }
                 } 
             }        
        } else if ((updated) && ((postUpdated.status == 1)))  //prayer answered
             {
                 //remove existing item from prayer list if there
                var prayerItem = $("prayerfindRequests0PR"+postUpdated.mapID)
                if (prayerItem)  //don't add if the prayer item is not present
                {
                    prayerItem.parentNode.removeChild(prayerItem);
                    //add it to the prayer list
                    var myTabber = $('tabberDivFind').tabber;
                    var j = getTabberIndex(myTabber)     
                    if (j == 2) //only add prayer item if 'prayer answered!' tab is active.
                    {    
                        var divID = "findRequests"+j   //this is how the id was constructed when the prayer list was built (see createPrayerList())              
                        var prayerList = $(divID) 

                        if (prayerList)
                        {
                            newItem = createPrayerItem(divID, myUser.memberID, myUser.display, mbrPic(myUser.primaryPic), myUser.lat, myUser.lon, postUpdated.mapID, postUpdated.title, postUpdated.description, postUpdated.ratingTotal)                
                            var firstItem = prayerList.firstChild
                            prayerList.insertBefore(newItem, firstItem)
                        }
                     } 
                 }
             }
        
        enableBut("postSubmitBut")
    }
    
    function onUpdatePostError()
    {
         msgBox("Oops!", "Could not update prayer request.", 300);

    }

function getNotification()
{
    arr = document.getElementsByName("postPDnotification")
    for (i in arr)
    {
        if (arr[i].checked == true)
        {
            return arr[i].value
        }
    }

}
 
function comparePost(oldPost, newPost, main, mainRef, details, detailsRef, catDel, catAdd, ageDel, ageAdd, dateExactDel, dateExactAdd, dateRange, friendAdd, friendEmailAdd, notifyOldFriends, oldFriendsID, oldFriendsEmail)
{
    var changed = false;    //flag if any of the post fields were changed
    
    if (oldPost.title != newPost.title)
    {
        main.push(newPost.title)
        mainRef.push("title")
        changed = true
    }
    
    if (newPost.update != "") 
    {
        var myDate = new Date();
        var currentDate = myDate.format("MMM d, yyyy")
        //var newDescription = newPost.description + enc("\r\n\r\nUPDATE (") + currentDate + enc("):\r\n") + newPost.update 
        // I add tokens for the new update
        var newDescription = newPost.description + "!xyz1tk!" + currentDate + "!zyx1tk!" + newPost.update  //!xyz1tk! and !zyx1tk! are the begining and end markers of an update header, will be decoded by the UI and formatted
        main.push(newDescription)
        mainRef.push("description")
        changed = true
    }
    else
    {
        if (oldPost.description != newPost.description) 
        {
            main.push(newPost.description)
            mainRef.push("description")
            changed = true
        }   
    }
    
    if (oldPost.status != newPost.status)
    {
        main.push(newPost.status)
        mainRef.push("status")
        changed = true
    }    
    
    if (oldPost.notifyMe != newPost.notifyMe)
    {
        main.push(newPost.notifyMe)
        mainRef.push("notifyMe")
        changed = true
    }   
    
 /*
    if (oldPost.ageStr != newPost.ageStr)
    {
        details.push(newPost.ageStr)
        detailsRef.push("age")
        changed = true
    }
    if (oldPost.time != newPost.time)
    {
        details.push(newPost.time)
        detailsRef.push("time")
        changed = true
    }
    if (oldPost.cost != newPost.cost)
    {
        details.push(newPost.cost)
        detailsRef.push("cost")
        changed = true
    }
    if (oldPost.phone != newPost.phone)
    {
        details.push(newPost.phone)
        detailsRef.push("phone")
        changed = true
    }
 */   
    if (oldPost.web != newPost.web)
    {
        details.push(newPost.web)
        detailsRef.push("web")
        changed = true
    }
    
    for (i in oldPost.cat)
    {
        del = true
        for (j in newPost.cat)
        {   
            if (newPost.cat[j] == oldPost.cat[i]){del = false; break};
        }
        if (del) {catDel.push(oldPost.cat[i]); changed = true};
    }
    
    for (i in newPost.cat)
    {
        add = true
        for (j in oldPost.cat)
        {   
            if (oldPost.cat[j] == newPost.cat[i]){add = false; break};
        }
        if (add) {catAdd.push(newPost.cat[i]); changed = true};
    }   
 /*      
    for (i in oldPost.ages)
    {
        del = true
        for (j in newPost.ages)
        {   
            if (newPost.ages[j] == oldPost.ages[i]){del = false; break};
        }
        if (del) {ageDel.push(oldPost.ages[i]); changed = true};
    }
    
    for (i in newPost.ages)
    {
        add = true
        for (j in oldPost.ages)
        {   
            if (oldPost.ages[j] == newPost.ages[i]){add = false; break};
        }
        if (add) {ageAdd.push(newPost.ages[i]); changed = true};
    }   
 */   
    if ((newPost.catGroup == 10) || (newPost.catGroup == 60)) //there are 4 scenarios: 2 where user make changed within same date mode (dateExact mode and dateRange mode), 2 where users switch date mode (ie from dateExact to dateRanger)
    {
        if ((oldPost.dateMin.getFullYear() == "1900") && (newPost.dateMin.getFullYear() == "1900"))   //case of exact dates before and after edit
        {       
            for (i in oldPost.dates)
            {
                del = true
                for (j in newPost.dates)
                {   
                    if (newPost.dates[j].toLocaleString() == oldPost.dates[i].toLocaleString()){del = false; break};  //need to convert date to string to compare otherwise "==" does not work
                }
                if (del) {dateExactDel.push(oldPost.dates[i]); changed = true};
            }
            
            for (i in newPost.dates)
            {
                add = true
                for (j in oldPost.dates)
                {   
                    if (oldPost.dates[j].toLocaleString() == newPost.dates[i].toLocaleString()){add = false; break};
                }
                if (add) {dateExactAdd.push(newPost.dates[i]); changed = true};
            }       
        }
        
        if ((oldPost.dates.length == 0) && (newPost.dates.length == 0))  //case of date range before and after edit
        {
            if ((oldPost.days != newPost.days) || (oldPost.dateMin.toLocaleString() != newPost.dateMin.toLocaleString()) || (oldPost.dateMax.toLocaleString() != newPost.dateMax.toLocaleString()))  //if one field changes I update all three on the server
            {
                dateRange.days = newPost.days
                dateRange.dateMin = newPost.dateMin
                dateRange.dateMax = newPost.dateMax
                dateRange.action = 2   //changed
                changed = true
            }       
        }
        
        if ((oldPost.dateMin.getFullYear() == "1900") && (newPost.dates.length == 0)) //users switched from exact dates to date range
        {
            for (i in oldPost.dates)   //delete all exact dates
            {
                dateExactDel.push(oldPost.dates[i]);
            }        
            //padd new date Range
            dateRange.days = newPost.days
            dateRange.dateMin = newPost.dateMin
            dateRange.dateMax = newPost.dateMax
            dateRange.action = 1   //add
            changed = true
        
        }
        
        if ((oldPost.dates.length == 0) && (newPost.dateMin.getFullYear() == "1900"))  //user switched from date range to exact dates
        {
            for (i in newPost.dates)   //add these new exact dates
            {
                dateExactAdd.push(newPost.dates[i]);
            }        
            //don't need to pass the date range since it will be erased
            dateRange.action = 3   //add            
            changed = true
        }
    
    }
    
    if (newPost.catGroup == 60)  //playdate case
    {
        for (i in newPost.friendsID)
        {
            add = true
            for (j in oldPost.friendsID)
            {   
                if (oldPost.friendsID[j] == newPost.friendsID[i]){add = false; break};
            }
            if (add) 
            {
                friendAdd.push(newPost.friendsID[i]); 
                friendEmailAdd.push(newPost.friendsEmail[i]);
                changed = true
            }
        }
        
        if (newPost.newFriends.length > 0) {changed = true}  //new Friends have been entered
        
        if (notifyOldFriends)  // either 0 for "notify new friends only" or 1 for "notify all friends"
        {
            oldFriendsID = oldPost.friendsID
            oldFriendsEmail = oldPost.friendsEmail
        }
        
    }
    
    return changed
}


function clearPostPane()
{
    CGid = getPostCGid();
    if (CGid == 60) //case of playdate
    {
            disablePlaydateWiz();   //morph wiz back to pinpost mode
    }  
    
    //clear category group options   
    var arr = new Array()
    arr = document.getElementsByName("postCG")
    for (i=0;i<arr.length;i++)
    {
        arr[i].checked = false;
    }
    
    //clear user text fields
    $("postAddrInput").value = "";
    $("postLat").value = "";
    $("postLon").value = "";
    
    $("postTitle").value = "";
    $("postDescription").value = "";
    $("postPrayerUpdateText").value = "";
    $("postPrayerAnswerCB").checked = false;
    $("postNotifyMeCB").checked = false;
    setAgeRange("");  //$("postAgeStr").value = "";
    //$("postTime").value = "";
    //$("postCost").value = "";
    //$("postPhone").value = "";
    $("postWeb").value = "";
       
    //clear all check boxes
    for (i in CatID)
    {
        $("post"+CatID[i]).checked = false;
    }
    //reset catgroup drop down 
    //$("postList").selectedIndex = 0
    //showPostCat()
    
    clearDateExact()
    clearDateRange()
    
    //clear days
    var arrDays = new Array()
    arrDays = document.getElementsByName("postDay");
    for (i=0;i<arrDays.length;i++)
    {
        arrDays[i].checked = false;
    }
    
    //clear ages
    var arrAges = new Array()
    arrAges = document.getElementsByName("postAge");
    for (i=0;i<arrAges.length;i++)
    {
        arrAges[i].checked = false;
    }     
    
    $("postWiz0").style.display = "none"
    $("postWiz1").style.display = "none"
    $("postWiz2").style.display = "block"
    $("postDatesDiv").style.display = "none"  
    $("postWiz3").style.display = "none"
    $("postWiz4").style.display = "none"
    $("postPane").style.display = "none"
    
    //hide the prayer update fields
    $("postPrayerUpdateLabel").style.display = "none"; 
    $("postPrayerUpdateText").style.display = "none"; 
    $("postPrayerAnswer").style.display = "none"; 
    //hide "show categories link" and show categories block
    $("showCategoriesLink").style.display = "none"; 
    $("postCatLabel").style.display = "block"; 
    $("postCheckCat").style.display = "block"; 
    //hide "show more details link" and show details block
    $("showPostMoreDetails").style.display = "block"; 
    $("postMoreDetails").style.display = "none"; 
    
    clearInfoBox("pv")  //make sure we hide the preview box if opened
    
    //map.Clear();
    clearMbrPane()
    //deactivate Poat and Playdate nav buttons
    $("postNavBut").className = ""; 
    //$("playdateNavBut").className = "";
    App.postDirty = false;
    App.playdateDirty = false;
}

function showPostCategories()
{
    //hide "show categories link" and show categories block
    $("showCategoriesLink").style.display = "none"; 
    $("postCatLabel").style.display = "block"; 
    $("postCheckCat").style.display = "block"; 
}

function showPostDetails()
{
    //hide "show more details link" and show details block
    $("showPostMoreDetails").style.display = "none"; 
    $("postMoreDetails").style.display = "block"; 
}
