﻿
// Global variables

var App = new AppObj(false, false, false, false, false)   //the Post and myMap functionality have not been downloaded yet
var myUser = new userObj(true, false) //user is new and not logged in by default  
var postRef = new postObj()          //will be used as the reference (original) post when a user edits a post to detect edits  
var postUpdated = new postObj()      //stores a post that has been udpated so I can later create a prayer item and refresh the prayer list
var cmtRef = new cmtObj()            //will be used as the reference (original) comment when a user edits a comment to detect edits     
 
var map = null;
var pinID = 1; 
//global var for the map infobox
var _hide;
var _currentShape = null;
var _isPanning = false; 

var photoFolder = "photos";
var mbrFolder = "members";
var defaultPhoto = "mbrDefault1.jpg"  //"defaultPin.jpg";
var mbrDefaultPhoto = "mbrDefault1.jpg";
var mbrDefaultThumbnail = "mbrDefaultThumb.jpg";

var iconPath = "icons/"
var pinIconEV = iconPath + "pin-small-pink.gif"
var pinIconPG = iconPath + "pin-small-green.gif"
var pinIconSC = iconPath + "pin-small-dblue.gif"
var pinIconCL = iconPath + "pin-small-lblue.gif"
var pinIconDC = iconPath + "pin-small-lyellow.gif"
var pinIconPD = iconPath + "pin-small-red.gif"
var pinIconPR = iconPath + "pin-candle-dark.gif"   //"pin-small-red.gif"
var pinIconCandle = iconPath + "pin-candle-bright.gif"

var pinTinyEV = iconPath + "pin-tiny-pink.gif"
var pinTinyPG = iconPath + "pin-tiny-green.gif"
var pinTinySC = iconPath + "pin-tiny-dblue.gif"
var pinTinyCL = iconPath + "pin-tiny-lblue.gif"
var pinTinyDC = iconPath + "pin-tiny-lyellow.gif"

var userSearch = false;  //bool telling if user pushed the find button

var tabberOptions = 
{                 
  /* Optional: code to run when the user clicks a tab. If this
     function returns boolean false then the tab will not be changed
     (the click is canceled). If you do not return a value or return
     something that is not boolean false, */

  'onClick': setTabberOnClick    //this function will be called when a user clicks a tabber (either Find or myMap tabber)
};
    
function setTabberOnClick(argsObj) {  

    var t = argsObj.tabber; /* Tabber object */
    var id = t.id; /* ID of the main tabber DIV */
    var i = argsObj.index; /* Which tab was clicked (0 is the first tab) */
    t.index = i  //store i in tabber.index property so we later know which tab was clicked
    var e = argsObj.event; /* Event object */
    var memberID = t.memberID //t.memberID is reset every time fillMyMapPane is called

    if (id == "tabberDiv") {  //if myMap tabber assign below function to onClick event
        switch (i)
        {
            //case 0:                   //Favorites tab array index is 0
            //getFavorites(memberID);break;
            case 0:                  //Posts tab array index is 2
            getPosts(memberID);break;
            case 1:
            getReviews(memberID);break;      //return confirm('Swtich to '+t.tabs[i].headingText+'?\nEvent type: '+e.type);  //original example of code usage
            //case 3:
            //getPlaydates();break;    //other's playdates can not be seen                 
            case 2:
            getMyMapPhotos(memberID);break;    
            default:                                  
        }   
     }
     else {      //if Find tabber assign below function to onClick event
        switch (i)
        {
            case 0:                   //Most recent prayers tab
                find(0); break;
            case 1:                    // Most prayed prayers tab
                find(1); break; 
            case 2:                     //Answered prayers tab
                find(2); break;       
        }                   
     }
}


// retrieves Enter key when user signs in
function getLoginEnterKey(event) {
    if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13))  //Firefox syntax then IE
    {	
	    //do stuff
	    if ($("loginPane").style.display == "block")
		{
		    login();
		}
    }
}

// retrieves Enter key when user signs in
function getFindEnterKey(event) {
    if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13))  //Firefox syntax then IE
    {	
	    //do stuff
	    if ($("findPane").style.display == "block")
		{
		    find();
		}
    }
}
           
function init()
{
    
    // creates both mymap and find tabbers
    tabberAutomatic(tabberOptions);   //this creates a tabber only the first time it is called (then the orginal class names are not found because they were changed when run the first time)           
    $('tabberDivFind').tabber.index = 0 //initializes index to the first tab (in case the onload recent prayer request fails, the error message will be shown inside that tab and we need to know its index

    //detectBrowser()
    
    //$("nav").firstChild.firstChild.focus()  //give focus to the "Find an activity" button since I'm showing the Find dialog on load
    $("findPane").style.display = "block";  

    fillAccordion();            
    new Accordian('findAccordion',5,'header_highlight');
    
    roundCorners()
    //initFindDateChooser()
    checkCookie() 
    getMap()                           //initializes main page

    if (myUser.newuser == true)         // first time users with no cookies are geolocated (based on IP address)
    {
        var located = false
        try                             // make sure that we don't break if the IP location fails (ex: IP hidden)
        {    
            //located = myUser.locate()
        }
        catch (err) { }  //return
        
        if (located == true)
        {
            // myUser.log()
        }
     }
     else    //lccate user om map based on it's lat, lon retrieved from cookies
     {
        //var mapCenter = new VEPixel(300,300)
        //map.SetCenterAndZoom(map.PixelToLatLong(mapCenter), 4) 
        //map.SetCenterAndZoom(new VELatLong(35, -105), 4)  //zoom used to be 10
     }
     
     map.AttachEvent("onchangeview", currentView);  //when user moves the map, we display "current view" in the find city field 
     //$("userLoc").focus(); 
     
     dbFind(0)
     
     /*  this block has been moved to the call back function of dbFind(0)
     if (showPinpost)    //if showing a pinpost such as prayer request was requested on load (thru the URL)
     {
        CGid = showPinpost[0]; 
        mapID = showPinpost[1]; 
        mbrID = showPinpost[2]; 
        
        CG = convertToCG(CGid)
        PageMethods.getMapItem(CG, mapID, onMapItemResult, onMapItemError); 

        //
        if (mbrID)
        {
            if (myUser.memberID)  //case where an existing user is getting a playdate invite that doesn't belong to her
            {
                if (myUser.memberID != mbrID) 
                {logOut("noPrompt")}          //we need to log her out first so there's no conflict with myUser.memberID
            }       
            myUser.memberID = mbrID;
        }
        
     }
     else 
     {  
        
     }    
     */
     
     if (newRegistration)  //if the user has just completed registration (by clicking email link). Registration either succeeded or failed
     {
        if (newRegistration == "success")
        {
           msgBox("Welcome!", "Your registration is now complete. Please sign in to have access to all site features.", 300)
           loginButton()       
        }
        else 
        {
            if (newRegistration == "failed")
            {
                msgBox("Oops!", "Sorry we could not complete this registration. Please sign up again.", 300)  
                joinButton()               
            }
        } 
     }       
}

    function onMapItemResult(resultTable)
    {
        if (resultTable.rows)  //if data is returned
        {
            var CGmapID = resultTable.rows[0].CG + resultTable.rows[0].mapID;        //ie PG203, contains a concatenation of the table category group and the mapID
            var lat = resultTable.rows[0].lat
            var lon = resultTable.rows[0].lon 
            clearFindPane();
            deactivateNavButtons()
            addPin(CGmapID, lat, lon, null)            
            //mapPrayerRequest(CGmapID, lat, lon)          
            var VElatlon = new VELatLong(resultTable.rows[0].lat, resultTable.rows[0].lon)
            map.SetCenterAndZoom(VElatlon, 5);
            
            var myShape = getShapeByLinkID(CGmapID);
            displayInfoBox(myShape);
            
            var response = showPinpost[3]
            if (response)  { doNothing() } // we're showing a new prayer response to someone who posted a request
            else //we're showing a prayer invitation
            {
                msgBox("Welcome to Faithmap", "Here is your prayer invitation.<br/><br/>To respond to this prayer request, click the golden 'Pray' button. Thank you.", 300)  
            }
        }
        else
        {
            onMapItemError()
        }
    }

    function onMapItemError()
    {
         msgBox("Oops!", "Could not get map item.", 300)  
    }

function getMap()
{
    map = new VEMap('myVEMap');
    map.SetDashboardSize(VEDashboardSize.Small);
    var mapCenter = new VELatLong(38,-108);
    map.LoadMap(mapCenter);

    map.AttachEvent("onmousedown", OnMouseDown);
    map.AttachEvent("onmousemove", OnMouseMove);
    map.AttachEvent("onmouseup", OnMouseUp);
    map.AttachEvent("onmouseover", OnMouseOver);
    map.AttachEvent("onclick", OnClick);
    map.AttachEvent("onstartpan", OnStartPan);
    map.AttachEvent("onstartzoom", OnStartZoom);

    VEShape.prototype.linkID = ""; // this is my own defined property to store the Prayer ID
    VEShape.prototype.mapID = ""; //this is the mapID associated to a userID (linkID) so we can query for the user prayer response to that mapID

    //reposition the default map dashboard (navigation control)
    var dsb = $("myVEMap_dashboard");
    //dsb.style.top = "370px";
    //dsb.style.left = "0px";
    $("mapDashboard").appendChild($("myVEMap_dashboard"));

}  

// map events redefined to achieve onclick experience of info boxes (popups) - hack copied from: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2523717&SiteID=1 
       //////////////////////////////////////////////////
        function OnMouseDown(e)
        {
            if (e.leftMouseButton)
                _isPanning = true;
        }

        //////////////////////////////////////////////////
        function OnMouseMove(e)
        {
            if (_isPanning)
                CustomHideInfoBox(_currentShape);
        }

        //////////////////////////////////////////////////
        function OnMouseUp(e)
        {
            _isPanning = false;
        }
        
        //////////////////////////////////////////////////
        function OnMouseOver(e)
        {
            return true;
        }

        //////////////////////////////////////////////////
        function OnClick(e)
        {
            if (e.elementID)
            {
                var clickedShape = map.GetShapeByID(e.elementID);
                displayInfoBox(clickedShape)
            }
        }

        //////////////////////////////////////////////////
        function displayInfoBox(clickedShape)
        {
            if (clickedShape)
            {
                if (window.ero.isVisible() && (clickedShape == _currentShape) )
                {
                    // We clicked on the shape which has an infobox open.
                    CustomHideInfoBox(_currentShape);
                }
                else 
                {
                    if (window.ero.isVisible())
                    {
                        // We clicked on a different shape. Close the infobox first,
                        // then show it for the new shape.                      
                        CustomHideInfoBox(_currentShape);
                    }
                    //if (clickedShape._isDrawn)  //we shouldn't show the infobox if the shape is not visible on the map 
                    //{  
                        getInfoBoxContent(clickedShape)                       
                        CustomShowInfoBox(clickedShape);
                    //}
                    //else {}    
                }
            }
        }
        //////////////////////////////////////////////////
        function OnStartPan(e)
        {
            if (e.leftMouseButton)
            {
                // We don't want to handle this here, because a simple mouse click on a shape,
                // could be interpreted as a "start pan" action.
                return;
            }

            CustomHideInfoBox(_currentShape);
        }

        //////////////////////////////////////////////////
        function OnStartZoom(e)
        {
            CustomHideInfoBox(_currentShape);
        }

        //////////////////////////////////////////////////
        function DisableEroHide()
        {
            _hide = window.ero.hide;
            window.ero.hide = function(a) 
            {
                return; 
            }        
        }
        
        //////////////////////////////////////////////////
        function EnableEroHide()
        {
            window.ero.hide = _hide;
        }

        //////////////////////////////////////////////////
        function CustomShowInfoBox(shape)
        {
            if (!shape)
                return;
                
            DisableEroHide();
            map.ShowInfoBox(shape);
            _currentShape = shape;
        }

        //////////////////////////////////////////////////
        function CustomHideInfoBox(shape)
        {
            if (!shape)
                return;
                
            // Before actually calling the hide method, we need to restore the ero hide function,
            // otherwise it doesn't hide
            EnableEroHide();
            map.HideInfoBox(shape);
            _currentShape = null;
        }


function getInfoBoxContent(myPin)
{  
    var desc = myPin.GetDescription()
    //if the box already has a description, we do nothing here, the info box will be shown again with its previous content
    if (desc == "")
    {
        var id = myPin.linkID
        var mapID = myPin.mapID
        var divID = "VPOP" + id;    
        myPin.SetDescription("<div class='myPopUpDiv' id='" + divID + "' lang='"+myPin.GetID()+"'><div class='loadingDiv'><img class='loadingImg' src='icons/progress_loading.gif'/>Loading...</div></div>")
        if (id.slice(0,2) == "PR") {getPinContent(id);} else {getUsrPinContent(id, mapID);}  //id is either a CGmapID or a userID
    }
}

function getShapeByLinkID(id)
{
    //get all shapes
    var baseLayer = map.GetShapeLayerByIndex(0)   //the default layer where pins are added
    var count = baseLayer.GetShapeCount()
    
    for (i=0; i<count; i++)
    {
        if (baseLayer.GetShapeByIndex(i).linkID == id) {return baseLayer.GetShapeByIndex(i); break}
    }
    return false;
}



function currentView()
{
    $("userLoc").value = "current map view";
    $('userLoc').className = "inputText"
    $('userLoc').blur() //important to remove the cursor from userLoc after the event gets triggered, otherwise user can type but userLocTyped is not set
    $("userLocTyped").checked = false;    //resetting check box indicating if user typed
    toggleLocalRequestsRadio();
}

function doNothing()
{
}

function showWelcome()
{
    $("welcomePane").style.display = "block";
}

function closeSlideshow()
{
     ss.pause();
     $("slideshow").style.display="none";
     $("selectedPic").value = "";

}

function findButton()
{
      //switch active button
      deactivateNavButtons()
      $("findNavBut").className = "activelink";
      
      $("postPane").style.display="none";
      $("myMapPane").style.display = "none";
      $("findPane").style.display="block";
      //$("userLoc").focus(); 
      //$('tabberDivFind').tabber.tabShow(0);  //reset to 1st tab (ie Most prayed)
      
      //find($('tabberDivFind').tabber.index)
     
}

function postButton()
{
      
      if (myUser.logged)
      {    
          if (App.playdateDirty)  //case where user is switching from Post button to Playdate button without first properly exiting post dialog
          {
            msgBox("Please confirm", "You made some changes, are you sure you want to exit?<br/><br/><div class='divBut'><a id='confirmPostExitYes' class='but' href='javascript:clearPostPane();postButton();closeMsgBox();'>Yes</a><a id='confirmPostExitReturn' class='but' href='javascript:closeMsgBox();'>No</a></div>", 300)
            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#confirmPostExitYes", "transparent")   //round the yes and cancel buttons since they're added at run time
                Nifty("a#confirmPostExitReturn", "transparent")
            }
            return
          }            

          if (App.post == false)
          {
            //loadpostPanel();   
            App.post = true;              
            fillPostCat()    //inside this if so it only gets done the first time user clicks 'Create pinpost'
            //showPostCat()
          }

          if ($("postCG60").checked == true)  //enable if it's not already enabled
          { 
            clearPostPane()
            disablePlaydateWiz()
          }
          
          $("postPane").style.display="block";
          $("findPane").style.display="none";
          $("myMapPane").style.display = "none";
          if ($("postWiz2").style.display == "block") { $("postTitle").focus()}  //only give the focus if the element is visible otherwise IE generates an error
          
          //switch active button
          deactivateNavButtons()
          $("postNavBut").className = "activelink";
      }
      else {showLoginJoin()}
}

function playdateButton()
{
      
      if (myUser.logged)
      {   
          if (App.postDirty)  //case where user is switching from Post button to Playdate button without first properly exiting post dialog
          {
            msgBox("Please confirm", "You made some changes, are you sure you want to exit?<br/><br/><div class='divBut'><a id='confirmPostExitYes' class='but' href='javascript:clearPostPane();playdateButton();closeMsgBox();'>Yes</a><a id='confirmPostExitReturn' class='but' href='javascript:closeMsgBox();'>No</a></div>", 300)
            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#confirmPostExitYes", "transparent")   //round the yes and cancel buttons since they're added at run time
                Nifty("a#confirmPostExitReturn", "transparent")
            }
            return
          }            
          if (App.post == false) 
          {
              //loadpostPanel();   
              App.post = true;             
              fillPostCat()
          }
          if (App.playdate == false)
          {
              App.playdate = true;              
              fillPostPDCat()
          }            
          
          if ($("postCG60").checked == false)  //enable if it's not already enabled
          { 
            clearPostPane()
            enablePlaydateWiz()  
          }
          $("postPane").style.display="block";
          $("postAddrInput").focus();
          $("findPane").style.display="none";
          $("myMapPane").style.display = "none";

                //switch active button
          deactivateNavButtons()
          $("playdateNavBut").className = "activelink";
      }
      else {showLoginJoin()}
}

function myMapButton()
{  
      if (myUser.logged)
      {
          $("findPane").style.display="none";
          $("postPane").style.display="none";
                   
          if (myUser.memberID != null)
          {
            //download myMap code
            App.myMap = true;      
                  
            clearMyMapPane()
            fillMyMapPane(myUser.memberID);
            enableMyMap()  //in case user viewed someone else's profile before           
          }
          
          $("myMapPane").style.display = "block";   
          //switch active button
          deactivateNavButtons()
          $("myMapNavBut").className = "activelink";
      }
      else {showLoginJoin()}

}

function viewProfile(memberID, display)
{
    display = unescape(display)
    $("findPane").style.display="none";
    $("postPane").style.display="none";
     
    clearMyMapPane()
    fillMyMapPane(memberID)  
    if (myUser.memberID != memberID)
    {
        disableMyMap(display)
    }
    else
    {
        enableMyMap()
    }
    
    $("myMapPane").style.display = "block";   
}
  
  
function setDirtyFlag()
{
      if ($("postCG60").checked == true)  //playdate edit case
      { 
        App.playdateDirty = true;
      }
      else   //post edit case
      {
        App.postDirty = true;      
      }
}  
  
    
function showBox(title, w, h, url, profile)
{
    if (myUser.logged)
    {
      if (profile){$("photoType").value = "profile"}   //set the photo type field to profile so we know what type of photos to refresh in mymap pane
      
      $("divPhotoBoxTitle").innerHTML = title ;
      $("divPhotoBoxContent").innerHTML = "<iframe frameBorder='0' height="+h+" src='"+url+"'></iframe>";
      $("divPhotoBox").style.display = "block"; 
      Nifty("div#divPhotoBoxContent", "transparent") 
    }
    else {showLoginJoin()}   
}    

function msgBox(title, str, w, h)
{
      //w = 300  //default width and height
      //h = 300 
      title = unescape(title)   
      str = unescape(str)
      $("divBox").style.width = w +"px";
      //$("divBoxContent").style.height = h +"px";         //don't need to specify the height since the content will determine it  
      $("divBoxTitle").innerHTML = title ;
      $("divBoxContent").innerHTML = "<br/>"+ str + "<br/><br/>";
      $("divBox").style.display = "block";  
      Nifty("div#divBoxContent","transparent");    //need to call this again to round the inside corners :(   

}

function msgBox1(title, str, w, h)   //same as above except it doesn't escape title and string, used in case where we need to display links inside the msgbox (ie send to friends)
{
      //w = 300  //default width and height
      //h = 300 
      //title = unescape(title)   
      //str = unescape(str)
      $("divBox").style.width = w +"px";
      //$("divBoxContent").style.height = h +"px";         //don't need to specify the height since the content will determine it  
      $("divBoxTitle").innerHTML = title ;
      $("divBoxContent").innerHTML = "<br/>"+ str + "<br/><br/>";
      $("divBox").style.display = "block";  
      Nifty("div#divBoxContent","transparent");    //need to call this again to round the inside corners :(   
}

function closeMsgBox()
{
      $("divBox").style.display = "none";   
}

function closePhotoBox()
{
      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
      {
          //need to determine what type of photo was added. If "profile" we refresh the user profile photos, if not we refresh the user photo count and user photos.
          if ($("photoType").value == "profile")
          {
            PageMethods.getProfilePhotos(myUser.memberID, onProfilePhotoResult, onProfilePhotoError);     
          }
          else
          {
            //get new photoCount and update user photoCount property    
            PageMethods.getPhotoCount(myUser.memberID, onPhotoCountResult, onPhotoCountError);   
          }
          //need to update the thumbnail value if a photo is added to a post that had no photo(ie thumbnail before)
          if ($('tabberDivFind').tabber.index == 0)  //the first tab is 'prayer posts;
          {
            getPosts(myUser.memberID)  //if 'MyFaithmap' button is active we are sure that the user is looking at his own profile
          }                
      } 
     $("photoType").value = ""   //reset photo type field
     $("divPhotoBox").style.display = "none";     
}   
        
        function onPhotoCountResult(result)
        {
            myUser.photoCount = result;
            //refresh photo tab by calling getMyMapPhotos()  
            try{$("tabberDiv").getElementsByTagName("ul")[0].getElementsByTagName("a")[2].firstChild.nodeValue = "Photos"// ("+myUser.photoCount+")"
            }catch(err){}  //updating photo tab title in case photos were added
            getMyMapPhotos(myUser.memberID)          // I should replace this with a client update of the myMap page (however the current implementation of a separate photoUpload.aspx page doesn't allow this)
              
        } 
        function onPhotoCountError(){
        }
        function onProfilePhotoResult(resultSet)
        {
            fillPhotoInfo(resultSet)  //function located in mymap.js
        } 
        function onProfilePhotoError(){
        }        
        

function joinButton()
{
    if (myUser.logged){msgBox("Oops!", "You have already joined!",300);return}
    $("joinPane").style.display = "block";  
    $("loginPane").style.display = "none";
    $("joinEmail").focus(); 
     
}

function loginButton()
{
    $("loginPane").style.display = "block";
    $("notRegistered").style.display = "none"; 
    $("loginPane").style.width = "235px";   
    $("loginEmail").focus(); 
}


function showLoginJoin()
{
    $("loginPane").style.display = "block";
    $("notRegistered").style.display = "block";  
    $("loginPane").style.width = "450px";   
    $("loginEmail").focus(); 
    Nifty("div#notRegistered","transparent");
}


function refreshGreeting()
{
    $("greeting").innerHTML = "welcome <b>"+myUser.display+"</b>,";
}

function roundCorners()
{
    Nifty("ul#nav a","transparent");
    Nifty("ul#nav1 a","transparent");
    Nifty("div.paneBody","transparent");       
    Nifty("div.leftPane","transparent");
    Nifty("div.centerPane","transparent");
    Nifty("div.rightPane","transparent");
    Nifty("div#slideshowBody","bottom transparent");
    Nifty("div#rightPaneContent","top transparent");
    Nifty("div#findSearchArea", "transparent");
    if (document.all)  {Nifty("a.but","transparent");}  // 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.but","transparent");
    //centerDiv($("findDiv"));
    
      //below is to reset the hide display since Nifty corners changes it
      $("postWiz0").style.display = "none";
      $("postWiz1").style.display = "none";
      $("postWiz2").style.display = "block";
      $("postWiz3").style.display = "none";
      $("postWiz4").style.display = "none";
      $("postWizPD").style.display = "none";
      $("postWiz3NextPDBut").style.display = "none";
      
}


/*
function centerDiv(Element)
{
 var refElement = Element.parentElement.parentElement 
 var spanElement = Element.firstChild
 var aElement = spanElement.firstChild
 //objh = parseFloat(Element.offsetHeight)/2;
 var objw = parseFloat(spanElement.offsetWidth)/2;
 //Element.style.top = Math.floor(Math.round((refElement.offsetHeight/2)+refElement.scrollTop)-objh)+'px';
 var lefty = Math.floor(Math.round((refElement.offsetWidth/2)+refElement.scrollLeft)-objw)+'px'
 //aElement.style.marginLeft = lefty
 Element.style.left = lefty
 //Element.style.paddingLeft = lefty
 //Element.offsetLeft = lefty
}
 */

function checkCookie()
{
    var displayName = getCookie("display");
    var memberID = getCookie("memberID");
    var emailAddress = getCookie("email");
    var userName = getCookie("usrname");
    var userLat = getCookie("lat");
    var userLon = getCookie("lon");
    var userPic = getCookie("primaryPic");
    
    if ((displayName!=null && displayName!="")&&(memberID!=null && memberID!=""))
      {
        myUser.logged = true;
        myUser.newuser = false;
        myUser.memberID = memberID
        myUser.display = displayName;
        myUser.email = emailAddress;
        myUser.name = userName;
        myUser.lat = +userLat;
        myUser.lon = +userLon;
        myUser.primaryPic = userPic
        refreshGreeting()
        $("divLogOut").style.display = "block"
      }
    else 
      {
        $("greeting").innerHTML = "<a href='javascript:loginButton();'>sign in</a>&nbsp&nbsp|&nbsp&nbsp<a href='javascript:joinButton();'>join</a>"
        showWelcome();
      }
}  


function deactivateNavButtons()
{
      arr = $("nav").getElementsByTagName("li")
      for (i=0;i<arr.length;i++)
      {
           arr[i].className = "" 
      }
}


function clearPanes()
{
    clearFindPane()
    if (App.post)
    {
        clearPostPane()
    }
    if (App.myMap)
    {
        clearMyMapPane()
    }
    clearReview()
    clearProfilePane()
    $("slideshow").style.display="none"; //hide slideshow
    $("managePhotoPane").style.display = "none";
    clearForgotPassword();
    clearSendToFriend();
    $("divPhotoBox").style.display = "none";  //hide add photo box
    clearFeedback();
    $("touPane").style.display = "none";
    $("privacyPane").style.display = "none";
    CustomHideInfoBox(_currentShape)
    clearMbrPane()
}

function dayName(number)
{
    switch(number)
    {
        case "1":
            return "mon";           
        case "2":
            return "tue";
        case "3":
            return "wed";
        case "4":
            return "thu";
        case "5":
            return "fri";
        case "6":
            return "sat";
        case "7":
            return "sun";
        default:
            return("day number not recognized"); // default code
     }
}


function detectBrowser()
{
    if (document.getElementById){}
    else{alert("This web site utilizes functionality only supported by modern browsers. It does not appear that your browser supports Javascript. Please upgrade your browser to use this web site.");return}

    if (document.getElementById && !document.all)
    {alert("this web site currently does not support the Firefox or NS6+ browsers. Only the IE browser is supported at this point.");return}

}

function clearWelcomePane()
{
    $("welcomePane").style.display = "none";
}

function convertToCG(CGid)
{
    var CG;  //Category Group
    switch(CGid)
    {
        case 10:
            CG = "EV"     //Events category group
            break
        case 20:
            CG = "PR"     //Prayer Requests   //Playgrounds
            break
        case 100:
            CG = "PR"     ///case where all requests are selected
            break
        case 30:
            CG = "SC"     //Schools
            break
        case 40:
            CG = "CL"     //Classes
            break
        case 50:
            CG = "DC"     ///Daycares
            break
        case 60:
            CG = "PD"     ///Daycares
            break
        default:
            msgBox("Oops!", "Category group not recognized", 300);
            //alert("Category group not recognized") // default code
     }
     return CG;
}

function convertToCGid(CG)
{
    var CGid;
    switch(CG)              //converting CG into catgroup id (ex PG into 20)
    {
        case "EV": 
            CGid = 10  
            break
        case "PR":
            CGid = 20         
            break    
        case "SC": 
            CGid = 30  
            break   
        case "CL": 
            CGid = 40  
            break  
        case "DC": 
            CGid = 50  
            break    
        case "PD": 
            CGid = 60  
            break                     
        default:
    }          
    return CGid
}


function showFeedback()
{
  if (myUser.logged)
  {
    $("feedbackPane").style.display = "block";
    $("feedbackText").focus();
  }
  else {showLoginJoin()}
}

function clearFeedback()
{
    $("feedbackText").value = "";
    $("feedbackPane").style.display = "none"; 
}

function sendFeedback()
{
    if (isEmpty($("feedbackText"))) 
    {
        msgBox("Oops!", "Feedback is empty, please type in your feedback.", 300);
        return;
    }
    disableBut("feedbackBut")
    PageMethods.sendUserFeedback(myUser.memberID, $("feedbackText").value.trims(), onUserFeedbackResult, onUserFeedbackError);        
}

    function onUserFeedbackResult()
    {
        enableBut("feedbackBut");
        clearFeedback();        
        msgBox("Thank you!", "Your feedback has been received. <br/>Thank you", 300);
    }

    function onUserFeedbackError()
    {
        msgBox("Oops!", "Could not send feedback, please try again.", 300);
    }


function showTOU()
{
    PageMethods.getFileAsString("tou", onTOUresult, onTOUerror);        
}

    function onTOUresult(result)
    {
        $("touContent").innerHTML = result;
        $("privacyPane").style.display = "none";
        $("touPane").style.display = "block";
    }
    function onTOUerror()
    {
            msgBox("Oops!", "Could not get terms of use.", 300);
    }

function showPrivacy()
{
    PageMethods.getFileAsString("privacy", onPrivacyResult, onPrivacyError);        

}
    function onPrivacyResult(result)
    {
        $("privacyContent").innerHTML = result;
        $("touPane").style.display = "none";
        $("privacyPane").style.display = "block";
    }
    function onPrivacyError()
    {
            msgBox("Oops!", "Could not get privacy policy.", 300);
    }

function clearTOU()
{
    $("touPane").style.display = "none";
}

function clearPrivacy()
{
    $("privacyPane").style.display = "none";
}

function disableBut(id, text)
{
    //creating the temp node
    var myText;
    tempDiv = document.createElement("div")
    tempDiv.id = id + "temp"
    tempDiv.className = "tempButton"
    if (text) {myText = text} else {myText = "Submitting..."}
    tempText = document.createTextNode(myText)
    tempDiv.appendChild(tempText);
     
    //attaching the temp node
    $(id).parentNode.appendChild(tempDiv) 
    
    //hiding the button
    $(id).style.display = "none";
            
}

function enableBut(id)
{
    //removing the temp node
    $(id+"temp").parentNode.removeChild($(id+"temp")) 
    
    //displaying the button
    $(id).style.display = "block";

}


function decHtmUpdate(myStr)    //gets !xyz1tk!DATE!zyx1tk! and returns <div class='update'>update (DATE)</div>
{   
    var text = myStr.replace(/!xyz1tk!/g,"<div class='update'>update <span>(");
    text = text.replace(/!zyx1tk!/g,")<span></div>");
    return text 
}

function decTxtUpdate(myStr)    //gets !xyz1tk!DATE!zyx1tk! and returns --- UPDATE (DATE) ---
{   
    var text = myStr.replace(/!xyz1tk!/g,"\r\r--- UPDATE (");
    text = text.replace(/!zyx1tk!/g,") ---\r");
    return text 
}

function encTxtUpdate(myStr)    //gets !xyz1tk!DATE!zyx1tk! and returns --- UPDATE (DATE) ---
{   
    var text = myStr.replace(/<br><br>--- UPDATE \((...........|............)\) ---<br>/g,"!xyz1tk!$1!zyx1tk!")  //11 or 12 dots is the date string "Jan 12, 2008"
    
    //var text = myStr.replace(/<br><br>--- UPDATE \(/g,"!xyz1tk!");
   // text = text.replace(/\) ---<br>/g,"!zyx1tk!");
    return text 
}



// Objects and their methods

// *************** beginning of App object definition and methods **************************
// ******************************************************************************************

function AppObj(post, playdate, myMap, postDirty, playdateDirty)
{
    this.post = post   //bool    tells whether the Post code has been dowloaded
    this.playdate = playdate     //bool   tells whether the Playdate code has been dowloaded
    this.myMap = myMap    //bool   tells whether the MyMap code has been dowloaded
    this.postDirty = postDirty  //bool  tells whether 
    this.playdateDirty = playdateDirty  //bool
}


// this defines the post object
function postObj(catGroup, mapID, cat, lat, lon, ages, ageStr, dates, dateStr, dateMin, dateMax, days, title, description, update, status, notifyMe, createdBy, createdOn, ratingTotal, web, phone, cost, time, friendsID, friendsEmail, newFriends)
{
    this.catGroup = catGroup
    this.mapID = mapID
    this.cat = cat          //array of categories
    this.lat = lat
    this.lon = lon 
    this.ages = ages          //array of age brackets (int)
    this.ageStr = ageStr      //age string specified by user
    this.dates = dates      //array of dates
    this.dateMin = dateMin
    this.dateMax = dateMax
    this.days = days              //concatenated strings of recurring events days during the week (ex: "2,4,6", ie Tue, Thu, Sat)
    this.title = title
    this.description = description 
    this.update = update
    this.status = status
    this.notifyMe = notifyMe
    this.createdBy = createdBy
    this.createdOn = createdOn
    this.ratingTotal = ratingTotal
    this.web = web
    this.phone = phone
    this.cost = cost
    this.time = time
    this.friendsID = friendsID  //array of member IDs (used for playdate)
    this.friendsEmail = friendsEmail //array of invitee member emails (ex: "john@msn.com")
    this.newFriends = newFriends //array of emails (used for playdate)
    
    //this.build = build
    //this.createPostString = createPostString
} 

function cmtObj(CG, mapID, id, title, description, rating, notify)   // this is used to store the orginal comment when editing it, to compare edited comment to original comment.
{
    this.CG = CG 
    this.mapID = mapID     
    this.id = id
    this.title = title   
    this.description = description     
    this.rating = rating   
    this.notify = notify   
}


// *************** beginning of USER object definition and methods **************************
// ******************************************************************************************

function userObj(newuser, logged, ctryCode, country, state, city, lat, lon, memberID, display, email, password, aboutMe, link, location, faith, church, name, primaryPic, favoriteCount, reviewCount, postCount, photoCount, playdateCount)
{
    this.newuser = newuser  //bool, true if no cookie present
    this.logged = logged     //bool
    
    this.ctryCode = ctryCode
    this.country = country
    this.state = state
    this.city = city
    this.lat = lat
    this.lon = lon
    
    this.memberID = memberID    //set at log-in or at startup if cookie present
    this.display = display
    this.email = email
    this.password = password
    this.aboutMe = aboutMe
    this.link = link
    this.location = location
    this.faith = faith
    this.church = church
    this.name = name
    this.primaryPic = primaryPic
    
    this.favoriteCount = favoriteCount
    this.reviewCount = reviewCount
    this.postCount = postCount
    this.photoCount = photoCount  //tracks map items photos (not personal photos)
    this.playdateCount = playdateCount
    
    this.locate = locate
}

function locate()     //get users's location based on IP address and set map view accordingly
{
    this.ctryCode = geoip_country_code()    // APIs from MAXMIND.com
    this.country = geoip_country_name()
    this.state = geoip_region()
    this.city = geoip_city()
    this.lat = geoip_latitude()
    this.lon = geoip_longitude()
    
    if (this.lat != null )  // BUG: not sure if the geo api actually returns null or nothing if the IP address is hidden
    {
        $("userLoc").value = this.city + ", " + this.state
        map.SetCenterAndZoom(new VELatLong(this.lat, this.lon), 4)  //zoom used to be 11 
        return true
    }    
    else {return false}

}

// *************** end of USER object definition and methods ****************************
