var Facebook = new Fbook("Facebook");
//var origCall = Function.prototype.call;
//Function.prototype.call = function (thisArg) {
//    console.log(thisArg);

//    var args = Array.prototype.slice.call(arguments, 1);
//    origCall.apply(thisArg, args);
//};


//========================================================
//  Constructor
//  Initialize parameteres
//========================================================
function Fbook(ObjectInstanceName)
{

    var status_msg = "";
    var full_name = "";
    var gl_status = "";
    var first_name = "";
    var fbook_avatar = ""
      //Supply stream attachments
           
    ///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;
  
}

  var TimeOutModal;



//========================================================
//  Login to facebook
//========================================================
 
Facebook.Login = function() {
    //console.log("in Facebook.Login");
    with (this) {
    
      FB.login(function(response) {
        //console.log(response.authResponse);
        if (response.authResponse) {
            if(IsAlreadySignedIn())
            {
                 window.setTimeout(function(){
                    Facebook.Connect(readUserPersCookie(PERSONCOOKIE_EMAIL), readUserPersCookie("pwd"));
                },2000)
            }    
            else{
                //Close to existing modal
               Facebook.Modal_Close();
               Facebook.fadeOutBackground();
               
                //Check if user is connected
                window.setTimeout(function(){ 
                    LogInConnectedUser();
                    },2000);  
            }
            
            function LogInConnectedUser()
            {
                    //console.log("Facebook.Login -> LogInConnectedUser");
                    //Publish to stream 
                    Facebook.Show_PermissionDialog_Social_Commenting("publish_stream,email")

                    //Is registered user
                    $(function() {
                            $.ajax({
                            type: "POST",
                                url: "/controls/AjaxCalls/Facebook/LogInConnectedUser.aspx?Facebook_UserId=" + Facebook.GetUserId(),
                            data: "",
                                success: function(output) { 
                                //RemoveCookie("TempC");
                                    Facebook.CompleteTempCAction(rtrim(output));
                                    ShowLoggedIn(true);
                                    $.event.trigger('SignInEvt');
                                }
                            });
                        });
                }
                    
                 //========================================================
                //  Private function: Trim of the trailing whitepace
                //========================================================
                function rtrim(stringToTrim) {
                    return stringToTrim.substring(0,stringToTrim.length-2);
                }       
                
          } 
       }, {scope:'publish_stream,email', enable_profile_selector: 1});
    };
}   

//========================================================
//  Login to facebook from registration form 
//========================================================
 
Facebook.Register_Login = function() {

    FB.login(function() { }, {scope:'publish_stream,email', enable_profile_selector: 1});
 
}

//========================================================
//  Login to facebook
//========================================================
 
Facebook.Login_Share = function(IdListing, shareType, sharedURL, title, metadescription) {

    var shortURL = GetShortURL(sharedURL);
    var thumbnail = "http://" + staticImgHostname.replace("static.localhost.com", "static-img.frontdoor-dev.gabriels.net") + "/images/fd-facebook-logo.jpg";
    
    with (this) {
           Facebook.Modal_Close();
                FB.getLoginStatus(function(response) {
                    if ((response.status) && (response.status == "connected")) {
                        var attachment= {
                        'name': title,
                        'href': shortURL,
                        'description': metadescription,
                        'media':
                            [{'type': 'image',
                            'src':  thumbnail, 
                                'href': shortURL}]
                        }
                        
                        Facebook.Stream_Publish('', attachment, null, '', '', null, false)
                      
                     }
                     else
                     {
                        // FB.Connect.requireSession(function(){
                        FB.login(function(response) {
                          if (response.authResponse) {
                            if(IsAlreadySignedIn())
                            {
                                 window.setTimeout(function(){
                                    Facebook.Connect(readUserPersCookie(PERSONCOOKIE_EMAIL), readUserPersCookie("pwd"), false);
                                },2000)
                            }    
                            else{
                                    //Close to existing modal
                                    Facebook.Modal_Close();
                                    
                                    //Check if user is connected
                                    window.setTimeout(function(){
                                        LogInConnectedUser();
                                        },2000);  
                                }
                                
                                function LogInConnectedUser()
                                {
                                        //Publish to stream 
                                       // Facebook.Show_PermissionDialog_Social_Commenting("publish_stream,email")

                                        //Is registered user
                                        $(function() {
                                                $.ajax({
                                                type: "POST",
                                                url: "/controls/AjaxCalls/Facebook/LogInConnectedUser.aspx?Facebook_UserId=" + Facebook.GetUserId(),
                                                data: "",
                                                    success: function(output) {
                                                        if(rtrim(output) == "success")
                                                        {
                                                            ShowLoggedIn(true);
                                                            document.getElementById("FB_in").style.display = "block";
                                                            document.getElementById("FD_in").style.display = "none";
                                                            document.getElementById("FD_FB_out").style.display = "none"; 
                                                      
                                                        }
                                                    }
                                                });
                                            });
                                        
                                    }
                                        
                                     //========================================================
                                    //  Private function: Trim of the trailing whitepace
                                    //========================================================
                                    function rtrim(stringToTrim) {
                                        return stringToTrim.substring(0,stringToTrim.length-2);
                                    }       
                                      var attachment= {
                                                            'name': title,
                                                            'href': shortURL,
                                                            'description': metadescription,
                                                            'media':
                                                                [{'type': 'image',
                                                                'src':  thumbnail, 
                                                                    'href': shortURL}]
                                                            }
                        
                                                         Facebook.Stream_Publish('', attachment, null, '', '', null, false)   
                                                  
                              }
                          })
                     }
                 });   
           Facebook.fadeOutBackground();
    };

}   

//========================================================
//  Executes when user logs on 
//========================================================

Facebook.OnLogin = function(){
      //console.log("Facebook.OnLogin");
      with (this) {    
//        window.setTimeout(function(){

            //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;
            }
            //Get logged in user
            
            window.setTimeout(function(){
                    Facebook.User_GetInfo();
            }, 300);
            
//        }, 500);  
            
       
    }        
}

//========================================================
//  Logout: facebook || myfrontdoor
//========================================================
 
Facebook.Logout = function()
{
    //console.log("Facebook.Logout");
    with (this)
    {
        //Close any open modals
        Facebook.Modal_Close();
        
        var TmpFBId = Facebook.GetUserId();
        //Logout of facebook
        FB.logout(function() { LogoutMyFrontdoor(); PopupMessage(); ToggleComponents(); });
        
        //========================================================
        //  Private function: Toogle header components
        //=========================================================
        
        function ToggleComponents() 
        {
             window.setTimeout(function()
             {
                window.location.replace("/Default.aspx");
                   // ToggleFacebookComponentStates();
             },1000);  
        }
        
        function PopupMessage()
        { 
            Facebook.Confirmation_Modal("You are logging out of both FrontDoor and Facebook.", "Facebook");  
          
            TimeOutModal = window.setTimeout(function()
            {
                Facebook.Modal_Close();
                Facebook.fadeOutBackground();    
            },5000);           
        }
        
        //========================================================
        //  Private function: Logout myfrontdoor
        //========================================================
        function LogoutMyFrontdoor()
        {
            //console.log("Facebook.Logout -> LogoutMyFrontdoor");
            $(function()
            {
                $.ajax(
                {
                    type: "POST",
                    url: "/controls/AjaxCalls/Facebook/IsAccountLinked.aspx?Facebook_UserId="+TmpFBId ,
                    data: "",
                    success: function(output)
                    {
                        if(output == "success")
                        {
                            $(function()
                            {
                                $.ajax(
                                {
                                    type: "POST",
                                    url: "/controls/AjaxCalls/Facebook/LogOutConnectedUser.aspx",
                                    data: "",
                                    success: function(output)
                                    {
                                        ChangeUserAction();

                                        $.event.trigger('SignOutEvt');
                                    }
                                });
                            });
                        }
                    }
                });
            });
        }

        //Toggle component states(header and status dialogs)
        function ToggleFacebookComponentStates()
        {
            document.getElementById("FD_in").style.display = "none";
            document.getElementById("FB_in").style.display = "none";
            document.getElementById("FD_FB_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";
            }
          
            if(document.getElementById("FB-Reg-LoggedIn") != null)
            {
                document.getElementById("FB-Reg-Not-LoggedIn").style.display = "block";
                document.getElementById("FB-Reg-LoggedIn").style.display = "none";
                document.getElementById("Reg_Status").innerHTML = "Add Your Facebook Account"    
                document.getElementById("first_name").value = ""
                document.getElementById("last_name").value = ""     
                document.getElementById("Reg_Optional").style.display = "block";
                document.getElementById("Reg_Name").innerHTML = "";
                document.getElementById("Reg_Avatar").innerHTML = "";
                document.getElementById("Reg_Success").style.display = "none";
                
                if(gE("fb_notification"))
                {
                    gE("fb_notification").style.display = "none";
                    gE("FB-Tab-LoggedIn").style.display = "none";   
                    gE("FB-Tab-Not-LoggedIn").style.display = "block";
                }
            }      
            
            RelocateToHP();
        }

        //Log out of My Accounts section 
        function RelocateToHP()
        {
            // 2010-03-17 MikkR. Ticket 6216. Added pro/account to urls from which to redirect to homepage.
            if (window.location.href.indexOf('pro/account') != -1 ||
                window.location.href.indexOf('recent-activity') != -1 ||
                window.location.href.indexOf('my-folders') != -1 ||
                window.location.href.indexOf('settings') != -1 || 
                window.location.href.indexOf('facebook') != -1)
            {
                window.location.replace("/Default.aspx")
            }
        }        
        //End function    
    }
}

//========================================================
//  Toggle Component states on every page
//========================================================
   
Facebook.Toggle_Component_States = function(){ 
     //console.log("Facebook.Toggle_Component_States");
     with (this) { 
     
        window.setTimeout(function(){        
         
//            document.getElementById("FB_in").style.display = "none";   
//            document.getElementById("FD_in").style.display = "none";   
//            document.getElementById("FD_FB_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";
            }
            
            if(document.getElementById("FB-Tab-LoggedIn") != null){
                gE("fb_notification").style.display = "none";
                gE("FB-Tab-Not-LoggedIn").style.display = "block";
                gE("FB-Tab-LoggedIn").style.display = "none";


            }
               
           if(document.getElementById("log_in_wrapper")){
                document.getElementById("log_in_wrapper").style.display = "block"
                Facebook.loginHeaderWidth();
            }
            
             //Change settings tab to redirect to sign up form
             if(window.location.href.indexOf('/my-folders') != -1 || 
                    window.location.href.indexOf('/settings') != -1 ||  
                    window.location.href.indexOf('/facebook') != -1 ||  
                    window.location.href.indexOf('/recent-activity') != -1 || 
                    window.location.href.indexOf('/register') != -1 || 
                    window.location.href.indexOf("/MyFolders.aspx") != -1)
            {
                 if(IsAlreadySignedIn()){ 
                                            
                    if(gE("settings"))
                    {
                        gE("settings").innerHTML = "<a href=\"/account/settings/\">Settings</a>";
                        if(window.location.href.indexOf('settings') != -1)
                        {
                            gE("settings").innerHTML = "Settings";
                        }
                    }                    
                    
                }
                else
                {
                    
                    if(gE("settings"))
                    {
                        gE("settings").innerHTML = "<a href=\"/account/register-facebook/\">Settings</a>";
                    }
                    
                        if(window.location.href.indexOf('settings') != -1)
                        {
                            window.location = "/account/register-facebook/"
                        }
                }
            }
            
       
        /*-- SET FB CLASS --*/
            if(document.getElementById("NavTabs"))
            {
                //emailHover();
                $(function(){
                        
                    var $share = $('.share');
                
                    $share.each(function(){
                        $(this).removeClass();
                        $(this).addClass('share');
                    });
                });
                 //end function
           
            
            }
        
        },300);  
            
     }
    
}



//========================================================
//  Get facebook user
//========================================================
Facebook.User_GetInfo = function() {
    //console.log("Facebook.User_GetInfo");
    var isSessionRunning = false;
      
    FB.getLoginStatus(function(response) {
        if ((response.status) && (response.status == "connected")) {
                isSessionRunning = true;
                //console.log(response);
                
                var query = FB.Data.query('select first_name, last_name, pic_square, profile_url, email_hashes from user where uid={0}',
                                                   FB.getAuthResponse().userID);
                query.wait(function(response) {
                                    if(response.length > 0){  
                                        //Show Facebook header
                                        ShowHeader(response);
                                        //Show Status Dialog
                                        ShowStatusDialog(response);
                                        //Show Facebook avantar and info for registration page
                                        ShowFacebookForRegistrationPage(response);
                                        //Set facebook global variables
                                        SetFacebookGlobalVariables(response);
                                        //Show logged  in/out states
                                        ShowLoggedInLoggedOutStates();
                                        //Show Messages for myfrontdoor
                                        ShowMessagesForMyFrontDoor(response);
                                        //Show Connect Connect Dialog messages
                                        ShowConnectMessages(response);
                                        //Share Buttons
                                        ShareButtons();
                                        //Fab Tab page
                                        ShowFacebookForFBTabPage(response);
                                        //Log into my frontdoor
                                        LogIntoMyFrontDoor();
                                        // hide div for loading
                                       HideLoadingDiv();
                     }                                    
               });      
         }
         
         //Exectues functionality if facebook session is active also returns true|false
         IsSessionActive(isSessionRunning);     
     });
    
    //========================================================
    //  Private function: Facebook Share Buttons -BM 12/30/09
    //========================================================
    
    function ShareButtons()
    { 
        if(document.getElementById("NavTabs"))
        {
            $(function(){
                /*-- SET FB CLASS --*/
                var $fbshare = $('.fbshare_sm');
                var $share = $('.share');
                
                $fbshare.each(function(index){
                      $(".fbshare_sm").show();
                });
                
                $share.each(function(){
                    $(this).removeClass();
                    $(this).addClass('share_sm');
                  //  $(".fbshare_sm").show();
                });            
                //emailHover();
                $(".right.shareall").hide();
                $(".fbshareall").show();
               // $shareAll.addClass('shareallfb');
                //FB Alert for Settings and Sign UP
                $("#FB-Reg-LoggedIn").show();
           
           });
        }    
    }
    
    function HideLoadingDiv()
    {
        var divLoading = gE("loading");
        if(divLoading != null)
           divLoading.style.display = "none";
    }
    
     //========================================================
     //  Private function: Facebook Header 
     //========================================================
    
    function ShowHeader(result)
    {
        //console.log("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 == null ){
                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("FB_in").style.display = "block"; 
            if (readUserPersCookie(PERSONCOOKIE_USERTYPE) == 2) {
              gE("my_fb").href = "/pro/account/dashboard";
            }
            else {
              gE("my_fb").href = "/account/recent-activity/";
            }
            document.getElementById("FD_in").style.display = "none";  
            document.getElementById("FD_FB_out").style.display = "none";
            document.getElementById("log_in_wrapper").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;
            Facebook.loginHeaderWidth();
        } 
    }
    
     //========================================================
     //  Private function: Connect dialog messages
     //========================================================
    
    function ShowConnectMessages(result)
    {
            window.setTimeout(function(){
                         //Header
                        if(document.getElementById("FacebookNameConnect") != null){
                            
                            //Assign profile image to div.
                            var fb_user_image2 = result[0].pic_square ;
                            if( fb_user_image2 == '' ){
                                fb_user_image2 = '/images/facebook/35x35_noavatar.gif';
                            }
                            html = '<a href="' + result[0].profile_url + '" target="_blank">';
                            html += '<span class="rounded"></span>';
                            html += '<img  border="0" src="' + fb_user_image2 + '">';
                            html += '</a>';                                     
                            document.getElementById("user-photo2").innerHTML = html;
                            
                            document.getElementById("FacebookNameConnect").innerHTML =  "<strong>" + result[0].first_name + "</strong>"
                        } 
                    
                    },3000);
    
    
    }
    
    //========================================================
    //  Private function: 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     
        }
    }
    
     //========================================================
     //  Private function: Show information for facebook registration page
    //========================================================
     
    function ShowFacebookForRegistrationPage(result)
    {
           //Register My Frontdoor Account
           if(document.getElementById("FB-Reg-LoggedIn") != 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 += '<span class="fb_icon"></span>';
                html += '<img border="0" src="' + fb_user_image + '">';
                html += '</a>'; 
                if(document.getElementById("FB-Reg-Not-LoggedIn") != null){
                    document.getElementById("FB-Reg-Not-LoggedIn").style.display = "none";
                 }
                document.getElementById("FB-Reg-LoggedIn").style.display = "block";
                if(document.getElementById("Reg_Status") != null){
                    document.getElementById("Reg_Status").innerHTML = "Your Facebook Account"
                }
                if(document.getElementById("Reg_Success"))
                {
                    document.getElementById("Reg_Success").style.display = "none"
                }
                document.getElementById("Reg_Avatar").innerHTML = html;
                
                if(document.getElementById("Reg_Optional"))
                {
                    document.getElementById("Reg_Optional").style.display = "none";
                }               

                //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("Reg_Name").innerHTML = html;
                //document.getElementById("name").innerHTML = html;
                
                 $(function() {
                $.ajax({
                    type: "POST",
                    url: "/controls/AjaxCalls/Facebook/IsAccountLinked.aspx?Facebook_UserId="+Facebook.GetUserId(),
                    data: "",
                        success: function(output) {
                            if(output == "success")
                            { 
                                if(!IsAlreadySignedIn()){ 
                                    //window.location.reload(true); 
                                    //window.location = "/Accounts/FB_signUp.aspx"     
                                }   
                            }
                            else{
                           
                                if(!IsAlreadySignedIn()){ 
                                    if (gE("first_name")) {                                       
                                        document.getElementById("first_name").value = result[0].first_name;
                                    }
                                    
                                    if (gE("last_name")) {
                                        document.getElementById("last_name").value = result[0].last_name
                                    }
                                    
                                    if (gE("agent_fname")) {                                       
                                        document.getElementById("agent_fname").value = result[0].first_name;
                                    }
                                    
                                    if (gE("agent_lname")) {
                                        document.getElementById("agent_lname").value = result[0].last_name;
                                    }
                                }        
                            }
                        }
                    });
                });
                
               
          } 
          
            //Change settings tab to redirect to sign up form
             if(window.location.href.indexOf('/my-folders') != -1 || 
                    window.location.href.indexOf('/settings') != -1 ||  
                    window.location.href.indexOf('/facebook') != -1 ||  
                    window.location.href.indexOf('/recent-activity') != -1 || 
                    window.location.href.indexOf("/MyFolders.aspx") != -1)
            {
                $(function() {
                    $.ajax({
                        type: "POST",
                        url: "/controls/AjaxCalls/Facebook/IsAccountLinked.aspx?Facebook_UserId="+Facebook.GetUserId(),
                        data: "",
                            success: function(output) {
                                if(output != "success")
                                { 
                                    if(!IsAlreadySignedIn()){ 
                                        
                                    
                                        if(gE("settings"))
                                        {
                                            gE("settings").innerHTML = "<a href=\"/account/register-facebook/\">Settings</a>";
                                        }
                                       
                                           if(window.location.href.indexOf('settings') != -1)
                                           {
                                             window.location = "/account/register-facebook/"
                                           }
                                    }        
                                }
                            }
                        });
                    });
                }
                //End 
    }
    
       function ShowFacebookForFBTabPage(result)
        {
           //Register My Frontdoor Account       
           if(document.getElementById("FB-Tab-LoggedIn") != 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 border="0" src="' + fb_user_image + '">';
                html += '</a>'; 
                
                document.getElementById("FB-Tab-Not-LoggedIn").style.display = "none";
                document.getElementById("FB-Tab-LoggedIn").style.display = "block";
                document.getElementById("Tab_Avatar").innerHTML = html;
                
                

                //Assign name of logged in user
                //html = '<a href="' + result[0].profile_url + '" target="_blank">'
                html = '<strong>'
                html +=   result[0].first_name +" "+ result[0].last_name
                html += '</strong>';
                //html += '</a>'; 
                
                document.getElementById("Tab_Name").innerHTML = html;
                //document.getElementById("name").innerHTML = html;
                
                 $(function() {
                    $.ajax({
                        type: "POST",
                        url: "/controls/AjaxCalls/Facebook/IsAccountLinked.aspx?Facebook_UserId="+Facebook.GetUserId(),
                        data: "",
                            success: function(output) {
                                if(output == "success")
                                { 
                                    gE("UnlinkAccounts").style.display = "block"
                                    gE("fb_notification").style.display = "none";
                                    
                                }
                                else
                                {
                                  gE("fb_notification").style.display = "block";
                                  
                                  //Handles two sessions
                                  if(IsAlreadySignedIn())
                                  {
                                  gE("fb_notification").style.display = "none";
                                    
                                  }
                                }
                            }
                        });
                });
                
               
          } 
          
    }

     //========================================================
     //  Private function: Set Global variables
    //========================================================
    function SetFacebookGlobalVariables(result)
    {
  
        //Create global email hash for facebook 
        email_hash = result[0].email_hashes[0];
        
        //Global facebook user id for facebook object
        facebook_uid = result[0].uid;
       
        //Global FirstName
        first_name = result[0].first_name
    }
    
     //========================================================
     //  Private function: Show logged in/out states
    //========================================================
    function ShowLoggedInLoggedOutStates()
    {
          //My frontdoor logged in state
        FB.getLoginStatus(function(response) {
            if ((response.status) && (response.status == "connected")) {
                document.getElementById("FB_in").style.display = "block";
                if (readUserPersCookie(PERSONCOOKIE_USERTYPE) == 2) {
                  gE("my_fb").href = "/pro/account/dashboard";
                }
                else {
                  gE("my_fb").href = "/account/recent-activity/";
                }   
            }
            else
            {
              //Display notification if not linked
              if(document.getElementById("LinkAcctNote") != null)
              {
                document.getElementById("LinkAcctNote").style.display = "block";
              }
           }
        });
      }
      
     //========================================================
    //  Private function: 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
        }
    }
    
    //========================================================
    //  Private function: 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("FB_in").style.display = "none";   
            //document.getElementById("FD_FB_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
    }
    //End Get User Info
    
    function LogIntoMyFrontDoor()
    {
           //Login
        $(function() {
                  $.ajax({
                    type: "POST",
                    url: "/controls/AjaxCalls/Facebook/IsAccountLinked.aspx?Facebook_UserId="+Facebook.GetUserId(),
                    data: "",
                        success: function(output) {
                            if(output == "success")
                            {
                                if(IsAlreadySignedIn() == false)
                                {
                                    //Log into my accounts if accounts are linked
                                   $(function() {
                                        $.ajax({
                                        type: "POST",
                                        url: "/controls/AjaxCalls/Facebook/LogInConnectedUser.aspx?Facebook_UserId=" + Facebook.GetUserId(),
                                        data: "",
                                            success: function(output) {
                                               ShowLoggedIn(true);
                                               //RemoveCookie("TempC");
                                               Facebook.CompleteTempCAction(rtrim(output));
                                            }
                                        });
                                    });   
                                }
                                
                            }
                            
                       }
                   })
                   
               })             
               
                function rtrim(stringToTrim) {
                    return stringToTrim.substring(0,stringToTrim.length-2);
                }       
       }
}


//========================================================
//  Connect Facebook User from Frontdoor
//========================================================

Facebook.Connect = function(email, pwd, showsuccess) {
    with (this) {
       // document.getElementById("progress_icon").style.display = "block";
          if(email == "" || email == "Enter your valid e-mail address")
          {
            $("#email_input").addClass("input-error");
            document.getElementById("emailErrLogin").style.display = "block";
            return false
          }
          
          if(validateEmailConnect(email) == false)
          {
              $("#email_input").addClass("input-error");
                document.getElementById("emailErrLogin").innerHTML = "Please check the format of your e-mail address and re-enter(i.e. joe@frontdoor.com).";
                document.getElementById("emailErrLogin").style.display = "block";
          
          }
//          if(validateEmail(email) == false)
//          {
//            document.getElementById("email_input").className = "modal_input small input-error";
//            document.getElementById("pwdFormatErrLogin").style.display = "block";
//            return false
//          }
          
          if(pwd == "" || pwd == "Enter your valid e-mail address")
          {
             $("#password_input").addClass("input-error");
            document.getElementById("pwdErrLogin").style.display = "block";
            return false
          }
          if(gE("loadingconnect")){
            gE("loadingconnect").style.display = "block";
          }
                  
         //create email hash
         $(function() {
              $.ajax({
                type: "POST",
                url: "/controls/AjaxCalls/Facebook/Connect_registerUsers.aspx?email=" + email + "&password=" +pwd + "&facebook_uid=" + Facebook.GetUserId(),
                data: "",
                success: function(output) { 
                    if(rtrim(output) == "success" || rtrim(output).indexOf("lastaction_") > -1){
                        
                            var isSessionRunning = false;
                            
                            FB.getLoginStatus(function(response) {
                                if ((response.status) && (response.status == "connected")) {

                                    isSessionRunning = true;
                                    FB.api(
                                        {
                                          method: 'fql.query',
                                          query: 'SELECT first_name, last_name, pic_square, profile_url, email_hashes FROM user WHERE uid='+FB.getAuthResponse().userID
                                        },
                                        function(result) {
            
                                                    if(result.length > 0) {
                                                     
                                                        Facebook.Modal_Close()
                                                          //window.setTimeout(function () {
                                                          
                                                          //Show linked accounts success if you logged into myfrontdoor then to facebook, not the other way around
                                                          if(showsuccess == undefined)
                                                          {
                                                            Facebook.Confirmation_Modal("<strong>You've successfully linked your accounts.</strong> <br/><br/>Remember, you can now use your Facebook account to log in to FrontDoor.");
                                                                window.setTimeout(function(){
                                                                   Facebook.Modal_Close();
                                                                    Facebook.fadeOutBackground();
                                                                     },3000);
                                                           } 
                                                         
                                                           window.setTimeout(function(){
                                                                    Facebook.CompleteTempCAction(rtrim(output));
                                                                     },3000);
                                                            
                                                        if(gE("UnlinkAccounts"))
                                                        {
                                                            gE("UnlinkAccounts").style.display = "block";
                                                        }
                                                    }                                    
                                                }); 
                                }
                            });  
                    }
                    else
                    {
                        //Success error
                        if(showsuccess == undefined)
                        {
                            
                          Facebook.Confirmation_Modal("You've successfully linked your accounts. You can use your Facebook account to log in to FrontDoor in the future.");
                            TimeOutModal = window.setTimeout(function(){
                                  Facebook.Modal_Close();
                                  Facebook.fadeOutBackground();
                            },5000);   
                        } 
                        
                        if(document.getElementById("Oops_Error"))
                        {
                            window.clearTimeout(TimeOutModal)
                           $("#email_input").addClass("input-error");
                           $("#password_input").addClass("input-error");
                            document.getElementById("Oops_Error").style.display = "block";
                            document.getElementById("emailErrLogin").style.display = "none";
                            document.getElementById("pwdErrLogin").style.display = "none";
                            gE("loadingconnect").style.display = "none";
                        }
                        
                    }
                      
                    
                }
              });
            
              if (gE("loadingconnect")) {
                gE("loadingconnect").style.display = "none";
              }
           });     
           
            //========================================================
            //  Private function: Trim of the trailing whitepace
            //========================================================
            function rtrim(stringToTrim) {
                return stringToTrim.substring(0,stringToTrim.length-2);
            }      
            
          
    };
    
       //========================================================
            //  Private function: Validate email
            //========================================================
             function validateEmailConnect(emailTxt){
                var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
                str = emailTxt;
                str = str.replace(/ /gi,""); 
                validateFlag = true
                for(var i = 0; i< str.split(",").length; i++)
                {   
                    if(!str.split(",")[i].match(emailRegEx))
                    {
                        validateFlag = false;
                    }
                }
                
               
                return validateFlag
        
            }
    //End Connect
}


//========================================================
//  Disconnect Facebook User from Frontdoor
//========================================================
Facebook.Disconnect = function(email) {
    Facebook.Modal_Close()
    with (this) {
          $(function() {
              $.ajax({
                type: "POST",
                url: "/controls/AjaxCalls/Facebook/Connect_unRegisterUsers.aspx?email=" + email,
                data: "",
                success: function(output) {
                    if(output == "successful")
                    {
                       FB.logout(function() { 
                            gE("FB_in").style.display = "none";
                            gE("FD_FB_out").style.display = "none";                            
                            gE("FD_in").style.display = "block";
                            
                            if(gE("FB-Reg-LoggedIn")){            
               
                                gE("FB-Reg-Not-LoggedIn").style.display = "block";
                                gE("FB-Reg-LoggedIn").style.display = "none";
                                gE("Reg_Status").innerHTML = "Add Your Facebook Account"                                      
                                gE("Reg_Optional").style.display = "block";
                                gE("Reg_Name").innerHTML = "";
                                gE("Reg_Avatar").innerHTML = "";
                                gE("Reg_Success").style.display = "none";                                
                            }
                            else
                            {
                                gE("UnlinkAccounts").style.display = "none";
                            }      
                            
                            Facebook.Confirmation_Modal("You have unlinked your FrontDoor and Facebook accounts.");
                            window.setTimeout(function(){
                                  Facebook.Modal_Close();
                                  Facebook.fadeOutBackground();
                            },5000);                                 
                       })
                       
                        
                      
                    }
                    else
                    {
                        window.setTimeout(function(){
                            Facebook.Confirmation_Modal("Your accounts could not be unlinked.");
                            }, 3000)
                    }
                }
              });
           });

    //End Disconnect
   
    };
}

// 2011-02-21 MikkoR. not used anywhere
//////========================================================
//////  Show confirmation modal
//////========================================================
////Facebook.Set_Optout_Cookie = function(Title, Message) {
////     with (this) {
////         $(function() {
////              $.ajax({
////                type: "POST",
////                url: "/controls/AjaxCalls/Facebook/Optout.aspx",
////                data: "",
////                success: function(output) {
////                  //$("#AjaxResponse").html(output);
////                }
////              });
////            });
////            //Close notification bar
////           Facebook.Banner_Close()
////            
////        
////     //End modal    
////    }
////}

// 2011-02-21 MikkoR. not used anywhere
//////========================================================
//////  Closes home page banner
//////========================================================
////Facebook.Banner_Close = function() {
////     with (this) {
////        
////          document.getElementById('banner-wrap').style.display = "none";
////            
////     //End modal    
////    }
////}

 //========================================================
//  Show confirmation modal
//========================================================
Facebook.Confirmation_Modal = function(Message, Title) {
    if(Title == undefined)
    {
        Title = "";
    }
    $(function() {
        $.ajax({
            type: "POST",
            url: "/controls/AjaxCalls/Facebook/successmodal.aspx?Message="+Message + "&Title=" + Title,
            data: "",
                success: function(output) {
                Facebook.fadeInBackground();            
                    //Show success modal                
                     $(output).modal();
                     
                }
        });
    });      
}

 //========================================================
//  Show confirmation modal for bookmarks
//========================================================
Facebook.BMConfirmation_Modal = function(Message, Title, BMSuppress) {
    if(Title == undefined)
    {
        Title = "";
    }
    
    if(BMSuppress == undefined)
    {
        BMSuppress = ""
    }
    
    $(function() {
        $.ajax({
            type: "POST",
            url: "/controls/AjaxCalls/Facebook/bmsuccessmodal.aspx?Message="+Message + "&Title=" + Title + "&BMSuppress=" + BMSuppress,
            data: "",
                success: function(output) {
                Facebook.fadeInBackground();            
                    //Show success modal                
                     $(output).modal();
                     
                }
        });
    });      
}

//========================================================
//  Show confirmation modal error
//========================================================
Facebook.Confirmation_Error_Modal = function(Message, Title) {
    if(Title == undefined)
    {
        Title = "";
    }
    $(function() {
        $.ajax({
            type: "POST",
            url: "/controls/AjaxCalls/Facebook/successmodal.aspx?Message="+Message + "&Title=" + Title,
            data: "",
                success: function(output) {
                Facebook.fadeInBackground();            
                    //Show error modal                
                     $(output).modal();
                     $("#modal").addClass("modal-error"); 
                     
                }
        });
    });      
}

 //========================================================
//  Show confirmation modal for bookmarks
//========================================================
Facebook.AgentTools_Modal = function(MessageType, MessageTitle, MessageBody, IdPhoto, Selected, IdClaim) {
    if (IdPhoto == undefined) { IdPhoto = ""; }
    if (Selected == undefined) { Selected = ""; }
    if (IdClaim == undefined) { IdClaim = ""; }
    
    $(function() {
        $.ajax({
            type: "POST",
            url: "/controls/AjaxCalls/Facebook/AgentTools-Modal.aspx?MessageType=" + MessageType + "&MessageTitle=" + MessageTitle + "&MessageBody=" + MessageBody + "&IdPhoto=" + IdPhoto + "&Selected=" + Selected + "&IdClaim=" + IdClaim,
            data: "",
                success: function(output) {
                Facebook.fadeInBackground();            
                    //Show success modal                
                     $(output).modal();
                }
        });
    });      
}


// 2011-02-21 MikkoR. Not used anywhere
//////========================================================
//////  Publish feed checkbox
//////========================================================
////Facebook.Show_Feed_Checkbox = function() {

////   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";
////                }
////            }
////    });
////}

//========================================================
//  Publish to stream dialog
//  
// user_message String The main user-entered message for the post. This field should typically be blank- only fill this field with content the user has actually entered themselves.
// attachment Object A dictionary object containing the text of the post, relevant links, and optionally a media type. You can also include other key/value pairs which will be stored as metadata. See Stream Attachments for details.
// action_links Object A dictionary of Action links objects, containing the link text and a hyperlink.
// target_id String The ID of the user or the Page where you are publishing the content. If you specify a target_id, the post appears on the wall of the target user, not the user that published the post. This mimics the action of posting on a friend's Wall.
// user_message_prompt String The sentence that appears before the user message field (e.g. "What's on your mind?")
// callback Function A function that takes two parameters: post_id and exception. post_id returns the id of the published post (which can be null if the user cancels). exception returns error description if an error occurred.
// auto_publish Boolean If the user has granted the publish_stream extended permission AND this parameter is true, then the post will be published without user approval. If the user has not set the extended permission, then the method will fail. (Default value is false)
//  actor_id String Allows the logged in user to publish on a Facebook Page's behalf if the user is an admin of the Page. If specified, actor_id indicates the ID of the Page that will publish the post. The post will appear on the Page's Wall as if the Page had posted it. (Default value is null)
//========================================================

Facebook.Stream_Publish = function(user_message, attachment, action_links, target_id, user_message_prompt, callback, auto_publish){
     with (this) {
                 FB.ui(
                   {
                     method: 'stream.publish',
                     message: user_message,
                     attachment: attachment,
                     action_links: action_links,
                     user_message_prompt: user_message_prompt
                   }, callback
                 );


       // FB.Connect.streamPublish(user_message ,attachment , action_links, target_id, user_message_prompt, callback, auto_publish)
     }
}


 //========================================================
//  Show Permissions dialog
//========================================================
Facebook.Show_PermissionDialog_Social_Commenting = function(permission){
         
         //Is this the first time the user logged in               
         FirstTimeLoggedIn();  
        //Check for multi-level permissions
//        FB.showPermissionDialog(permission, function(perms){
//          permission_granted = perms ? true : false ;  
//          
//        });               
               
        
 
     //Show link account window if user is not connected
     $(function() {
        $.ajax({
            type: "POST",
            url: "/controls/AjaxCalls/Facebook/IsAccountLinked.aspx?Facebook_UserId=" + Facebook.GetUserId(),
            data: "",
                success: function(output) {
                    if(output != "success")
                    {                               
                        Facebook.ConnectAccount_Modal()                
                    }
                }
        });
    });  
    
      //Check if user
      function FirstTimeLoggedIn()
      {

        $(function() {
              $.ajax({
                type: "POST",
                url: "/controls/AjaxCalls/Facebook/IsFirstTimeLoggedIn.aspx?Facebook_Uid="+Facebook.GetUserId(),
                data: "",
                success: function(output) {
                    if(output == "unsuccessful")
                    {
                        var attachment ={
                                'description':first_name + ' has just discovered HGTV\'s FrontDoor.com. With 4 million+ homes for sale and thousands of real estate "how-to" articles and video, FrontDoor combines the HGTV experience with the world of real estate. See what\'s for sale near you.'
                                };    
                                Facebook.Stream_Publish('', attachment, null, '', '', null, true)
                    }
                }
            });
        });
        
       
      }      
        
        
        //End dialog function
  }

//Looks like we are not using this function anymore - 08/27/2010.
 //========================================================
//  Publish feed story
//========================================================

//Facebook.Publish_Feed_Story = function(ArticleImage, PageTitle, MetaDescription, Href) {
//    with (this) {
//    
//     
//        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);
//       
//     //End function    
//    }
//}

//2011-02-21 MikkoR. Not used anywhere
//////========================================================
//////  Show Publish permission feed story
//////========================================================
////Facebook.SetStatus = function(status){
////     with (this) {
////       //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) {
////           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
////                       }, function(){ document.getElementById("error").style.display = "block"; }
////                     );
////                  }
////                 
////                 }
////                 //If not authorize, display authorization dialog 
////                 else{
////                 
////                   facebook_prompt_permission('status_update');
////                 }
////              });
////           }
////       }) 
////           
////            
////     /*
////     * 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});
////         
////        }
////        
////        //After attempted status set, displays confirmation for succession
////        function Facebook_users_setStatus_confirmation(){
////            document.getElementById("error").style.display = "block";
////        }


////        }   
////}

//Looks like we are not using this function anymore - 08/27/2010.
//========================================================
//  Show Publish permission feed story
//========================================================
//Facebook.Status_Permission = function(permission){
// with (this) {
//      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, function(){
//                      document.getElementById("error").style.display = "block";
//                });
//            }
//        });
//      });
//   }
//}

//Looks like we are not using this function anymore - 08/27/2010.
 //========================================================
//  Show Publish permission feed story
//========================================================
//Facebook.Publish_Permission = function(Permission) {
//    with(this)
//    {
//        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);
//                }
//            });
//        });
//    }
//}

//2011-02-21 MikkoR. Not used anywhere
//////========================================================
//////  IsFacebook is linked with frontdoor
//////========================================================
////Facebook.IsLinked = function()
////{
////  
////    linked = false
////     $(function() {
////          $.ajax({
////            type: "POST",
////            url: "/controls/AjaxCalls/Facebook/IsAccountLinked.aspx?Facebook_UserId="+Facebook.GetUserId(),
////            data: "",
////            success: function(output) {
////                if(output == "success")
////                {
////                    linked = true
////                    
////                }
////              //$("#AjaxResponse").html(output);
////            }
////          });
////        });
////        
////        return linked
////}

//========================================================
//  Feed Agent setting page modal
//========================================================

Facebook.Settings_MissingInfo_Greeting = function(firstName, sourceLogo, bMissingPassword, bMissingProfileAddress)
{
    $.ajax({
        url: '/controls/ajaxcalls/facebook/Settings_MissingInfo_Greeting.aspx?firstName=' + firstName + '&sourceLogo=' + sourceLogo + '&bMissingPassword=' + bMissingPassword + '&bMissingProfileAddress=' + bMissingProfileAddress,
        success: function(html){
            Facebook.fadeInBackground();
            $(html).modal({
                minHeight: 400,
                minWidth: 400 
            });
        }
   });
   
}
//========================================================
//  Account Login Modal
//========================================================

Facebook.Account_NoPassword = function(email, firstName, activationId, sourceName, sourceLogo)
{
    $.ajax({
        url: '/controls/ajaxcalls/facebook/AccountLoginModal-NoPassword.aspx?email=' + email + '&firstName=' + firstName + '&activationId=' + activationId + '&sourceName=' + sourceName + '&sourceLogo=' + sourceLogo,
        success: function(html){
            Facebook.fadeInBackground();
            $(html).modal({
                minHeight: 400,
                minWidth: 400 
            });
        }
   });
   
}
//========================================================
//  Account Login Modal
//========================================================
Facebook.Account_Login = function(task, data1, data2)
{
    $.ajax({
        url: '/controls/ajaxcalls/facebook/AccountLoginModal.aspx?Task=' + task + '&Data1=' + data1 + '&Data2=' + data2,
        success: function(html){
            Facebook.fadeInBackground();
            $(html).modal({
                minHeight: 400,
                minWidth: 400 
            });
            
            // 2011-02-17 MikkoR. Handle focus and blur of input controls in new html 
            ////Facebook.inputChange();
            HandleInputControls();
            AddBlurHandlersToPasswordAndPasswordHintFields();
            FocusToFirstInputInModal();
        }
   });
   
}

//========================================================
//  Homestyle Login Modal
//========================================================
Facebook.Homestyle_Login = function(task, idlisting, idaccount, agentcodestyle, idstyle, stylename) {
    $.ajax({
        url: "/controls/ajaxcalls/facebook/HomestyleLoginModal.aspx?task=" + task + "&idlisting=" + idlisting + "&idaccount=" + idaccount + "&agentcodestyle=" + agentcodestyle + "&idstyle=" + idstyle + "&stylename=" + stylename,
        success: function(html) {
            Facebook.fadeInBackground();
            $(html).modal({
                minHeight: 400,
                minWidth: 400
            });
            // 2011-02-17 MikkoR. Handle focus and blur of input controls in new html 
            ////Facebook.inputChange();
            HandleInputControls();
            AddBlurHandlersToPasswordAndPasswordHintFields();
            FocusToFirstInputInModal();
        }
    });

}

//========================================================
//  Bookmark Account Login Modal
//========================================================
Facebook.Bookmark_Login = function(bookMarkType, Query)
{
     if(bookMarkType == undefined)
     {
         bookMarkType = "";
     }
     if(Query == undefined)
     {
         Query = "";
     }
    
    $.ajax({
        url:'/controls/ajaxcalls/facebook/Bookmark_Login.aspx?bookMarkType=' + bookMarkType + '&' + Query,
        success: function(html){
            Facebook.fadeInBackground();
            $(html).modal({
                minHeight: 400,
                minWidth: 400 
            });
            // 2011-02-17 MikkoR. Handle focus and blur of input controls in new html 
            ////Facebook.inputChange();
            HandleInputControls();
            AddBlurHandlersToPasswordAndPasswordHintFields();
            FocusToFirstInputInModal();
        }
   });
   
}

//========================================================
//  Connect Account Login Modal
//========================================================
Facebook.ConnectAccount_Modal = function()
{
    $.ajax({
        url:'/controls/ajaxcalls/facebook/ConnectAccount_Modal.aspx?Facebook_UserId='+Facebook.GetUserId(),
        success: function(html){
            Facebook.fadeInBackground();
            $(html).modal({
                minHeight: 400,
                minWidth: 400
            });
            // 2011-02-17 MikkoR. Handle focus and blur of input controls in new html 
            ////Facebook.inputChange();
            HandleInputControls();
            AddBlurHandlersToPasswordAndPasswordHintFields();
            FocusToFirstInputInModal();
        }
   });
   
}

//========================================================
//  Bookmark Login Modal
//========================================================
Facebook.Bookmark_Modal = function(bookMarkType, Query)
{  
     if(bookMarkType == undefined)
     {
         bookMarkType = "";
     }
     if(Query == undefined)
     {
         Query = "";
     }
var html = ""
   var fb_user_image = ""
//     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", "pic_square", "profile_url", "email_hashes"],function(result, ex) { 
                
             // var isSessionRunning = FB.getAuthResponse() != null ? true : false;
              
                FB.getLoginStatus(function(response) {
                    if ((response.status) && (response.status == "connected")) {
                      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){                      
                              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>'; 
                                
                                   $.ajax({
                                    url:'/controls/ajaxcalls/facebook/Bookmark_Modal.aspx?Facebook_UserId='+ Facebook.GetUserId() + '&FirstName=' + first_name + '&facebook_avatar=' + fb_user_image + '&bookMarkType=' + bookMarkType + '&' + Query,
                                    success: function(html){ 
                                            Facebook.fadeInBackground();
                                            $(html).modal({
                                                minHeight: 400,
                                                minWidth: 400
                                            });
                                            // 2011-02-17 MikkoR. Handle focus and blur of input controls in new html 
                                            ////Facebook.inputChange();
                                            HandleInputControls();
                                            AddBlurHandlersToPasswordAndPasswordHintFields();
                                            FocusToFirstInputInModal();
                                        }
                                   });
                                        
                             }                                    
                       });    //wait
                   }
               });
   
}

//========================================================
//  Bookmark Login Modal
//========================================================
Facebook.ItemAlert_Modal = function(bNewAlert)
{  
    if(bNewAlert == undefined)
    {
        bNewAlert = true;
    }
    
    $(function() {
        $.ajax({
            type: "POST",
            url: "/controls/AjaxCalls/Facebook/itemalert_modal.aspx?bNewAlert="+bNewAlert,
            data: "",
                success: function(output) {
                Facebook.fadeInBackground();            
                    //Show item alert modal                
                     $(output).modal();
                     
                }
        });
    });         
}

//========================================================
//  Get User ID
//========================================================
Facebook.GetUserId = function()
{
    var FBId = null;
    
    FB.getLoginStatus(function(response) {
        if ((response.status) && (response.status == "connected")) {
            FBId = response.authResponse.userID; 
        }
    });
                   
    return FBId;
}

// 2011-02-21 MikkoR. Not used anywhere
//////========================================================
//////  Get User ID
//////========================================================
////Facebook.GetFirstName = function()
////{
////    var fbookname = ''
////        if(FB.getAuthResponse()) 
////        {
////            var query = FB.Data.query('select first_name from user where uid={0}', FB.getAuthResponse().userID);
////            query.wait(function(result) {   
////            if(result.length > 0){
////                fbookname = result[0].first_name;                              
////             }                                    
////           });      
////        }
////    
////    return fbookname       
////}

//========================================================
//  Share with a Friend
//========================================================

Facebook.ShareFriend = function(sharedURL, shareType, IdListing, thumbnail)
{
   window.clearTimeout(TimeOutModal)
     
        var MemberName = "";
        var MemberEmail = "";
        if(IsAlreadySignedIn() == true)
        {
            MemberName = DisplayName();
            MemberEmail = readUserPersCookie(PERSONCOOKIE_EMAIL);
            
        }
         
        $.ajax({
            url:'/controls/ajaxcalls/facebook/ShareFriend.aspx?sharedurl=' + sharedURL + '&sharetype=' + shareType + '&IdListing=' + IdListing + '&MemberName=' + MemberName + '&MemberEmail=' + MemberEmail + '&MetaDescription=' + $('meta[name=description]').attr("content"),
            success: function(html){
                Facebook.fadeInBackground();            
                $(html).modal();
                // 2011-02-17 MikkoR. Handle focus and blur of input controls in new html 
                ////Facebook.inputChange();
                HandleInputControls();
                FocusToFirstInputInModal();
            }
       });
//   }
//   else{
//   
//        var shortURL = GetShortURL(sharedURL);

//        if(thumbnail == null  || thumbnail == ""){

//              var attachment= {
//                'name': document.title,
//                'href': shortURL,
//                'description': $('meta[name=description]').attr("content")
//                }
//            
//        }
//        else
//        {
//              var attachment= {
//                'name': document.title,
//                'href': shortURL,
//                'description': $('meta[name=description]').attr("content"),
//                'media':
//                    [{'type': 'image',
//                        'src':  thumbnail, 
//                        'href': shortURL}]    
//                }
//        }

//        Facebook.Stream_Publish('', attachment, null, '', '', null, false)            

//   }

}

//========================================================
//  Share with a List
//========================================================

Facebook.ShareList = function(sharedURL, shareType, IdListing, emailOrFBShare)
{
    window.clearTimeout(TimeOutModal)
    var thumbnail = "http://" + staticImgHostname.replace("static.localhost.com", "static-img.frontdoor-dev.gabriels.net") + "/images/fd-facebook-logo.jpg";
    
//    var isSessionRunning = "";
//    FB.ensureInit(function() {
//        FB.Facebook.get_sessionState().waitUntilReady(function(session){    
//            isSessionRunning = session ? true : false;
//        })     
//    })       
    
    if(emailOrFBShare == "emailshare"){
        var MemberName = "";
        var MemberEmail = "";
        if(IsAlreadySignedIn() == true)
        {
            MemberName = DisplayName();
            MemberEmail = readUserPersCookie(PERSONCOOKIE_EMAIL);
            
        }
         
        $.ajax({
            url:'/controls/ajaxcalls/facebook/ShareFriend.aspx?sharedurl=' + escape(sharedURL) + '&sharetype=' + shareType.toLowerCase() + '&IdListing=' + IdListing + '&MemberName=' + MemberName + '&MemberEmail=' + MemberEmail + '&MetaDescription=' +  $('meta[name=description]').attr("content")+ '&Title=' + MemberName + " is looking at list of properties on HGTV\'s FrontDoor.com Real Estate. Tell " + MemberName +" what you think.",
            success: function(html){
                Facebook.fadeInBackground();
                $(html).modal();
                // 2011-02-17 MikkoR. Handle focus and blur of input controls in new html 
                ////Facebook.inputChange();
                HandleInputControls();
                FocusToFirstInputInModal();
            }
       });
   }
   else {
          
        if (FB.getAuthResponse() != null) {
               // get a shortURL for sharedURL before posting to facebook
               var shortURL = GetShortURL(sharedURL);
                         
               var attachment = {
                   'name': first_name + " is looking at list of properties on HGTV's FrontDoor.com Real Estate. Tell " + first_name + " what you think.",
                   'href': shortURL,
                   'description': "HGTV's FrontDoor.com makes it easy for you to share your favorite properties, articles and saved searches. It's social house-hunting made simple.",
                               'media':
                                   [{'type': 'image',
                                   'src':  thumbnail, 
                                       'href': shortURL}]

               }

               Facebook.Stream_Publish('', attachment, null, '', '', null, false)
        }
        else
        {
          FB.login(function(response) {
           if (response.authResponse) {
        
            if (IsAlreadySignedIn()) {
                window.setTimeout(function() {
                    Facebook.Connect(readUserPersCookie(PERSONCOOKIE_EMAIL), readUserPersCookie("pwd"), false);
                }, 2000)
            }
            else {
                //Close to existing modal
                Facebook.Modal_Close();

                //Check if user is connected
                window.setTimeout(function() {
                    LogInConnectedUser();
                }, 2000);
            }

            function LogInConnectedUser() {

                //Publish to stream 
                // Facebook.Show_PermissionDialog_Social_Commenting("publish_stream,email")

                //Is registered user
                $(function() {
                    $.ajax({
                        type: "POST",
                        url: "/controls/AjaxCalls/Facebook/LogInConnectedUser.aspx?Facebook_UserId=" + Facebook.GetUserId(),
                        data: "",
                        success: function(output) {
                            if (rtrim(output) == "success") {
                                ShowLoggedIn(true);
                                document.getElementById("FB_in").style.display = "block";
                                document.getElementById("FD_in").style.display = "none";
                                document.getElementById("FD_FB_out").style.display = "none";

                            }
                        }
                    });
                });

            }

            //========================================================
            //  Private function: Trim of the trailing whitepace
            //========================================================
            function rtrim(stringToTrim) {
                return stringToTrim.substring(0, stringToTrim.length - 2);
            }   
                   
            if(FB.getAuthResponse()) 
            {
                isSessionRunning = true;
                var query = FB.Data.query('select first_name from user where uid={0}', FB.getAuthResponse().userID);
                query.wait(function(result) {  
                  
                    if (result.length > 0) {
                        first_name = result[0].first_name
                       // get a shortURL for sharedURL before posting to facebook
                       var shortURL = GetShortURL(sharedURL);
                                 
                       var attachment = {
                           'name': first_name + " is looking at list of properties on HGTV's FrontDoor.com Real Estate. Tell " + first_name + " what you think.",
                           'href': shortURL,
                           'description': "FrontDoor.com, Listings, Homes for sale, Real Estate, Virtual Tours, social sharing, accounts, Facebook, saved articles, saved searches, saved listings, HGTV, Openhouse.com",
                                       'media':
                                           [{'type': 'image',
                                           'src':  thumbnail, 
                                               'href': shortURL}]

                       }

                       Facebook.Stream_Publish('', attachment, null, '', '', null, false);                

                    }
                }); // wait
            } //getsession
         }
        })
      } // else for fb connect
   }
   
}

//========================================================
//  Share Favorites with a Friend
//========================================================

Facebook.ShareFavoritesFriend = function(sharedURL, shareType, IdListing, title, metadescription, thumbnail, emailOrFBShare)
{
    window.clearTimeout(TimeOutModal)

    if (metadescription == "") {
        metadescription = "HGTV&#39;s FrontDoor.com makes it easy for you to share your favorite properties, articles and saved searches. It&#39;s social house-hunting made simple.";
    }
    
    if (thumbnail == "" || thumbnail == null) {
        var thumbnail = "http://" + staticImgHostname.replace("static.localhost.com", "static-img.frontdoor-dev.gabriels.net") + "/images/fd-facebook-logo.jpg";
    }      
    
    if(emailOrFBShare == "emailshare"){
        var MemberName = "";
        var MemberEmail = "";
        if(IsAlreadySignedIn() == true)
        {
            MemberName = DisplayName();
            MemberEmail = readUserPersCookie(PERSONCOOKIE_EMAIL);
            
        }
         
        $.ajax({
            url:'/controls/ajaxcalls/facebook/ShareFriend.aspx?sharedurl=' + sharedURL + '&sharetype=' + shareType + '&IdListing=' + IdListing + '&MemberName=' + MemberName + '&MemberEmail=' + MemberEmail + '&Title=' + escape(title) + '&MetaDescription=' + metadescription,
            success: function(html){
                Facebook.fadeInBackground();
                $(html).modal();
                // 2011-02-17 MikkoR. Handle focus and blur of input controls in new html 
                ////Facebook.inputChange();
                HandleInputControls();
                FocusToFirstInputInModal();
            }
       });
   }
   else {
        if (FB.getAuthResponse() != null) {
               // get a shortURL for sharedURL before posting to facebook
               var shortURL = GetShortURL(sharedURL);

               if(thumbnail == null || thumbnail == ""){
                   var attachment = {
                       'name': title,
                       'href': shortURL,
                       'description': metadescription
                   }
                   
               }
               else
               {               
                    var attachment = {
                           'name': title,
                           'href': shortURL,
                           'description': metadescription,
                                    'media':
                                         [{'type': 'image',
                                           'src':  thumbnail, 
                                            'href': shortURL}]
                       }
               }                      

               Facebook.Stream_Publish('', attachment, null, '', '', null, false)
        }
        else
        {
            
          FB.login(function(response) {
           if (response.authResponse) {
            if (IsAlreadySignedIn()) {
                window.setTimeout(function() {
                    Facebook.Connect(readUserPersCookie(PERSONCOOKIE_EMAIL), readUserPersCookie("pwd"), false);
                }, 2000)
            }
            else {
                //Close to existing modal
                Facebook.Modal_Close();

                //Check if user is connected
                window.setTimeout(function() {
                    LogInConnectedUser();
                }, 2000);
            }

            function LogInConnectedUser() {

                //Publish to stream 
                // Facebook.Show_PermissionDialog_Social_Commenting("publish_stream,email")

                //Is registered user
                $(function() {
                    $.ajax({
                        type: "POST",
                        url: "/controls/AjaxCalls/Facebook/LogInConnectedUser.aspx?Facebook_UserId=" + Facebook.GetUserId(),
                        data: "",
                        success: function(output) {
                            if (rtrim(output) == "success") {
                                ShowLoggedIn(true);
                                document.getElementById("FB_in").style.display = "block";
                                document.getElementById("FD_in").style.display = "none";
                                document.getElementById("FD_FB_out").style.display = "none";

                            }
                        }
                    });
                });

            }

            //========================================================
            //  Private function: Trim of the trailing whitepace
            //========================================================
            function rtrim(stringToTrim) {
                return stringToTrim.substring(0, stringToTrim.length - 2);
            }

            // get a shortURL for sharedURL before posting to facebook
            var shortURL = GetShortURL(sharedURL);

            if(thumbnail == null || thumbnail == ""){
                   var attachment = {
                               'name': title,
                               'href': shortURL,
                               'description': metadescription
                           }                           
             }
             else
             {               
                   var attachment = {
                                   'name': title,
                                   'href': shortURL,
                                   'description': metadescription,
                                            'media':
                                                 [{'type': 'image',
                                                   'src':  thumbnail, 
                                                    'href': shortURL}]
                               }
              }                      

              Facebook.Stream_Publish('', attachment, null, '', '', null, false)
                }
            });
    } // else for fb connect

   }// else for fb share


}   

//========================================================
//  Share properties with an agent
//========================================================

Facebook.SharePropertiesAgent = function()
{ 
    $.ajax({
        url:'/controls/ajaxcalls/facebook/SharePropertiesAgentModal.aspx',
        success: function(html){
            Facebook.fadeInBackground();
            $(html).modal();
        }
   });

}

//========================================================
//  Share agent info
//========================================================

Facebook.ShareAgentInfo = function(Name, Email, AccountID, DefaultInfo)
{ 
    if (DefaultInfo == 'undefined')
    {
        DefaultInfo = "Y";
    }
    
    $.ajax({
        url:'/controls/ajaxcalls/facebook/ShareAgentInfoModal.aspx?AgentName=' + Name + '&AgentEmail=' + Email + '&AccountId=' + AccountID + '&DefaultInfo=' + DefaultInfo,
        success: function(html){
            Facebook.fadeInBackground();
            $(html).modal();
        }
   });

}

// 2011-02-21 MikkoR. Not used anywhere
//////========================================================
//////  Share property
//////========================================================
////Facebook.ShareProperty = function(ArticleImage, PageTitle, MetaDescription, sharedURL) {

////    // get a shortURL for sharedURL before posting to facebook
////    var shortURL = GetShortURL(sharedURL);
////    var thumbnail = "http://frontdoor.com/images/fd-facebook-logo.jpg";
////    
////    var name = "";

////    if (FB.getAuthResponse() != null) {

////        name = first_name;
////        if (ArticleImage != "") {
////            var attachment = {
////                'name': name + " is looking at " + PageTitle + " Tell " + name + " what you think",
////                'href': shortURL,
////                'description': $('meta[name=description]').attr("content"),
////                'media':
////                    [{ 'type': 'image',
////                        'src': ArticleImage,
////                        'href': shortURL}]

////            }
////            Facebook.Stream_Publish('', attachment, null, '', '', null, false)
////        }
////        else {
////            var attachment = {
////                'name': name + " is looking at " + PageTitle + " Tell " + name + " what you think",
////                'href': shortURL,
////                'description': $('meta[name=description]').attr("content"),
////                'media':
////                [{ 'type': 'image',
////                    'src': thumbnail,
////                    'href': shortURL}]

////            }
////            Facebook.Stream_Publish('', attachment, null, '', '', null, false)
////        }

////    }
////    else {
////        FB.login(function(response) {
////          if(response.authResponse) {
////            
////       // FB.Connect.requireSession(function() {
////            if (IsAlreadySignedIn()) {
////                window.setTimeout(function() {
////                    Facebook.Connect(readUserPersCookie(PERSONCOOKIE_EMAIL), readUserPersCookie("pwd"), false);
////                }, 2000)
////            }
////            else {
////                //Close to existing modal
////                Facebook.Modal_Close();

////                //Check if user is connected
////                window.setTimeout(function() {
////                    LogInConnectedUser();
////                }, 2000);
////            }

////            function LogInConnectedUser() {

////                //Publish to stream 
////                // Facebook.Show_PermissionDialog_Social_Commenting("publish_stream,email")

////                //Is registered user
////                $(function() {
////                    $.ajax({
////                        type: "POST",
////                        url: "/controls/AjaxCalls/Facebook/LogInConnectedUser.aspx?Facebook_UserId=" + Facebook.GetUserId(),
////                        data: "",
////                        success: function(output) {
////                            if (rtrim(output) == "success") {
////                                document.getElementById("FB_in").style.display = "block";
////                                if (readUserPersCookie(PERSONCOOKIE_USERTYPE) == 2) {
////                                  gE("my_fb").href = "/pro/account/dashboard";
////                                }
////                                else {
////                                  gE("my_fb").href = "/account/recent-activity/";
////                                }
////                                document.getElementById("FD_in").style.display = "none";
////                                document.getElementById("FD_FB_out").style.display = "none";

////                            }
////                        }
////                    });
////                });

////            }

////            //========================================================
////            //  Private function: Trim of the trailing whitepace
////            //========================================================
////            function rtrim(stringToTrim) {
////                return stringToTrim.substring(0, stringToTrim.length - 2);
////            }

////           // FB.Facebook.get_sessionState().waitUntilReady(function(session) {
////            if(FB.getAuthResponse()) 
////            {
////                isSessionRunning = true;
////                var query = FB.Data.query('select first_name from user where uid={0}', FB.getAuthResponse().userID);
////                query.wait(function(result) {  

////                    if (result.length > 0) {
////                        name = result[0].first_name
////                        if (ArticleImage != "") {
////                            var attachment = {
////                                'name': name + " is looking at " + PageTitle + " Tell " + name + " what you think",
////                                'href': shortURL,
////                                'description': $('meta[name=description]').attr("content"),
////                                'media':
////                            [{ 'type': 'image',
////                                'src': ArticleImage,
////                                'href': shortURL}]

////                            }
////                            Facebook.Stream_Publish('', attachment, null, '', '', null, false);
////                        }
////                        else {
////                            var attachment = {
////                                'name': name + " is looking at " + PageTitle + " Tell " + name + " what you think",
////                                'href': shortURL,
////                                'description': $('meta[name=description]').attr("content"),
////                                'media':
////                                [{ 'type': 'image',
////                                    'src': thumbnail,
////                                    'href': shortURL}]
////                            }
////                            Facebook.Stream_Publish('', attachment, null, '', '', null, false);
////                        }

////                    }
////                }); // wait
////            } // getsession
////          }
////        })
////    }
////    //fbs_click(url, title)

////    //},5000) 

////}


//========================================================
//  Share article
//========================================================
Facebook.ShareArticle = function(sharedURL, shareType, IdListing)
{   

    // get a shortURL for sharedURL before posting to facebook
    var shortURL = GetShortURL(sharedURL);
    var thumbnail = "http://" + staticImgHostname.replace("static.localhost.com", "static-img.frontdoor-dev.gabriels.net") + "/images/fd-facebook-logo.jpg";
    
    var name = "";

    if(FB.getAuthResponse() != null)
    {       
      
          
          var attachment= {
            'name': document.title,
            'href': shortURL,
            'description': $('meta[name=description]').attr("content"),
            'media':
            [{ 'type': 'image',
                'src': thumbnail,
                'href': shortURL}]
        }
        
        Facebook.Stream_Publish('', attachment, null, '', '', null, false)
                      
     }
     else
    {
        FB.login(function(response) {
          if(response.authResponse) {   
       // FB.Connect.requireSession(function(){
            if(IsAlreadySignedIn())
            {
                 window.setTimeout(function(){
                    Facebook.Connect(readUserPersCookie(PERSONCOOKIE_EMAIL), readUserPersCookie("pwd"), false);
                },2000)
            }    
            else{
                //Close to existing modal
                Facebook.Modal_Close();
                
                //Check if user is connected
                window.setTimeout(function(){
                    LogInConnectedUser();
                    },2000);  
            }
                
            function LogInConnectedUser()
            {
        
                //Publish to stream 
               // Facebook.Show_PermissionDialog_Social_Commenting("publish_stream,email")

                //Is registered user
                $(function() {
                        $.ajax({
                        type: "POST",
                        url: "/controls/AjaxCalls/Facebook/LogInConnectedUser.aspx?Facebook_UserId=" + Facebook.GetUserId(),
                        data: "",
                            success: function(output) {
                                if(rtrim(output) == "success")
                                {
                                    ShowLoggedIn(true);
                                    document.getElementById("FB_in").style.display = "block";
                                    document.getElementById("FD_in").style.display = "none";
                                    document.getElementById("FD_FB_out").style.display = "none"; 
                              
                                }
                        }
                    });
               });
                
            }
                
             //========================================================
            //  Private function: Trim of the trailing whitepace
            //========================================================
            function rtrim(stringToTrim) {
                return stringToTrim.substring(0,stringToTrim.length-2);
            }       

            if(FB.getAuthResponse()) 
            {
                isSessionRunning = true;
                var query = FB.Data.query('select first_name from user where uid={0}', FB.getAuthResponse().userID);
                query.wait(function(result) {  
                    if(result.length > 0){                        
                       
                        
                          var attachment= {
                            'name': document.title,
                            'href': shortURL,
                            'description': $('meta[name=description]').attr("content"),
                            'media':
                            [{ 'type': 'image',
                                'src': thumbnail,
                                'href': shortURL}]
                        }
                        
                        Facebook.Stream_Publish('', attachment, null, '', '', null, false)
                                  
                    }                                    
                });    //wait
            }       // getsession
          }                                                      
        }) //login
    }
                  //fbs_click(url, title)

   //},5000)         

}

//========================================================
//  Share Search Results
//========================================================

Facebook.ShareSearch = function(CityName, SEOSection)
{
    if (SEOSection == undefined)
    {
        SEOSection = 'for_sale';
    }
     $.ajax({
            url:'/controls/ajaxcalls/facebook/ShareSearchModal.aspx?CityName=' + CityName + '&SEOSection=' + SEOSection,
            success: function(html){
                Facebook.fadeInBackground();
                $(html).modal();
                // 2011-02-17 MikkoR. Handle focus and blur of input controls in new html 
                ////Facebook.inputChange();
                HandleInputControls();
                FocusToFirstInputInModal();
            }
       });
}

Facebook.MaxLimit = function()
{
     $.ajax({
            url:'/controls/ajaxcalls/facebook/MaxNumberSavedModal.aspx',
            success: function(html){
                Facebook.fadeInBackground();
                $(html).modal();
            }
       });
}

Facebook.ClaimListingSaveNoPhotos = function()
{
     $.ajax({
            url:'/controls/ajaxcalls/facebook/ClaimListingsNoPhotos.aspx',
            success: function(html){
                Facebook.fadeInBackground();
                $(html).modal();
            }
     });
}

//========================================================
//  Send email to a friend
//========================================================
Facebook.SendEmail = function(To, From, Message, Subject, DisplayName, IdListing, shareType, sharedURL)
{ 
    var TmpShareType = shareType;
    var isValidInfo = false;
    if(shareType.toLowerCase() == "contactagent")
    {
        isValidInfo = validateContactForm();
    }
    else if(shareType.toLowerCase() == "contactprofiledagent")
    {
        if(gE("yourname"))
        {
            isValidInfo = validateForm();
        }
        else
        {
            isValidInfo = validateContactForm();
        }
    }
    else
    {
        isValidInfo = validateForm();
    }
    
    // temporary fix for agent share emails.
    if(shareType.toLowerCase() == "agentshare")
    {
        IdListing = "123171-QC4118262";
    }
    if(isValidInfo){
         
        var strURL = '/controls/ajaxcalls/facebook/SendEmail.aspx?to='+ To + "&from=" + From + "&message=" + escape(Message) + "&subject=" + Subject + "&displayname=" + DisplayName + '&IdListing=' + IdListing + '&sharetype=' + TmpShareType + '&sharedURL=' + sharedURL;
        
        if(gE("yourphone"))
        {
          if(gE("yourphone").value != "Enter your Phone Number")
          {
             strURL += "&phone=" + gE("yourphone").value;
          }
        }
        $.ajax({
            url:strURL,
            success: function(html){
                if (document.forms["detail-contact-form"]) {
                    document.forms["detail-contact-form"].reset();
                }
                $("#contactform_name_in").removeClass("focusField");
                $("#contactform_name_in").addClass("idleField");
                $("#contactform_email_in").removeClass("focusField");
                $("#contactform_email_in").addClass("idleField");
                $("#yourphone").removeClass("focusField");
                $("#yourphone").addClass("idleField");
                //$("#contactform_msg_in").removeClass("focusField");
                //$("#contactform_msg_in").addClass("idleField");
       
                 Facebook.Modal_Close()
                 
                 var confirmation = ""
                 if(shareType.toLowerCase() == "listing")
                 {
                    confirmation = "Your property has been shared!";
                 }
                 else if(shareType.toLowerCase() == "search")
                 {
                    confirmation = "Your search has been shared!";
                 }
                 else if(shareType.toLowerCase().indexOf("article") > -1)
                 {
                    confirmation = "Your article has been shared!";
                 }
                 else if(shareType.toLowerCase() == "list")
                 {
                    confirmation = "Your list has been shared!"
                 }               
                 else if(shareType.toLowerCase() == "agentshare")
                 {
                    confirmation = "Your properties have been shared!"
                 }               
                 else if(shareType.toLowerCase() == "contactagent" || shareType.toLowerCase() == "contactprofiledagent")
                 {
                    confirmation = "Your message has been sent."
                 }  
                 
                 Facebook.Confirmation_Modal(confirmation);
                    
                    
                 TimeOutModal = window.setTimeout(function(){
                    Facebook.Modal_Close();
                    Facebook.fadeOutBackground();    
                },3000);
            }
        })    
           
    }   
    
    function validateContactForm()
    {
        var isValid = true;
        if(document.getElementById("contactform_name_in").value == "")
        {
            $("#contactform_name_in").addClass("contactform-error");
            document.getElementById("contactform_name_error").innerHTML = "Please enter your name.";
            document.getElementById("contactform_name_error").style.display = "block";
            
            isValid = false
        }
        else
        {
            document.getElementById("contactform_name_error").style.display = "none";
            $("#contactform_name_in").removeClass("contactform-error");
        }
        
        if(document.getElementById("contactform_email_in").value == "")
        {
           $("#contactform_email_in").addClass("contactform-error");
           document.getElementById("contactform_email_error").innerHTML = "Please enter your e-mail address.";
           document.getElementById("contactform_email_error").style.display = "block";          
            
            isValid = false
        }
        else
        {        
            if(validateEmail("contactform_email_in") == false)
            {
                $("#contactform_email_in").addClass("contactform-error");
                document.getElementById("contactform_email_error").innerHTML = "Please check the format of your e-mail address and re-enter. (i.e. joe@frontdoor.com).";
                document.getElementById("contactform_email_error").style.display = "block";
                
                isValid = false
            }
            else
            {
                document.getElementById("contactform_email_error").style.display = "none";    
                $("#contactform_email_in").removeClass("contactform-error");   
            }
        }
        return isValid;
    }
  
    function validateForm()
    {
        if(document.getElementById("yourname").value == "")
        {
            $("#modal").addClass("modal-error"); 
            $("#yournameInput").addClass("input-error");
            document.getElementById("sender_name_error").innerHTML = "Please enter your name.";
            document.getElementById("sender_name_error").style.display = "block";
            
            return false
        }
        else if(document.getElementById("youremail").value == "")
        {
            $("#modal").addClass("modal-error"); 
            $("#youremailInput").addClass("input-error");
           document.getElementById("sender_email_error").innerHTML = "Please enter your e-mail address.";
           document.getElementById("sender_email_error").style.display = "block";
           //document.getElementById("section").className = "section error_bg"
           //document.getElementById("bottom").className = "bottom error_bg"
           
            
            return false
        }
        else if(validateEmail("youremail") == false)
        {
            $("#modal").addClass("modal-error"); 
            $("#youremailInput").addClass("input-error");
            document.getElementById("sender_email_error").innerHTML = "Please check the format of your e-mail address and re-enter. (i.e. joe@frontdoor.com).";
            document.getElementById("sender_email_error").style.display = "block";
            
            return false
        }
        
        if(gE("Recipient"))
        {
           if(document.getElementById("Recipient").value == "")
            {
                $("#modal").addClass("modal-error"); 
                $("#recipientInput").addClass("input-error");
                document.getElementById("recipient_error").innerHTML = "Please enter an e-mail addresses.";
                document.getElementById("recipient_error").style.display = "block";
                
                return false
            }
            else if(validateEmail("Recipient") == false)
            {
                 $("#modal").addClass("modal-error"); 
                 $("#recipientInput").addClass("input-error");
                 document.getElementById("recipient_error").innerHTML = "Oops! Please enter a valid e-mail address. Separate multiple addresses with comma";
                 document.getElementById("recipient_error").style.display = "block";
                return false
            }
        }
        
        if(gE("broker_check"))
        {
          if(gE("broker_check").checked == false)
          {
                 $("#modal").addClass("modal-error"); 
                // $("#broker_checkbox").addClass("input-error");
                 document.getElementById("agree_error").innerHTML = "Oops! Please agree the license";
                 document.getElementById("agree_error").style.display = "block";
                return false;        
          }    
        }
        return true
        
    }
    
    function validateEmail(fieldName){ 
        var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        var str = document.getElementById(fieldName).value;
        str = str.replace(/ /gi,""); 
        validateFlag = true
        for(var i = 0; i< str.split(",").length; i++)
        {   
            if(!str.split(",")[i].match(emailRegEx))
            {
                validateFlag = false;
            }
        }
        
        return validateFlag
        
    }
    
    String.prototype.trim = function() {
    a = this.replace(/^\s+/, '');
    return a.replace(/\s+$/, '');
    }

}



//========================================================
//  Close Modals
//========================================================
Facebook.Modal_Close = function()
{
    $.modal.close();
    if(TimeOutModal)
    { 
        window.clearTimeout(TimeOutModal);
    }   
}

//========================================================
//  Get password
//========================================================
Facebook.GetPassword = function()
{
    if(gE("Email_Add").value != "" && gE("Email_Add").value == "Enter your valid email address"){
        gE("pwdFormatErrLogin").style.display = "block"
        gE("pwdFormatErrLogin").innerHTML = "Please enter email address"
        $("#modal").addClass("modal-error"); 
        $("#email_input").addClass("input-error");
        
        return false
    } 
    if(validateEmailForgot(gE("Email_Add").value) == false)
    {   
         gE("pwdFormatErrLogin").innerHTML = "Please check the format of your e-mail address and re-enter. (i.e. joe@frontdoor.com)."   
         gE("pwdFormatErrLogin").style.display = "block";
        $("#modal").addClass("modal-error"); 
        $("#email_input").addClass("input-error");
        return false
    }           
   
    var querystring = "email=" + gE("Email_Add").value + "&action=forgot_password"; // to differentiate between signin, signup and forgot password actions in Personalization.aspx page.   
    $AJAX.GetForDelegate(forgotpasswordResultDelegate, PersonalizationRoot + "AjaxCalls/Personalization.aspx?" + querystring);

  function  forgotpasswordResultDelegate(AjaxResponse)
  { 
    if(AjaxResponse == "success"){
        Facebook.Modal_Close()
        Facebook.Confirmation_Modal("Your password was just sent to your e-mail address.");
    }
    else
    {
        gE("pwdFormatErrLogin").style.display = "block";
        gE("pwdFormatErrLogin").innerHTML = AjaxResponse
        $("#modal").addClass("modal-error"); 
        $("#email_input").addClass("input-error");
    }
  }
  
   //========================================================
            //  Private function: Validate email
            //========================================================
             function validateEmailForgot(emailTxt){
                var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
                str = emailTxt;
                str = str.replace(/ /gi,""); 
                validateFlag = true
                for(var i = 0; i< str.split(",").length; i++)
                {   
                    if(!str.split(",")[i].match(emailRegEx))
                    {
                        validateFlag = false;
                    }
                }
                
               
                return validateFlag
        
            }
}

//========================================================
//  Get password
//========================================================
Facebook.AccountActivation = function(email, password)
{

   
          
         $.ajax({
            url:"/controls/ajaxcalls/facebook/AccountActivation.aspx?email=" + email + "&password=" + password,
            success: function(html){
                Facebook.Confirmation_Modal("Account activation e-mail sent.");
                    
                window.setTimeout(function(){
                    Facebook.Modal_Close();
                },5000); 
            }
        })    
        
//     var strURL = "/controls/ajaxcalls/facebook/AccountActivation.aspx?email=" + email + "&password=" + password;
//     $AJAX.GetForDelegate(ActivationDelegate, strURL);
//     
//     function ActivationDelegate(AjaxResponse)
//     {
//     
//        Facebook.Confirmation_Modal("Account activation e-mail sent.");
//                
//        window.setTimeout(function(){
//                Facebook.Modal_Close();
//                },5000); 
//                
//     }
}

var GL_overlayDiv;

Facebook.fadeInBackground = function(){
    if(!GL_overlayDiv){
        GL_overlayDiv = document.createElement('div');
    }
    GL_overlayDiv.id = "modalOverlayDiv";
    $('#global_wrap').append(GL_overlayDiv);
    $('#modalOverlayDiv').css('height', $("body").height());
    $(GL_overlayDiv).fadeTo(250, .3);
    $(document).keydown(Facebook.handleEscape);	
    $(GL_overlayDiv).click( function(){
        Facebook.Modal_Close(); 
        Facebook.fadeOutBackground();
    })
}

Facebook.fadeOutBackground = function(){
    if(GL_overlayDiv) {
        $(GL_overlayDiv).fadeTo(250, .0) 
        $('#modalOverlayDiv').css('height', '0px')    
    setTimeout(function(){
        //document.getElementById('global_wrap').removeChild(GL_overlayDiv);
        if (GL_overlayDiv && GL_overlayDiv.parentNode !=null) {
            GL_overlayDiv.parentNode.removeChild(GL_overlayDiv);   
        } 
    }, 251);
  }
}

Facebook.handleEscape = function(e) {
    if (e.keyCode == 27) {
        document.getElementById('global_wrap').removeChild(GL_overlayDiv);    
        $('#modalOverlayDiv').css('height', '0px') 
    }
}

Facebook.loginHeaderWidth = function(){
    var $loginLinks = $('.login-links');
    var $loginWrapperBg = $('.log_in_wrapper_bg');
    
    $loginLinks.each(function(index){
        //alert($(this).width());    
        $loginWrapperBg.eq(index).css("width", ($(this).width()+65)+"px");
    });
    
}

//========================================================
//  Get short URL from original lURL
//========================================================

function GetShortURL(sharedURL) {
    var shortURL = $.ajax({
        url: '/controls/AjaxCalls/Facebook/ShortURLFB.aspx?sharedurl=' + encodeURIComponent(sharedURL),
        async: false
    }).responseText;

    return shortURL;
}


//========================================================
//  Facebook Share
//========================================================

function fbs_click(sharedURL, title) {

    if (typeof sharedURL == 'undefined' ) {
        sharedURL = document.CanonicalURL() + document.FacebookTrackingParam();
    }

    if (typeof title == 'undefined' ) {
        title = document.title;
    }
    
    // get a shortURL for sharedURL before posting to facebook
    var shortURL = GetShortURL(sharedURL);
    
    window.open("http://www.facebook.com/sharer.php?u="+shortURL+"&t="+ title,"sharer","toolbar=0,status=0,width=626,height=436");
    return false;
} 

//========================================================
//  Display Facebook Status Control
//========================================================
              
function ShowFacebookStatusDialog(containerID, defaultText, sharedURL)
{
    var parentContainer = document.getElementById(containerID);
    var statusWrap = document.getElementById("status-wrap");
    var statusWrapConnect = document.getElementById("status-wrap-connect");
    
    // In case of article pages, the function receives a single parameter, 
    // the containerId of the control that will host the Facebook Status Control
    
    //In case of package article pages, we can overwrite the default status text
    if (parentContainer != null && statusWrap != null && statusWrapConnect != null)
    {
        if( document.getElementById('ctl00_FacebookStatusDialog1_status_message') != null)
        {
            if (sharedURL == null) {
                sharedURL = document.CanonicalURL() + document.FacebookTrackingParam();
            }
            
            // get a shortURL for sharedURL before posting to facebook
            var shortURL = GetShortURL(sharedURL);
            
            if (defaultText != null)
            {
                // replace the whole text
                document.getElementById('ctl00_FacebookStatusDialog1_status_message').innerHTML = defaultText + shortURL;
            }
            else
            {
                //only append the shortURL
                document.getElementById('ctl00_FacebookStatusDialog1_status_message').innerHTML += shortURL;
            }
        }
        
        parentContainer.appendChild(statusWrap);
        parentContainer.appendChild(statusWrapConnect);
    }
}
 
 //========================================================
//  BM Properties What's This Modal
//========================================================
Facebook.WhatsThis = function()
{
    $.ajax({
        url:'/controls/ajaxcalls/facebook/WhatsThisModal.aspx',
        success: function(html){
            Facebook.fadeInBackground();
            $(html).modal({
                minHeight: 400,
                minWidth: 400 
            });
        }
   });


}

//========================================================
//  What's This Modal Message
//========================================================
Facebook.WhatsThisMessage = function(message, onCloseDelegate) {
    $.ajax({
        url: '/controls/ajaxcalls/facebook/WhatsThisModalMessage.aspx?Message=' + message,
        success: function(html) {
            Facebook.fadeInBackground();
            $(html).modal({
                minHeight: 400,
                minWidth: 400,
                onClose: function() {
                    if (typeof (onCloseDelegate) != "undefined") {
                        onCloseDelegate();
                    }
                }
            });
        }
    });

}   

//========================================================
//  BM Properties - View as a list
//========================================================
Facebook.ViewAsList = function()
{
    if(!IsAlreadySignedIn())
    {
        if(FB.getAuthResponse() == null)
        {    
            Facebook.Bookmark_Login("properties_module", 'page=' + GetPageName()); 
        }
        else
        {
            Facebook.Bookmark_Modal("properties_module", 'page=' + GetPageName());
        }   
    }
    else
    {
        window.location.href = WebRoot + "account/my-folders/";
    }
}  

//========================================================
//  BM Properties - Share
//========================================================
Facebook.BMShareLogin = function(ShareType)
{
    if(!IsAlreadySignedIn())
    {
        if(FB.getAuthResponse() == null)
        {    
            Facebook.Bookmark_Login("share_module", 'page=' + GetPageName() + '&shrtype=' + ShareType); 
        }
        else
        {
            Facebook.Bookmark_Modal("share_module", 'page=' + GetPageName() + '&shrtype=' + ShareType);
        }   
    }
    else
    {
        ShareAllListings(ShareType);
    }
}  

//========================================================
//  BM Properties Clear All Properties Modal
//========================================================
Facebook.ClearAllProperties = function()
{
    $.ajax({
        url:'/controls/ajaxcalls/facebook/ClearPropertiesModal.aspx',
        success: function(html){
            Facebook.fadeInBackground();
            $(html).modal({
                minHeight: 400,
                minWidth: 400 
            });
            
//            window.setTimeout(function(){
//                        Facebook.Modal_Close();
//                        Facebook.fadeOutBackground();
//                      }, 
//                5000);
        }
   });
   
}  

// 2011-02-21 MikkoR. Not used anywhere
//////========================================================
//////  BM Properties Share Properties Broker Modal
//////========================================================
////Facebook.SharePropertiesBrokerModal = function(email)
////{
////      if(email != "")
////      {
////        $.ajax({
////            url:'/controls/ajaxcalls/facebook/SharePropertiesBrokerModal.aspx?email=' + email,
////            success: function(html){
////                Facebook.fadeInBackground();
////                $(html).modal({
////                    minHeight: 400,
////                    minWidth: 400 
////                });
////            }
////        });
////      }
////   
////}    

//========================================================
//  Agent Share Badge Modal
//========================================================
Facebook.BadgeShare_Modal = function(url, fbtitle, fbmessage, fbimage, twmessage) {
    $.ajax({
        url: "/controls/AjaxCalls/Facebook/badgeshare-modal.aspx?url="+UrlEncode(url) +"&fbtitle=" + fbtitle + "&fbmessage=" + fbmessage + "&fbimage=" + UrlEncode(fbimage) + "&twmessage=" + twmessage,
        success: function(html) {
            Facebook.fadeInBackground();   
                     
            $(html).modal({
                minHeight: 400,
                minWidth: 400 
            });
                 
        }
    });
}

//========================================================
//  BM Properties Share Properties Agent Modal
//========================================================
Facebook.SharePropertiesAgentModal = function(email, name)
{
   if(email != "")
   {
//        if(!IsAlreadySignedIn())
//        {
//            if(FB.getAuthResponse() == null)
//            {    
//                Facebook.Bookmark_Login("zone_module", 'page=' + GetPageName() + '&email=' + email + '&name=' + name); 
//            }
//            else
//            {
//                Facebook.Bookmark_Modal("zone_module", 'page=' + GetPageName() + '&email=' + email + '&name=' + name);
//            }   
//        }
//        else
        {
	        try {
	            $.ajax({
	                url: '/controls/ajaxcalls/accounts/ShareAllListings.aspx',
	                type: 'GET',
	                dataType: 'text',
	                success: function(data) {	
	                    
                        MemberName = DisplayName();
                        MemberEmail = readUserPersCookie(PERSONCOOKIE_EMAIL);
                        
                        $.ajax({
                           url:'/controls/ajaxcalls/facebook/SharePropertiesAgentModal.aspx?sharedurl=' + escape(data) + '&AgentEmail=' + email+ '&AgentName=' + name + '&MemberName=' + MemberName + '&MemberEmail=' + MemberEmail,
                           success: function(html){
                                Facebook.fadeInBackground();
                                $(html).modal({
                                    minHeight: 400,
                                    minWidth: 400 
                                });
                           }
                       });
	                },
	                error: function(XMLHttpRequest, textStatus, errorThrown) {
	                    alert('error this:' + this + '\n XMLHttpRequest:' + XMLHttpRequest + '\ntextStatus:' + textStatus);
	                }
	            });
            }
            catch (e) {
                alert('error:' + e);
            }
            
         }
   }
   
}       
      
//

Facebook.CompleteTempCAction = function(output)
{ 
               if(output.indexOf("lastaction_bmpshare") > -1) // Signed in but still sharing all listings is pending.
               {    
                    RemoveCookie("TempC");                
                    ShowLoggedIn(true);
                    var ShareType = 'emailshare';
                    var Arr = output.split("::");
                    if(Arr.length > 1)
                    {
                        ShareType = Arr[1];
                    }
                    if(SignInOrRegister == "SignIn")
                    {
                      // If user is logged into facebook already share with facebook if not share with email.
                        FB.getLoginStatus(function(response) {
                            if ((response.status) && (response.status == "connected")) {
                           // ShareType = 'fbshare';
                                Facebook.Connect(readUserPersCookie(PERSONCOOKIE_EMAIL), readUserPersCookie("pwd"), false);
                            }
                            
                        });
                        Facebook.Modal_Close();
                        window.setTimeout(function(){ 
                            Facebook.fadeOutBackground();
                            ShareAllListings(ShareType);
                        ChangeUserAction();
                        },2000);    
                        
                    }
               }
               else if(output.indexOf("lastaction_bmpagentshare") > -1) 
               // Signed in but still sharing all listings is pending.
               {   
                    RemoveCookie("TempC");                 
                    ShowLoggedIn(true);
                    var Arr = output.split("::");
                    var TmpAgentName = Arr[1];
                    var TmpAgentEmail = Arr[2];
                    
                  //  RemoveCookie("TempC");
                    if(SignInOrRegister == "SignIn")
                    {
                      // If user is logged into facebook already share with facebook if not share with email.
                        FB.getLoginStatus(function(response) {
                            if ((response.status) && (response.status == "connected")) {
                                Facebook.Connect(readUserPersCookie(PERSONCOOKIE_EMAIL), readUserPersCookie("pwd"), false);
                            }
                        });
                        Facebook.Modal_Close();
                        window.setTimeout(function(){ 
                            Facebook.fadeOutBackground();                    
                            ChangeUserAction();
                            Facebook.SharePropertiesAgentModal(TmpAgentEmail, TmpAgentName);
                        },2000);    
                        
                    }
               }
               else if(output == "lastaction_bmpviewlist") // Signed in but still View as List action is pending.
               {    
                    RemoveCookie("TempC");                
                    ShowLoggedIn(true);
                    var ShareType = 'emailshare';
                    if(SignInOrRegister == "SignIn")
                    {
                      // If user is logged into facebook already share with facebook if not share with email.
                        FB.getLoginStatus(function(response) {
                            if ((response.status) && (response.status == "connected")) {
                                ShareType = 'fbshare';
                                Facebook.Connect(readUserPersCookie(PERSONCOOKIE_EMAIL), readUserPersCookie("pwd"), false);
                            }
                        });
                        Facebook.Modal_Close();      
                        window.setTimeout(function(){ 
                            window.location.href = WebRoot + "account/my-folders/";
                        },2000);    
                        
                    }
               }    
               else if(output == "lastaction_additem") // Signed in but still add listing action is pending.
               {
                    if (typeof BookmarkModuleSaveListing == 'function')
                    {
                        if (typeof ChangeUserAction == 'function') 
                        {
                            ChangeUserAction();
                        }
                        BookmarkModuleSaveListing();
                    }
                    if(readTempCookie("type") == "Article")
                    {
                       RemoveCookie("TempC");          
                       SaveItem();
                    }

               }
               else if(output.indexOf("lastaction_showitemalertdialog") > -1) // Signed in but want to see the item alert dialog.
               {                    
                    ShowLoggedIn(true);

                    if(SignInOrRegister == "SignIn")
                    {
                      // If user is logged into facebook already share with facebook if not share with email.
                        FB.getLoginStatus(function(response) {
                            if ((response.status) && (response.status == "connected")) {
                           // ShareType = 'fbshare';
                                Facebook.Connect(readUserPersCookie(PERSONCOOKIE_EMAIL), readUserPersCookie("pwd"), false);
                            }
                        });
                        Facebook.Modal_Close();
                        ChangeUserAction();
                        window.setTimeout(function(){ 
                            Facebook.Modal_Close();
                            Facebook.fadeOutBackground();
                            Facebook.ItemAlert_Modal((getAlertListingId(alertIdListing) == -1));
                        },2000);    
                        
                    }
               }
               else if(output == "success")
                    { 
                        RemoveCookie("TempC");  
                        ChangeUserAction();
                        document.getElementById("FB_in").style.display = "block";
                        if (readUserPersCookie(PERSONCOOKIE_USERTYPE) == 2) {
                            gE("my_fb").href = "/pro/account/dashboard";
                           // window.location.href = "/pro/account/dashboard";
                        }
                        else {
                            gE("my_fb").href = "/account/recent-activity/";
                           // window.location.href = "/account/recent-activity/";
                        }
                        document.getElementById("FD_in").style.display = "none";
                        document.getElementById("FD_FB_out").style.display = "none";    
                    }
}

// 2011-02-17 MikkoR. Replaced by AddBlurHandlersToPasswordAndPasswordHintFields
////Facebook.inputChange = function() {
////	
////	$("#login_password").blur(function(){
////		if($(this).val()==""){
////			$("#login_password").hide();
////			$("#password-hint").show();
////			$("#password-hint").val("Please enter your password");
////			$("#password-hint").removeClass("focusField").addClass("idleField");
////		}
////	});	

////	$("#ca_password").blur(function(){
////		if($(this).val()==""){
////			$("#ca_password").hide();
////			$("#password-hint").show();
////			$("#password-hint").val("Please enter your password");
////			$("#password-hint").removeClass("focusField").addClass("idleField");
////		}
////	});	
////}

// 2011-02-17 MikkoR. Replaces Facebook.inputChange
function AddBlurHandlersToPasswordAndPasswordHintFields(formid) {
    var login_form;
    if (formid) {
        login_form = formid;
    }
    else {
        login_form = "#login_form";
    }
    $("#password-hint", login_form).removeClass("focusField");

    $("#login_password", login_form).blur(function() {
        if ($(this).val() == "") {
            $(this).hide();
            $("#password-hint", login_form).removeClass("focusField").addClass("idleField");
            $("#password-hint", login_form).show();
        }
    });

    $("#ca_password", login_form).blur(function() {
        if ($(this).val() == "") {
            $(this).hide();
            $("#password-hint", login_form).removeClass("focusField").addClass("idleField");
            $("#password-hint", login_form).show();
        }
    });

    $("#password-hint", login_form).click(function() {
        $(this).hide();
        $("#login_password", login_form).show().focus();
        $("#ca_password", login_form).show().focus();
    });

    $("#password-hint", login_form).focus(function() {
        $(this).hide();
        $("#login_password", login_form).show().focus();
        $("#ca_password", login_form).show().focus();
    });
}

function TestEmailAddress(email) {
    var d = new Date();

    $.ajax({
      type: 'GET',
      url: '/controls/ajaxcalls/Accounts/AccountLookup-BlankPassword.aspx?email=' + email + '&rnd=' + d.getTime(),
      success: ProcessAccountLookupResponse,
      dataType: "json"
    });
}

function SendAccountConfirmationEmail(email, firstName, activationId, sourceName) {
    var d = new Date();

    $.ajax({
      type: 'GET',
      url: '/controls/ajaxcalls/Accounts/SendConfirmationEmail.aspx?email=' + email + '&firstName=' + firstName + '&activationId=' + activationId + '&sourceName=' + sourceName + '&rnd=' + d.getTime(),
      success: ProcessAccountLookupResponse,
      dataType: "json"
    });
}

function ProcessAccountLookupResponse(responseJSON, statusText, caleeOptions) {
    // if the status is success
    if (statusText == "success") {
        // if any errors
        if (typeof responseJSON["errors"] != "undefined") {
            Facebook.Modal_Close();
            Facebook.Confirmation_Error_Modal(responseJSON["errors"], "Oops!");
        }
        else if (typeof responseJSON["success_message"] != "undefined") {
            //Facebook.Confirmation_Modal(responseJSON["success_message"], "Success!");
        }
        
        // if any JS to execute
        if (typeof responseJSON["script"] != "undefined") {
            Facebook.Modal_Close();
            new Function("options", "responseJSON", "statusText", responseJSON["script"])(caleeOptions, responseJSON, statusText);
        }
        
    }
    else
    {
        Facebook.Modal_Close();        
        Facebook.Confirmation_Error_Modal("There was an error contacting the server: \r\n" + statusText, "Oops!");
    }
}

function CloseModalAndFadeOutBkg(timeout) {
    if (typeof (timeout) != undefined && timeout > 0) {
        window.setTimeout(function() {
            Facebook.Modal_Close();
            Facebook.fadeOutBackground();
            window.clearTimeout();
        }, timeout);
    }
    else {
        Facebook.Modal_Close();
        Facebook.fadeOutBackground();
    }
}





























