﻿// functions for Join and Login functionality 

function join()
{
    valid = true
    
    //verfiy fields are not empty
    if (isEmpty($("joinEmail"))) 
    {
        msgBox("Oops!", "The email address field is empty. Please enter your email address.", 300)
        //$("joinEmail").focus();    doesn't quite work because the focus gets lost once user closes msgBox
        valid = false
        return
        ;
    } 
    if (isEmpty($("joinPassword"))) 
    {
        msgBox("Oops!", "The Password field is empty. Please enter a password.", 300)
        //$("joinPassword").focus();  
        valid = false
        return
    }  
    if (isEmpty($("joinPasswordRepeat"))) 
    {
        msgBox("Oops!", "The Password field is empty. Please enter a password.", 300)
        //$("joinPasswordRepeat").focus();  
        valid = false
        return
    }  
    if (isEmpty($("joinDisplayName"))) 
    {
        msgBox("Oops!", "The display name field is empty. <br/><br/>Please enter a display name, this name will show with prayer request or response you create with Faithmap. You can always change it later if you decide to.", 300, 200)
        //$("joinDisplayName").focus();  
        valid = false
        return
    }
  
    //validate email field    
    if (!emailValid($("joinEmail").value))
    {
        msgBox("Oops!", "The email address entered is not valid, please try again.", 300)
        //$("joinEmail").focus();  
        valid = false
        return
    }  
    
        //validate password field    
    if ($("joinPassword").value.trims() == "")
    {
        msgBox("Oops!", "The password entered is empty, please try again.", 300)
        //$("joinEmail").focus();  
        valid = false
        return
    }  
    
    //verify passwords match
    if ($("joinPassword").value != $("joinPasswordRepeat").value)
    {
        msgBox("Oops!", "The two passwords entered do not match, please try again.", 300)
        //$("joinPassword").focus();   
        valid = false  
        return  
    }
    
    //verify TOU box is checked
    if (!$("joinTOUcb").checked)
    {
        msgBox("Oops!", "You have not checked the 'terms of use' box.", 300)
        valid = false  
        return  
    }
             
    if (valid)
    {
        getUserLocation()
    }
    
}

function getUserLocation()
{
    $("joinPaneContent").style.display = "none";
    $("joinGreeting").innerHTML = "Hello " + $("joinDisplayName").value.trims() + ","
    $("joinPaneContent2").style.display = "block";
  


}


function findUser()   //same as the find() in find.js and findLocPin() in post.js
{
      //check that address field is not empty   
    if (isEmpty($("newUserLoc"))) 
    {
        msgBox("Oops!", "The zip code field is empty. Please enter a zip code.", 300)
        return
    } 
    
    //map.Clear();
    map.ShowDisambiguationDialog(false);
    //map.FindLocation($('userLoc').value, onFoundResults);
    disableBut("joinBut", "Locating...")
    map.Find(null,$('newUserLoc').value,null,null,null,null,null,null,false,false,onFoundUserResults);

}

    function onFoundUserResults(ShapeLayer,FindResult,Place,HasMore)     //in VE4: onFoundResults(e)
    {
        //enableBut("joinBut")
        //disableBut("joinBut")
        //PageMethods.createPendingMember($("joinEmail").value.trims(), $("joinPassword").value.trims(), $("joinDisplayName").value.trims(), Place[0].LatLong.Latitude, Place[0].LatLong.Longitude, Place[0].Name, onCreatePendingResult, onCreatePendingError)
        PageMethods.registerNewMember($("joinEmail").value.trims(), $("joinPassword").value.trims(), $("joinDisplayName").value.trims(), Place[0].LatLong.Latitude, Place[0].LatLong.Longitude, Place[0].Name, onNewMemberResult, onCreatePendingError)


        /*
        
        //filter the redundant results from VE countaining "county" and "river"
        for (i=0; i<Place.length; i++)
        {
            if ((Place[i].Name.match("(county)") != null) || (Place[i].Name.match("(river)") != null))   //in VE4: e[i].ID.match("...
            {
                Place.splice(i, 1)  //remove that element from the array  
                i=i-1            //resetting for loop because when the array is sliced, if the next item also was a match it would be skipped over 
            }
        }
        
        if (Place.length > 1)
        {
            var results="More than one location exist for your entry. Please select your location area:<ul>";
            for (i=0; i<Place.length; i++)
            {
                results+="<li><a href='javascript:closeMsgBox();map.Find(null,\""+Place[i].Name+"\",null,null,null,null,null,null,false,null,onFoundUserResults);'>"+Place[i].Name+"</a><br></li>";                
                //results+="<li><a href='javascript:closeMsgBox();map.FindLocation(\""+e[i].ID+"\", onFoundResults);'>"+e[i].ID+"</a><br></li>";  //VE4
            }
            results+="</ul>";
            msgBox("Faith Map", results, 300);
         }
         else
         {  
            enableBut("joinBut")
            if (Place.length == 1)
            {   
                //alert(Place[0].LatLong.Latitude + " , "+Place[0].LatLong.Longitude+ " , "+ Place[0].Name)
                disableBut("joinBut")
                PageMethods.createPendingMember($("joinEmail").value.trims(), $("joinPassword").value.trims(), $("joinDisplayName").value.trims(), Place[0].LatLong.Latitude, Place[0].LatLong.Longitude, Place[0].Name, onCreatePendingResult, onCreatePendingError)
            }
            else {msgBox("Oops!", "The zip code can not be mapped, please try a different zip code or alternatively enter your 'city, state'.", 300);}
         }
         */
    }

    function onNewMemberResult(result)   //result is nRows, ie 1 if a row was inserted and -1 if the user already exists in our database
    {
        //if alreadymember...
        //if pending...
        
        if (result != -1)
        {
            clearJoin();    
            msgBox("Welcome!", "Thank you for registering. Please sign in to have access to all site features.", 300)
            loginButton()    
        }
        else
        {
            clearJoin();    
            msgBox("Oops!", "You have already registered! <br/><br/>Please try signing in with your email address. <br/>If you don't remember your password, click on 'forgot password' in the Sign-in window.", 300, 200)
        }
        enableBut("joinBut")
    }

    function onCreatePendingResult(result)   //result is nRows, ie 1 if a row was inserted and -1 if the user already exists in our database
    {
        //if alreadymember...
        //if pending...
        
        if (result != -1)
        {
            clearJoin();    
            msgBox("Welcome to Faithmap", "To verify your identity, we just sent you an email. <br/><br/>Please look for the Welcome message from Faithmap and click on the link inside to complete your registration.", 400) 
        }
        else
        {
            clearJoin();    
            msgBox("Oops!", "You have already registered! <br/><br/>Please try logging in with your email address. <br/>If you don't remember your password, click on 'forgot password' in the Sign-in screen.", 300, 200)
        }
        enableBut("joinBut")
    }
    
    function onCreatePendingError()
    {
        enableBut("joinBut")
        clearJoin();
        msgBox("Oops!", "Could not perform registration. Please try again.", 300)      
    }
    

function clearJoin()
{
    $("joinEmail").value = "";
    $("joinPassword").value = "";
    $("joinPasswordRepeat").value = "";    
    $("joinDisplayName").value = "";   
    $("joinPane").style.display = "none";
    $("joinTOUcb").checked = "false";    //does not work for some reason
    $("newUserLoc").value = "";
    $("joinPaneContent2").style.display = "none"; 
    $("joinPaneContent").style.display = "block";
}

function login()
{
    //validate email/password
    disableBut("signinBut", "Signing in...")
    PageMethods.logUser($("loginEmail").value.trims(), $("loginPassword").value.trims(), onLogUserResult, onLogUserError);
}

    function onLogUserResult(resultTable)
    {
        switch (resultTable.rows[0].status)
        {
            case "wrongEmail":  //not used for now
                //clearLogin();
                msgBox("Oops", "The email entered was not recognized, please try again.", 300)
                break;
            case "wrongPassword":  //not used for now
                //clearLogin();
                msgBox("Oops", "The password entered is not correct, please try again.", 300)
                break; 
            case "noMember":
                //clearLogin();
                msgBox("Oops", "The email or password entered was not recognized, please try again.", 300)
                break;
            case "pendgMember":
                clearLogin();
                msgBox("Oops", "To complete your registration, please check your email for the Welcome message from Faithmap and click on the link inside. <br/><br/>If you do not see our Welcome email in your Inbox folder, you may also check your Junk or Spam folder.", 300)
                break;
            case "foundMember":
                clearLogin();
                myUser.logged =  true;
                myUser.memberID = resultTable.rows[0].memberID;
                myUser.display = resultTable.rows[0].display;
                myUser.aboutMe = resultTable.rows[0].aboutMe;
                myUser.link = resultTable.rows[0].link;
                myUser.email = resultTable.rows[0].email;
                myUser.password = resultTable.rows[0].password;
                myUser.lat = resultTable.rows[0].lat;
                myUser.lon = resultTable.rows[0].lon;
                myUser.location = resultTable.rows[0].location;
                myUser.faith = resultTable.rows[0].faith;
                myUser.church = resultTable.rows[0].church;
                myUser.name = resultTable.rows[0].name;
                myUser.primaryPic = resultTable.rows[0].primaryPic;
                refreshGreeting();
                $("divLogOut").style.display = "block";
                $("welcomePane").style.display = "none";
                showPane()
                //findButton()  //show Search pane
                setCookie("display",myUser.display,900)
                setCookie("memberID",myUser.memberID,900)
                setCookie("email",myUser.email,900)
                setCookie("usrname",myUser.name,900)
                setCookie("lat",myUser.lat+"",900)
                setCookie("lon",myUser.lon+"",900)
                setCookie("primaryPic",myUser.primaryPic,900)
                //re-postion the map base on user lat and lon instead of IP address lat and lon
                //$("userLoc").value = "current view"
                /*          
                if (!showPinpost) //we shouldn't change the map items if the user got a prayer invite
                {
                    //map.SetCenterAndZoom(new VELatLong(myUser.lat, myUser.lon), 4)  //zoom used to be at 10    
                    var mapCenter = new VELatLong(38,-108);
                    map.SetCenterAndZoom(mapCenter, 4)  //zoom used to be at 10                   
                    dbFind(0)  
                }*/
                break;
            default:
         }
         enableBut("signinBut")           
    }
    
    function onLogUserError()
    {
        clearLogin();
        msgBox("Oops", "Could not perform login. Please try again.", 300, 200)
    }


function showPane()
{
    arr = $("nav").getElementsByTagName("li")
    for (i=0;i<arr.length;i++)
    {  
        if (arr[i].className == "activelink")
        {    
            arr[i].getElementsByTagName("a")[0].onclick()         //triggers the onclick event for the active button
        }
    }
}


function clearLogin()
{
    $("loginEmail").value = "";
    $("loginPassword").value = "";
    $("loginPane").style.display = "none"
}


function emailValid(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   return false
		}
		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false
		}
		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false
		}
		 if (str.indexOf(at,(lat+1))!=-1){
		    return false
		 }
		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false
		 }
		 if (str.indexOf(dot,(lat+2))==-1){
		    return false
		 }		
		 if (str.indexOf(" ")!=-1){
		    return false
		 }
 		 return true					
	}


function logOut(noPrompt)
{
    myUser.logged = false;
    myUser.memberID = null;
    myUser.display = "";
    myUser.email = ""
    myUser.password = "";
    myUser.aboutMe = "";
    myUser.link = "";
    myUser.name = "";
    myUser.lat = 0
    myUser.lon = 0
    myUser.primaryPic = "";
    $("greeting").innerHTML = "<a href='javascript:loginButton();'>sign in</a>&nbsp&nbsp|&nbsp&nbsp<a href='javascript:joinButton();'>join</a>"
    $("divLogOut").style.display = "none";
    clearPanes()
    map.Clear()
    deleteCookie("display");   //deleteCookie( name, path, domain )
    deleteCookie("memberID");
    deleteCookie("email");
    deleteCookie("usrname");
    deleteCookie("lat");
    deleteCookie("lon");
    deleteCookie("primaryPic");
    if (noPrompt){}  //don't prompt the msgBox if parameter is passed
    else{msgBox("Thank you", "You are now signed out.", 300)}

}

function forgotPassword()
{ 
    clearLogin()
    $("loginPane").style.display = "none"
    $("forgotPasswordPane").style.display = "block"
    $("FPemail").focus();

}

function clearForgotPassword()
{
    $("FPemail").value = "";
    $("forgotPasswordPane").style.display = "none"
}

function sendPassword()
{
    if (emailValid($("FPemail").value))
    {
        disableBut("forgotPasswordBut")
        PageMethods.sendUserPassword($("FPemail").value.trims(), onUserPasswordResult, onUserPasswordError)
    }
    else
    {
        msgBox("Oops!", "The email address entered is not valid, please try again.", 300)
    }
}

    function onUserPasswordResult(result)
    {
        if (result)   //returns true if password was sent, false if email address was not found
        {
              clearForgotPassword()
              msgBox("Thank you", "Your password has been sent to your email address.", 300)      
        }
        else  
        {
             msgBox("Oops!", "The email address entered was not recognized. Please correct it or try a different email address.", 300)       
        }
        enableBut("forgotPasswordBut");
    
    }
    function onUserPasswordError(result)
    {
            msgBox("Oops!", "Could not send password.", 300)
    }