var status_msg = "";
var full_name = "";
var gl_status = "";


///Change from status check to session check because errors are thrown with FB.Facebook.apiClient.get_session().uid
var fbStatus;
var email_hash;
var facebook_uid;

/*
 * The facebook_onload statement is printed out in the PHP. If the user's logged in
 * status has changed since the last page load, then refresh the page to pick up
 * the change.
 *
 * This helps enforce the concept of "single sign on", so that if a user is signed into
 * Facebook when they visit your site, they will be automatically logged in -
 * without any need to click the login button.
 *
 * @param already_logged_into_facebook  reports whether the server thinks the user
 *                                      is logged in, based on their cookies
 *
 */
 //var is_Local_Facebook_Session_Running = isLoggedIn;
function facebook_login(){
     FB.login(function() { facebook_onlogin(); CheckIfRegisteredUserTimer()}, {scope:'publish_stream,email', enable_profile_selector: 1});
}

function CheckIfRegisteredUserTimer()
{
    window.setTimeout(CheckIfRegisteredUser, 2000);
    
}

function show(){
    FB.login(function(response) {
          if (response.authResponse) {
            if (response.perms) {
             
            } else {
              
            }
          } else {
            // user is not logged in
          }
        }, {scope:'publish_stream,email,status_update'});
                                
//FB.Connect.showPermissionDialog("publish_stream,email,status_update", function(perms){
  //  })
}
////function showperm(permission){
////    FB.login(function(response) {
////          if (response.authResponse) {
////            if (response.perms) {
////             
////            } else {
////              
////            }
////          } else {
////            // user is not logged in
////          }
////        }, {scope:permission});
////                                
//////FB.Connect.showPermissionDialog("publish_stream,email,status_update", function(perms){
////  //  })
////}

////function showMulitple(){
////               
////    showperm("publish_stream");
////    showperm("email");
////    showperm("status_update");
////           
//////  FB.Facebook.apiClient.users_hasAppPermission("publish_stream", function(result){
//////    if(result == false){
//////        FB.Connect.showPermissionDialog("publish_stream", function(perms){
//////          
//////         })  
//////    
//////    }
//////  
//////  })
//////                                             
////// FB.Facebook.apiClient.users_hasAppPermission("email", function(result){
//////    if(result == false)
//////    {
//////     FB.Connect.showPermissionDialog("email", function(perms){
//////       }) 
//////    }
////// })
//////    
//////                               
//////   FB.Facebook.apiClient.users_hasAppPermission("status_update", function(result){
//////        if(result == false)
//////        {
//////         FB.Connect.showPermissionDialog("status_update", function(perms){
//////           })
//////        }
//////   })   
////    
////}

function facebook_onlogin() {
      window.setTimeout(init, 500);
      
}



/*
 * Our <fb:login-button> specifies this function in its onlogin attribute,
 * which is triggered after the user authenticates the app in the Connect
 * dialog and the Facebook session has been set in the cookies.
 */


/*
 * Reactivates local session
 */
////function refresh_page(uid, session_key, url) {
////  window.location = '/facebook/ReactivateSession.aspx?uid=' + uid + '&session_key=' + session_key + '&url=' + url;
////}


/*
 * Show the feed form. This would be typically called in response to the
 * onclick handler of a "Publish" button, or in the onload event after
 * the user submits a form with info that should be published.
 *
 */
////var gl_template_data
////function facebook_publish_feed_story(articleImage, pageTitle, metaDescription, href) {
////    view = "<a href=" + href+ "> View this property </a>"
////    if(articleImage != ""){
////             var template_data = {
////                "pageTitle":pageTitle,
////                "metaDescription":metaDescription,
////                "images":[{"src":articleImage,
////                                             "href":href}],
////                "view":view                             
////             }
////        }
////    else
////    {
////      var template_data = {
////                "pageTitle":pageTitle,
////                "metaDescription":metaDescription,
////                "view":view                             
////             }
////    }    
////    
////    //set global variable for permissions
////    gl_template_data = template_data
////    
////    FB.ui(
////                   {
////                     method: 'stream.publish',
////                     message: '',
////                     attachment: template_data,
////                     action_links: null,
////                     user_message_prompt: true
////                   }, null
////                 );


////  // FB.Connect.showFeedDialog(81722621772, template_data, null, null, FB.FeedStorySize.shortStory, FB.RequireConnect.promptConnect);
////      

////}

/*
 * If a user is not connected, then the checkbox that says "Publish To Facebook"
 * is hidden in the "add run" form.
 *
 * This function detects whether the user is logged into facebook but just
 * not connected, and shows the checkbox if that's true.
 */
////function facebook_show_feed_checkbox() {

////      FB.getLoginStatus(function(response) {
////          if (response.authResponse) {

////            // If the user is currently logged into Facebook, but has not
////            // authorized the app, then go ahead and show them the feed dialog + upsell
////            checkbox = ge('publish_fb_checkbox');
////            if (checkbox) {
////              checkbox.style.visibility = "visible";
////            }
////          }
////        });
////}

//Set facebook status for logged in user
function Facebook_users_setStatus(status){
   //Before doing anything make sure status_message has been supplied by the onload
    if(status_msg != ""){   
      first_word = status.substring(0,status.indexOf(" "))
      rest_of_sentence = status.substring(status.indexOf(" "))
        
        //Test for the first word to see if it is uers's first name, if so do not include
        if(first_word == full_name){
            status = rest_of_sentence;
            gl_status = status; 
        }
        
        //If no name just supply what is in the status box
        else{
            gl_status = status;
        }
    }
   FB.getLoginStatus(function(response) {
       //console.log("getting login status" + response.authResponse);
       if (response.authResponse) {
          var query = FB.Data.query('select status_update from permissions where uid={0}', response.authResponse.userID);
          query.wait(function(rows) {
             if (rows[0].publish_stream) {
             with (this) {
                 FB.ui(
                   {
                     method: 'stream.publish',
                     message: status,
                     attachment: '',
                     action_links: null,
                     user_message_prompt: true
                   }, Facebook_users_setStatus_confirmation
                 );
              }
             
              //  FB.Facebook.apiClient.users_setStatus(status, false, true, Facebook_users_setStatus_confirmation);
             }
             //If not authorize, display authorization dialog 
             else{
             
               facebook_prompt_permission('status_update');
             }
          });
       }
   })
   
//    FB.ensureInit(function() {
//        FB.Facebook.apiClient.users_hasAppPermission('status_update', function(result){
//            //Try 
//            try{
//                //Set if user authorized status update 
//               if(result == true){
//                  FB.Facebook.apiClient.users_setStatus(status, false, true, Facebook_users_setStatus_confirmation);
//                }
//                //If not authorize, display authorization dialog 
//                else{
//                 
//                   facebook_prompt_permission('status_update');
//                }
//            }
//            //Catch
//            catch(error){
//                document.getElementById("errorRed").style.display = "block";
//            }
//            
//        });  
//    });
}

/*
 * Prompts the user to grant a permission to the application.
 */
function facebook_prompt_permission(permission) {
    FB.login(function(response) {
      if (response.authResponse) {
        if (response.perms) {
         Facebook_users_setStatus(gl_status);
        } else {
          
        }
      } else {
        // user is not logged in
      }
    }, {scope:permission});

//  FB.ensureInit(function() {
//    FB.Connect.showPermissionDialog(permission, function(status){
//        permission_granted = status ? true : false; 
//        if(permission_granted == true)
//        {
//            FB.Facebook.apiClient.users_setStatus(gl_status, false, true, Facebook_users_setStatus_confirmation);
//        }
//    });
//  });
}

//After attempted status set, displays confirmation for succession
function Facebook_users_setStatus_confirmation(){
    document.getElementById("error").style.display = "block";
}


//This gets users general info.            
////function Facebook_users_getInfo()
////{
////        var isSessionRunning = ""; 
////            
////          isSessionRunning = FB.getAuthResponse() != null ? true : false;
////          var query = FB.Data.query('select first_name, last_name, "status", pic_square, profile_url, email_hashes from user where uid={0}',
////                                                   FB.getAuthResponse().userID);
////          query.wait(function(result) {  
////              if(result.length > 0) {
////              
////                   //Show Facebook header
////                   ShowHeader(result)
////                   
////                   //Show Status Dialog
////                   ShowStatusDialog(result)
////                   
////                   
////                   //Show Facebook avantar and info for registration page
////                   ShowFacebookForRegistrationPage(result)
////                     
////                   //Set facebook global variables
////                   SetFacebookGlobalVariables(result)
////                    
////                  //Show logged  in/out states
////                  ShowLoggedInLoggedOutStates()
////                  
////                  //Show Messages for myfrontdoor
////                  ShowMessagesForMyFrontDoor(result)
////                  
////              }                                    
////        });     
////     
////     //Exectues functionality if facebook session is active also returns true|false
////     IsSessionActive(isSessionRunning)  
////}

//Facebook Header 
function ShowHeader(result)
{
 //Header
    if(document.getElementById("user-photo") != null){
        //Assign profile image to div.
        var fb_user_image = result[0].pic_square ;
        if( fb_user_image == '' ){
            fb_user_image = '/images/facebook/35x35_noavatar.gif';
        }
        html = '<a href="' + result[0].profile_url + '" target="_blank">';
        html += '<span class="rounded"></span>';
        html += '<img height="35" width="35" border="0" src="' + fb_user_image + '">';
        html += '</a>'; 
        document.getElementById("user-photo").innerHTML = html;
        document.getElementById("facebook-status-out").style.display = "none";  
        document.getElementById("facebook-status-in").style.display = "block";
        
        //Assign name of logged in user
        html = '<a href="' + result[0].profile_url + '" target="_blank">'
        html +=   result[0].first_name
        html += '</a>'; 
        
        document.getElementById("FacebookName").innerHTML = html
    } 
}

//Display Status Dialog
function ShowStatusDialog(result)
{
  //Status dialog
  if(document.getElementById("status-photo") != null){ 
        
         //Assign profile image to div.
        var fb_user_image = result[0].pic_square ;
        if( fb_user_image == '' ){
            fb_user_image = '/images/facebook/50x50_noavatar.gif';
        }
        
        //Display login/logout status for dialog
        document.getElementById("status-wrap").style.display = "block";
        document.getElementById("status-wrap-connect").style.display = "none";
        
        //Add image
        html = '<a href="' + result[0].profile_url + '" target="_blank">';
        html += '<span class="rounded"></span>';
        html += '<img border="0" src="' + fb_user_image + '">';
        html += '</a>'; 
                      
        //Add photo
        document.getElementById("status-photo").innerHTML = html;
         
        //Get full name
        full_name = result[0].first_name;
        
        //Store message in a variable
        status_msg = document.getElementById("ctl00_FacebookStatusDialog1_status_message").innerHTML; 
        
        //Conditional for prepending name. If name not found, leave message as is.
        if(status_msg.substring(0,status_msg.indexOf(" ")) == "is"){
            document.getElementById("ctl00_FacebookStatusDialog1_status_message").innerHTML = full_name + " " + status_msg
        }
        else{
            document.getElementById("ctl00_FacebookStatusDialog1_status_message").innerHTML = status_msg
        }
        
        //Message return by the api that current exists on facebook. Maybe usable in the future. 
        //result[0].status.message     
    }
}

//Show information for facebook registration page
////function ShowFacebookForRegistrationPage(result)
////{
////       //Register My Frontdoor Account
////       if(document.getElementById("fb_avatar") != null){
////        
////            //Assign profile image to div.
////            var fb_user_image = result[0].pic_square ;
////            if( fb_user_image == '' ){
////                fb_user_image = '/images/facebook/35x35_noavatar.gif';
////            }
////            html = '<a href="' + result[0].profile_url + '" target="_blank">';
////            html += '<span class="rounded"></span>';
////            html += '<img height="35" width="35" border="0" src="' + fb_user_image + '">';
////            html += '</a>'; 
////            document.getElementById("image").innerHTML = html;
////            

////            //Assign name of logged in user
////            html = '<a href="' + result[0].profile_url + '" target="_blank">'
////            html +=   result[0].first_name +" "+ result[0].last_name
////            html += '</a>'; 
////            document.getElementById("name").innerHTML = html;
////            
////            if(email_hash != undefined)
////            {
////                document.getElementById("mfd_fb_connected").style.display = "block";
////                document.getElementById("mfd_fb_new_account").style.display = "none";
////            }
////            else{
////                document.getElementById("mfd_fb_connected").style.display = "none";
////                document.getElementById("mfd_fb_new_account").style.display = "block";
////            
////            }    
////      } 
////}

//Set Global variables
function SetFacebookGlobalVariables(result)
{
    //Create global variable for email hash. 
    email_hash = result[0].email_hashes[0];
    
    //Global facebook user id
    facebook_uid = result[0].uid;
                              
}

//Show logged in/out states
//function ShowLoggedInLoggedOutStates()
//{
//      //My frontdoor logged in state
//       if(email_hash != undefined){
//            document.getElementById("loggedin").style.display = "block";
//            document.getElementById("notloggedin").style.display = "none";
//            document.getElementById("my_status").style.display = "none"; 
//        }
//        else
//        {
//          //Display notification if not linked
//          if(document.getElementById("LinkAcctNote") != null)
//          {
//            document.getElementById("LinkAcctNote").style.display = "block";
//          }
//       }
//}

//Display messages for myfrontdoor
////function ShowMessagesForMyFrontDoor(result)
////{
////   //Display actor's first name on welcome page 
////    if(document.getElementById("actor") != null)
////    {
////        document.getElementById("actor").innerHTML = result[0].first_name
////    }
////}

//Determines if session is active
////function IsSessionActive(isSessionRunning)
////{
////      //Execute this block below only when session is not running
////     if(isSessionRunning == ""){
////        isSessionRunning = false
////      }
//// 
////    if(isSessionRunning == false){
////        //For facebook login in header
////        document.getElementById("facebook-status-out").style.display = "block"
////        
////        //For update status module
////        if(document.getElementById("status-wrap") != null)
////        {
////            document.getElementById("status-wrap").style.display = "none";
////            document.getElementById("status-wrap-connect").style.display = "block"
////        } 
////        
////        //Display registration avatar
////        if(document.getElementById("mfd_fb_new_account") != null)
////        {
////            document.getElementById("mfd_fb_connected").style.display = "none";
////             document.getElementById("mfd_fb_new_account").style.display = "block";
////        }
////    }
////    
////    return isSessionRunning
////}


////function UserLogsInToFBWhileOnRegistrationForm()
////{
////}

//Display Notification Banner
function DisplayNotificationBanner()
{ 
    var isSessionRunning = "";
    
        FB.getLoginStatus(function(response) {
               if (response.authResponse) {
                    isSessionRunning = true;       
                   //Display Notification B
                   if(readCookie("FrontDoorUserPers") == null)
                   { 
                      document.getElementById('HomeFacebookBanner').innerHTML =  notificationB();
                   }
                   //Display Notification D
                   
                   else
                   {
                    document.getElementById('HomeFacebookBanner').innerHTML =  notificationD();
                   }
               }
               if(isSessionRunning == ""){
                    isSessionRunning = false
               } 
               
               if(isSessionRunning == false){
                    //Display Notification A
                    if(readCookie("FrontDoorUserPers") == null){
                      document.getElementById('HomeFacebookBanner').innerHTML = notificationA();
                    }
                    //Display Notification C
                    else if(readCookie("FrontDoorUserPers") != null){
                      document.getElementById('HomeFacebookBanner').innerHTML = notificationC();
                    }
               }
        });
   
}

////function ieBanner() {
////    var browser = navigator.appName;
////  if(browser == "Microsoft Internet Explorer"){
////        document.getElementById('no-show').style.top ="3px";
////        document.getElementById('dont-ask').style.top ="0";
////        document.getElementById('fb-close').style.top ="2px";
////    }
////}

//Notification A � Ask for both facebook connect and myfrondoor login
function notificationA()
{
  var html="";
    html+="<div id='banner-wrap' class='clearfix'>";
    html+="<div id='banner'>";
    html+="<div class='banner-content'>";
    html+="<span class='now-how'>";
    html+="Save and share properties, articles and more with MyFrontDoor. <a href='/my_frontdoor/sign_up.aspx'>Register with FrontDoor</a> or use";
    html+="</span>";
    html+="<div class='fb-button'>";
    html+="<a onclick='facebook_login(); return false;' href='javascript://(0)'><img src='/images/facebook/connect-button.png' alt='fb-connect' title='fb-connect'/></a>";
    html+="</div>";
    
    html+="<div class='banner-right'>";
    html+="<span class='no-show' id='no-show'>";
    html+="<input type='checkbox' onclick='SetOptoutCookie()' />";
    html+="</span>";
    html+="<span class='dont-ask' id='dont-ask'>Don't ask Again</span>";
    html+="<span class='fb-close' id='fb-close'><a href='javascript:void(0);' onclick='fbClose()'><img src='/images/facebook/x.png' alt='x' height='11' width='11' /></a></span>";
    html+="</div>";
    
    html+="</div>";
    html+="</div>";
    html+="</div>";    
    
    return html;
    
}


//Notification B � Logged into Facebook, but not front door. We then need to ask to login to Frontdoor
function notificationB()
{
  
     var html="";
    html+="<div id='banner-wrap' class='clearfix'>";
    html+="<div id='banner'>";
    html+="<div class='banner-content'>";
    html+="<span class='now-how'>";
    html+="<a href='/my_frontdoor/Default.aspx'>MyFrontDoor</a> profiles grant you quick access to your favorite listings, articles & search criteria. <a href='/my_frontdoor/Default.aspx'>Sign up</a>.";
    html+="</span>";
    html+="<div class='banner-right'>";
    html+="<span class='no-show'>";
    html+="<input type='checkbox' onclick='SetOptoutCookie()' />";
    html+="</span>";
    html+="<span class='dont-ask'>Don't ask Again</span>";
    html+="<span class='fb-close'><a href='javascript:void(0);' onclick='fbClose()'><img src='/images/facebook/x.png' alt='x' height='11' width='11' /></a></span>";
    html+="</div>";
    html+="</div><!--END banner-content-->";
    html+="</div><!--END banner-->";
    html+="</div><!--END banner-wrap -->";
    
    return html;
}

//Notification C � Logged into Frontdoor, but not facebook so we then need the facebook connect button. 
function notificationC()
{
    var html="";
    html+="<div id='banner-wrap' class='clearfix'>";
    html+="<div id='banner'>";
    html+="<div class='banner-content'>";
    html+="<div class='fb-button'>";
    html+="<a href='javascript:void(0);' onclick='facebook_login(); return false;'><IMG SRC='/images/facebook/connect-button.png'></a>";
    html+="</div>";
    html+="<span class='now-how'>";
    html+="Now you can share your favorite houses, stories and more with your Facebook friends. <a href='http://www.frontdoor.com/Neighborhood/Facebook-Connect-Text/55064' target='_blank'>Here's how</a>";
    html+="</span>";
    html+="<div class='banner-right'>";
    html+="<span class='no-show'>";
    html+="<input type='checkbox' onclick='SetOptoutCookie()' />";
    html+="</span>";
    html+="<span class='dont-ask'>Don't ask Again</span>";
    html+="<span class='fb-close'><a href='javascript:void(0);' onclick='fbClose()'><img src='/images/facebook/x.png' alt='x' height='11' width='11' /></a></span>";
    html+="</div>";
    html+="</div><!--END banner-content-->";
    html+="</div><!--END banner-->";
    html+="</div><!--END banner-wrap -->";

   
    
     return html;
}

//Notification D � Logged into both send to the fan page. 
function notificationD()
{
    var html="";
    html+="<div id='banner-wrap' class='clearfix'>";
    html+="<div id='banner'>";
    html+="<div class='banner-content'>";
    html+="<span class='fan'>";
    html+="Become a FrontDoor <a href='http://www.facebook.com/frontdoor' target='_blank'>Fan on Facebook</a> and get the latest on what's happening on the hottest real estate site.";
    html+="</span>";
    html+="<div class='banner-right'>";
    html+="<span class='no-show'>";
    html+="<input type='checkbox' onclick='SetOptoutCookie()' />";
    html+="</span>";
    html+="<span class='dont-ask'>Don't ask Again</span>";
    html+="<span class='fb-close'><a href='javascript:void(0);' onclick='fbClose()'><img src='/images/facebook/x.png' alt='x' height='11' width='11' /></a></span>";
    html+="</div>";
    html+="</div><!--END banner-content-->";
    html+="</div><!--END banner-->";
    html+="</div><!--END banner-wrap -->";
    
    return html;
}

//Logout of facebook
////function facebook_log_out()
////{
////    FB.logout(function() { reloadCurrentPage(); LogoutMyFrontdoor();})
////}

//Reload page
////function reloadCurrentPage() {

////  window.setTimeout(toggleFacebookComponentStates, 300)
////}

////function LogoutMyFrontdoor()
////{
////  if(email_hash != undefined)
////    {
////     $(function() {
////          $.ajax({
////            type: "POST",
////            url: "/controls/AjaxCalls/Facebook/LogOutConnectedUser.aspx",
////            data: "",
////            success: function(output) {
////                document.getElementById("loggedin").style.display = "none";
////                document.getElementById("notloggedin").style.display = "block";
////            }
////          });
////       });
////   }
////}

//Toggle component states(header and status dialogs)
////function toggleFacebookComponentStates()
////{
////if(document.getElementById("facebook-status-in")){
////     document.getElementById("facebook-status-in").style.display = "none";
////     
////     document.getElementById("facebook-status-out").style.display = "block";
////     
////     document.getElementById("facebook-status-out").style.display = "block";
////}     
////    
////     
////     if(document.getElementById("status-wrap") != null){
////        document.getElementById("status-wrap").style.display = "none";
////        document.getElementById("status-wrap-connect").style.display = "block";
////     }
////     
////     if(document.getElementById("HomeFacebookBanner") != null ){
////       DisplayNotificationBanner() 
////     } 
////     
////      if(document.getElementById("LinkAcctNote") != null)
////      {
////        document.getElementById("LinkAcctNote").style.display = "none";
////      }
////}

//Closes facebook notification bar
function fbClose(){
    document.getElementById('banner-wrap').style.display = "none";
}

//If or not your status is updated.
function fbError(){
    var apples = true;
    if(apples){
        document.getElementById('error').style.display = "block";
    }else{
        document.getElementById('error').style.backgroundColor = "#F5CBCB";
        document.getElementById('error').style.display = "block";
    }
}


//function FacebookAddLoadEvent(func)
//{   
//    var oldonload = window.onload;   
//    if (typeof window.onload != 'function') 
//    {   
//      window.onload = func;   
//    } 
//    else 
//    {   
//      window.onload = function() 
//      {   
//        if (oldonload) {   
//          oldonload();   
//      }   
//    func();   
//    }   
//  }   
//}   

////Add onload event to page but first check if this module is stand alone
//FacebookAddLoadEvent(init);   

////Add a custorm third function if needed
//FacebookAddLoadEvent(function() {   
//    /* more code to run on page load */  
// });   
 
 
/* FOR TEXT AREA STATUS */
/* GET STATUS AFTER MODULE LOADS*/
////function init() {
////    
////    //Display Banner Notification
////    if(document.getElementById('HomeFacebookBanner') != null )
////    {
////     DisplayNotificationBanner()   
////    }
////    
////    //Persist status for status dialog
////    if(document.getElementById('ctl00_FacebookStatusDialog1_status_message') != null)
////    {
////        fbStatus = document.getElementById('ctl00_FacebookStatusDialog1_status_message').innerHTML;
////    }
////    
////    window.setTimeout(Facebook_users_getInfo, 300);    
////}




/*RETURN TO PREV STATUS (NO UPDATE)*/
function statusReturn()
{    
     if(document.getElementById('ctl00_FacebookStatusDialog1_status_message').innerHTML == "")
     {
        document.getElementById('ctl00_FacebookStatusDialog1_status_message').innerHTML = fbStatus;
    }
}

/*CLEAR BOX*/
function statusClear(){
    document.getElementById('ctl00_FacebookStatusDialog1_status_message').innerHTML = '';
}


//Load Status Diaglog
 

////function GetFacebookStatusDialog(message,responsObjId) {
////        $(function() {
////          $.ajax({
////            type: "POST",
////            url: "/controls/AjaxCalls/Facebook/Status.aspx?message=" + message,
////            data: "",
////            success: function(output) {
////              $("#AjaxResponse").html(output);
////            }
////          });
////        });
////      }
      
function SetOptoutCookie() {
        $(function() {
          $.ajax({
            type: "POST",
            url: "/controls/AjaxCalls/Facebook/Optout.aspx",
            data: "",
            success: function(output) {
              //$("#AjaxResponse").html(output);
            }
          });
        });
        //Close notification bar
        fbClose()
      }      
      

//BYRON


//Connect Myfrontdoor Account with Facebook.
function facebook_connectRegisterUsers(email, pwd)
{
    document.getElementById("progress_icon").style.display = "block";

 //create email hash
 $(function() {
      $.ajax({
        type: "POST",
        url: "/controls/AjaxCalls/Facebook/Connect_registerUsers.aspx?email=" + email + "&password=" +pwd + "&facebook_uid=" + facebook_uid,
        data: "",
        success: function(output) {
            document.getElementById("progress_icon").style.display = "none";
            /*
             * If user created email hash matches what's on facebook's server 
             * join accounts(by saving email hash to db
             * 
            */
            window.setTimeout(function () {
              var isSessionRunning = false; 

              //FB.getLoginStatus(function(response) {
                FB.getLoginStatus(function(response) {
                    if ((response.status) && (response.status == "connected")) {
            
                      isSessionRunning = true;
                      var query = FB.Data.query('select first_name, last_name, "status", pic_square, profile_url, email_hashes from user where uid={0}',
                                                               FB.getAuthResponse().userID);
                      query.wait(function(result) {  
                                if(result.length > 0) {   
                                        if(result[0].email_hashes[0] != undefined)
                                        {
                                            ShowConfirmation("Successful", "Your Facebook account has been linked to your MyFrontDoor account!");
                                            document.getElementById("loggedin").style.display = "block";
                                            document.getElementById("notloggedin").style.display = "none";
                                            document.getElementById("my_status").style.display = "none";
                                        }
                                         //User hashed email address doesn't not match what's on facebooks server
                                        else
                                        {
                                            if(document.getElementById("error2")!= null)
                                            {
                                                document.getElementById("error2").style.display="block";
                                            }
                                            //ShowConfirmation("Unsuccessful", "The accounts could not be linked because the email address you supplied does not match your email address on facebook or you have already linked accounts.");
                                        } 
                                    }                                    
                                 });  
                      }
                  });
              //});    
            }, 
           3000
            )
        }
      });
   });
}


//UnConnect Myfrontdoor Account with Facebook.
function facebook_connectUnRegisterUsers(email)
{

    $(function() {
      $.ajax({
        type: "POST",
        url: "/controls/AjaxCalls/Facebook/Connect_unRegisterUsers.aspx?email=" + email,
        data: "",
        success: function(output) {
            if(output == "successful")
            {
                ShowConfirmation("Successful", "You have unlinked your myfrontdoor and facebook accounts");
            }
            else
            {
                ShowConfirmation("Unsuccessful", "Your accounts could not be unlinked");
            }
        }
      });
   });
}


 function ShowConfirmation(title, message)
        {
            //tb_showhtml('','your.aspx?width=x&height=y'','')
            //the first parameter could be for a title to the box if you wanted
            //we've never used the third parameter
           var IE6 = navigator.appVersion.indexOf("MSIE 6.")
           if(IE6 != -1)
           {
             window.scrollTo(0,0);
             tb_showhtml(title, "/controls/AjaxCalls/Facebook/Confirmation.aspx?height=176&width=325&inlineId=hiddenModalContent&modal=true&message=" + message + "&title=" + title, false); 
           }
           else
           {
            tb_showhtml(title, "/controls/AjaxCalls/Facebook/Confirmation.aspx?height=176&width=325&inlineId=hiddenModalContent&modal=true&&message=" + message + "&title=" + title, false); 
           }
}
        
        
//function facebook_friendsGetAppUsers()
//{   
//alert(FB.Facebook.apiClient.friends_getAppUsers(function (result){}))
////FB.Facebook.apiClient.friends_getAppUsers(function (results){
////             
////    
////    });
//}

function CheckIfRegisteredUser()
{
    //Not a registered user
    if(email_hash == undefined)
    {
        //Go to welcome page if not on registration form
        if(window.location.href.indexOf("sign_up.aspx") == -1 )
        {
            //Go to the connect accts page if already logged into myfrontdoor
            if(IsAlreadySignedIn() == true)
            {
                window.location = "/my_frontdoor/connect_accts.aspx?url=" + window.location.href;
            }
            //Go to welcome page if not logged into MyFrontdoor
            else
            {
              window.location = "/my_frontdoor/welcome.aspx?url=" + window.location.href;
            }    
        }
    }
    //Is registered user
    else
    {
       $(function() {
          $.ajax({
            type: "POST",
            url: "/controls/AjaxCalls/Facebook/LogInConnectedUser.aspx?email_hash=" + email_hash,
            data: "",
            success: function(output) {
            
            }
          });
       });
    }
}


////function rtrim(stringToTrim) {
////	return stringToTrim.substring(0,stringToTrim.length-2);
////}































