/*
 * 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.Connect.requireSession(function() { facebook_onlogin(); })
}
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.Connect.showFeedDialog(81722621772, template_data, null, null, FB.FeedStorySize.shortStory, FB.RequireConnect.promptConnect);
      
//  // Load the feed form
//  FB.ensureInit(function() {
//           FB.Facebook.apiClient.users_hasAppPermission('publish_stream', function(result){
//            //Try 
//            try{
//                //Set if user authorized feeds
//               if(result == true){
//                  FB.Connect.showFeedDialog(80810561772, template_data, null, null, FB.FeedStorySize.shortStory, FB.RequireConnect.promptConnect);
//                }
//                //If not authorize, display authorization dialog 
//                else{
//                 
//                  facebook_publish_prompt_permission('publish_stream');
//                }
//            }
//            //Catch
//            catch(error){
//               // alert("There was an error: " + error);
//            }
//            
//        });  
//        
//  });
}

function facebook_publish_prompt_permission(permission) {
  FB.ensureInit(function() {
    FB.Connect.showPermissionDialog(permission, function(status){
        permission_granted = status ? true : false; 
        if(permission_granted == true)
        {
            FB.Connect.showFeedDialog(80810561772,  gl_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.ensureInit(function() {
      FB.Connect.get_status().waitUntilReady(function(status) {
          if (status != FB.ConnectState.userNotLoggedIn) {
            // 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";
            }
          }
        });
    });
}
var status_msg = "";
var full_name = "";
var gl_status = "";
//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.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.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";
}

///Change from status check to session check because errors are thrown with FB.Facebook.apiClient.get_session().uid
var fbStatus;
//This gets users general info.            
function Facebook_users_getInfo()
{

  FB.ensureInit(function() {
  var isSessionRunning = "";
    FB.Facebook.get_sessionState().waitUntilReady(function(session){
        isSessionRunning = session ? true : false;
         FB.Facebook.apiClient.users_getInfo([FB.Facebook.apiClient.get_session().uid],["first_name","last_name", "status", "pic_square","profile_url"],function(result, ex) {     
              if(result.length > 0) {
                    //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 +" "+ result[0].last_name
                        html += '</a>'; 
                        document.getElementById("FacebookName").innerHTML = html

                  } 
                
                  //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
                        
                  }
              }                                    
        });      
     });
     
     //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 Notification Banner
function DisplayNotificationBanner()
{
 
  FB.ensureInit(function() {
    var isSessionRunning = "";
    FB.Facebook.get_sessionState().waitUntilReady(function(session){
    isSessionRunning = session ? true : false;       
       //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://(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.Connect.logout(function() { reloadCurrentPage(); })
}

//Reload page
function reloadCurrentPage() {

  window.setTimeout(toggleFacebookComponentStates, 300)
}

//Toggle component states(header and status dialogs)
function toggleFacebookComponentStates()
{
     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() 
     } 
 
}

//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