
 //========================================================
// checks whether cookie exists or not.
// returns true if user signed in otherwise returns false.
 //========================================================
 function IsAlreadySignedIn()
 {
//    var myCookie = readCookie(PERSONCOOKIE); 
//    if(myCookie != null)
//     {
//        return true;
//     }
//     else
//     {
//        return false;
//        
//     }

    // decided to use the email value since bookmark pool is creating the personcookie with sessionid 
    if(readUserPersCookie(PERSONCOOKIE_EMAIL) != "")
    {
        return true;
    }
    else
    {
        return false;
    }
 }   
 
 //========================================================
 //checks whether ListingId exists in the temporary cookie.
 // returns -1 if user haven't saved this listingId or haven't signed in.
 //========================================================
 function getSavedListingId(ListingId)
 {
    var arr = readListingsPersCookie();
    if( arr != undefined)
    {
       return inArray(ListingId, arr);
     }
     return -1;
 }

 //========================================================
 //checks whether ListingId exists in the alert temporary cookie.
 // returns -1 if user haven't saved this listingId or haven't signed in.
 //========================================================
 function getAlertListingId(ListingId)
 {
    var arr = readAlertsPersCookie();
    if( arr != undefined)
    {
       return inArray(ListingId, arr);
     }
     return -1;
 }

 //========================================================
//checks whether ArticleId exists in the temporary cookie.
 // returns -1 if user haven't saved this ArticleId or haven't signed in.  
 //========================================================
 function getSavedArticleId(Id)
 {
    var arr = readArticlesPersCookie();    
    if( arr != undefined)
    {
      return inArray(Id, arr);
    }
    return -1;
 }  
 
 //========================================================
 //get temporary cookie value for whatever the cookieName passed
 //checks whether cookieName exists in the temporary cookie.
 // returns blank if it dosen't exist 
 //========================================================
 function getTempCookie(NameOfCookie)
 {   
    if (document.cookie.length > 0) 
    { 
     begin = document.cookie.indexOf(NameOfCookie);     
     if (begin != -1) 
     {  
       begin += NameOfCookie.length+1                  
       end = document.cookie.indexOf("&", begin);        
       var name = unescape(document.cookie.substring(begin,end)); 
       name = name.split(";")[0];
       if (name.charAt(0)==",")
       {
        name=name.substring(1,name.length); 
       }       
       return name;       
      }      
   }
    return ""; 

    }


 
 //========================================================        
 // switch the divs between "sign in | sign up" and "welcome | sign out".
 // if true it hides "sign in | sign up". 
 //========================================================
function ShowLoggedIn(flag)
{
    var isSessionRunning = "";

    //console.log("show logged in: " + flag);
    if(flag)
    {     
	    try {
            //FB.getLoginStatus(function(response) {
            FB.getLoginStatus(function(response) {
                //console.log(response);
                if ((response.status) && (response.status == "connected")) {
                    Facebook.User_GetInfo();
                    isSessionRunning = "isrunning";
                    //console.log(isSessionRunning);
                    $(function() {

                        $.ajax({
                            type: "POST",
                            url: "/controls/AjaxCalls/Facebook/IsAccountLinked.aspx?Facebook_UserId="+Facebook.GetUserId(),
                            data: "",
                            success: function(output) {
                                if(output == "success")
                                {                      
                                    //gE("loading").style.display = "none";
                                    gE("FD_in").style.display = "none";
                                    gE("FD_FB_out").style.display = "none"                                
                                }                          
                            }
                        });
                    });  
                }
                
                //console.log(isSessionRunning);
                if(isSessionRunning == "")
                {
                    //Only display logged into frontdoor only if accts are not linked. Otherwise, Facebook.js will handle
                    gE("myfacebookgreeting").innerHTML = "<em id=\"FB_icon\" class=\"fb\">&nbsp;</em><a href=\"javascript:\/\/(0);\" onclick=\"Facebook.Login(); return false;\">Get Connected, " + DisplayName() + "</a>";
                    //gE("loading").style.display = "none";
                    gE("FD_in").style.display = "block";
                    gE("FD_FB_out").style.display = "none";
                    Facebook.loginHeaderWidth();      
                }                    
                
                                 
                SignInOrRegister = "SignIn"


            });  
        }
        catch(e) {
        }
    }
    else
    {  
        Facebook.Modal_Close();
        document.getElementById("FB_in").style.display = "none";
        document.getElementById("FD_in").style.display = "none";
        document.getElementById("loading").style.display = "none";
        document.getElementById("FD_FB_out").style.display = "block";       
        SignInOrRegister = "";
    }
    
    if (readUserPersCookie(PERSONCOOKIE_USERTYPE) == 2) {
      var loginType = "fd";
      
      document.getElementById("loading").style.display = "none";
      document.getElementById("FD_FB_out").style.display = "none";       
      
      if (isSessionRunning.length > 0) {
        loginType = "fb";
        $("#my_fb > a").attr("href", "/pro/account/dashboard");
        document.getElementById("FB_in").style.display = "block";
        document.getElementById("FD_in").style.display = "none";
      }
      else {
        $("#my_fd > a").attr("href", "/pro/account/dashboard");
        gE("myfacebookgreeting").innerHTML = "<em id=\"FB_icon\" class=\"fb\">&nbsp;</em><a href=\"javascript:\/\/(0);\" onclick=\"Facebook.Login(); return false;\">Get Connected, " + DisplayName() + "</a>";
        document.getElementById("FD_in").style.display = "block";
        document.getElementById("FB_in").style.display = "none";
      }
      
      LoadProAccountMenu(loginType);
    }
    else if (readUserPersCookie(PERSONCOOKIE_USERTYPE) == 1) {
      if (isSessionRunning.length > 0) {
        $("#my_fb > a").attr("href", "/account/recent-activity/");
        document.getElementById("FB_in").style.display = "block";
        document.getElementById("FD_in").style.display = "none";
      }
      else {
        $("#my_fd > a").attr("href", "/account/recent-activity/");
        gE("myfacebookgreeting").innerHTML = "<em id=\"FB_icon\" class=\"fb\">&nbsp;</em><a href=\"javascript:\/\/(0);\" onclick=\"Facebook.Login(); return false;\">Get Connected, " + DisplayName() + "</a>";
        document.getElementById("FD_in").style.display = "block";
        document.getElementById("FB_in").style.display = "none";
      }
    }

    //console.log(readUserPersCookie(PERSONCOOKIE_USERTYPE));
 } 
 
 //========================================================
 // checks whether current page is personalization default page. 
 //========================================================
 function IsDefaultPage()
 {
    var url = window.location.href.split('?')[0];
    var arr = url.split(PersonalizationRoot);  
    if(arr[arr.length -1] == "Default.aspx" || arr[arr.length -1] == "")
    {
       return true;
    }
    else
    {
       return false;
    }
 }
 
  //========================================================
 // display header based on whether user logged in or not.
  //========================================================
 function DisplayHeader()
 {
    ShowLoggedIn(IsAlreadySignedIn());      
 }
 
  //========================================================
 // thick box update. Updates the information in the thickbox
 // div tag and resizes the frame size.
  //========================================================
 function tb_update(URL, Width, Height) 
 { 
    gE("TB_window").style.width = (parseInt(Width, 10) + 30) + "px"; ;  
    gE("TB_window").style.height = (parseInt(Height, 10) + 30) + "px"; ;  
    gE("TB_ajaxContent").style.width = Width + "px";  
    gE("TB_ajaxContent").style.height = Height + "px";   
    if(URL != undefined || URL != null)
    {
       $AJAX.GetToObject(gE("TB_ajaxContent"),URL);
     }
    tb_position_gt(parseInt(Width, 10) + 30);  
    window.setTimeout(function(){
            LoadPageDefaults();
        },255);
    
 }
         
 function tb_updateHTML(caption, html, Width, Height)
 {
     //if IE 6
    if (typeof document.body.style.maxHeight === "undefined") {
			$("body","html").css({height: "100%", width: "100%"});
			$("html").css("overflow","hidden");
			//iframe to hide select elements in ie6
			if (document.getElementById("TB_HideSelect") === null) {
				$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}
		//all others
		else{
			if(document.getElementById("TB_overlay") === null){
				$("body").append("<div id='TB_overlay'></div><div id='TB_window'>");
				$("#TB_overlay").click(tb_remove);
			}
		}
		
		if(caption===null){caption="";}
		//add loader to the page
		$("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");
		//show loader
		$('#TB_load').show();

		//defaults to 630 if no paramaters were added to URL
		TB_WIDTH = (Width*1) + 30 || 630;
		//defaults to 440 if no paramaters were added to URL
		TB_HEIGHT = (Height*1) + 40 || 440; 
		ajaxContentW = TB_WIDTH - 30;
		ajaxContentH = TB_HEIGHT - 45;
			
		if($("#TB_window").css("display") != "block"){
						$("#TB_window").append("<!--<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>close</a> or Esc Key</div></div>--><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
					}else{
						$("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
						$("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
						$("#TB_ajaxContent")[0].scrollTop = 0;
						$("#TB_ajaxWindowTitle").html(caption);
					}
			
	    $("#TB_closeWindowButton").click(tb_remove);
			
//		$("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
						tb_position();
						$("#TB_load").remove();
						tb_init("#TB_ajaxContent a.thickbox");
						$("#TB_window").css({display:"block"});
						window.setTimeout(function(){
                                            LoadPageDefaults();
                                        },255);
//					});

       gE("TB_ajaxContent").innerHTML = html;
					
		document.onkeyup = function(e){
		        // ie
				if (e == null) { 
					keycode = event.keyCode;
				}
				// mozilla
				else { 
					keycode = e.which;
				}
				// close
				if(keycode == 27){ 
					tb_remove();
				}	
			};		
 }
 
 function tb_position_gt(gt_WIDTH)
 {
    $("#TB_window").css({marginLeft: '-' + parseInt((gt_WIDTH / 2),10) + 'px', width: gt_WIDTH});
    // take away IE6
	if ( !(jQuery.browser.msie && typeof XMLHttpRequest == 'function')) { 
		$("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
	}
  }    

// if IsFirstTime = true, then display mask and the control else just update the div innerHTML.
 function SignIn(IsFirstTime)
 { 
//    if(IsDefaultPage())
//    {
//        // default page has sign in control displayed already on the page. 
//          alert("Please Sign in Below");
//     }
//     else 

        if(IsFirstTime)
        {
         if(gE("search_pricemin"))
         {
            gE("search_pricemin").setAttribute("tabindex", -1);
            gE("search_pricemin").tabIndex=-1;
         }
         if(gE("search_pricemax"))
          {
            gE("search_pricemax").setAttribute("tabindex", -1);
            gE("search_pricemax").tabIndex=-1;
           }
         if(gE("search_bedrooms"))
          {
            gE("search_bedrooms").setAttribute("tabindex", -1);
            gE("search_bedrooms").tabIndex=-1;
          }
     
            if(gE("email")!=null)
            {
                tb_showhtml('', PersonalizationRoot + "AjaxCalls/SignIn.aspx?display=login&height=285&width=310&emailadd=" + gE("email").value, false); 
            }
            else
            {
                tb_showhtml('', PersonalizationRoot + "AjaxCalls/SignIn.aspx?display=login&height=285&width=310", false); 
            }
        }
        else if (gE("Email_Add")!=null)
        {
            
            tb_showhtml('', PersonalizationRoot + "AjaxCalls/SignIn.aspx?display=login&height=285&width=310&emailadd=" + gE("Email_Add").value, false); 
        }
        else 
        {           
         tb_update(PersonalizationRoot + "AjaxCalls/SignIn.aspx?display=login", "310", "285"); 
        }
//     }
 }
   
 function SignOut()
 {
    $AJAX.GetForDelegate(SignOutDelegate, PersonalizationRoot + "AjaxCalls/Personalization.aspx?action=sign_out");   
     if(document.getElementById("HomeFacebookBanner") != null )
     {
         window.setTimeout(reload, 300);
     }
 }
                    
 function SignOutDelegate(AjaxResponse)
 {
      ShowLoggedIn(false);
      // || AjaxResponse.indexOf("has been saved") > -1
      if(AjaxResponse != "success") 
      {
           window.location.reload(true); 
      }       
      else
      {
           var url = window.location.href.split('?')[0];
           
           if (window.location.pathname == "/" || window.location.pathname == "")
           {
               window.location.href= window.location.href;
           }
           
           if(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.href.toLowerCase().indexOf('pro/') != -1 || window.location.href.indexOf("agent-tools/") != -1)
           {            
               window.location.replace("/Default.aspx")
           }           

           if(url.indexOf(PersonalizationRoot) > -1)
           {
              window.location.href = PersonalizationRoot + "Default.aspx";
           }
           else
           {
                ChangeUserAction();
           }
            
//            if(window.location.href.indexOf('pro/') != -1)
//            {
//                window.location.reload(true);
            //            }

            $.event.trigger('SignOutEvt');
       }
 }
   
 function NotSignedInDelegate(AjaxResponse)
 {
    var  html = AjaxResponse;
     tb_updateHTML("", html, 550, 360);
//      tb_showIframe();
//      gE("TB_ajaxContent").innerHTML = html;
 }
 
 
   function SubmitByEnterkey(e,formID)
   {
       if (window.event)
        {
            KeyCode = e.keyCode;           
        }
        else if(e.which)
        {
            KeyCode = e.which;
        }
            
       if(KeyCode == 13)
         {
            if(formID!=undefined)
            {
                if(formID=="login_form")
                {               
                   //SignInSubmit(formID);
                   return true; 
                   
                }
                else if(formID=="forgot_pw_form")
                {
                    //GetPassword();                 
                    return true;
                }
                else
                {
                  ValidateEmailFriend(formID);
                }
             }
             else
             {
                SaveSearchSubmit();
             }
        }
        else
        {
         return false;
       }
  }

  var task;
  var customdata1;
  var customdata2;
  var active_form;
   
 function SignInSubmit(formID, _task, _customdata1, _customdata2)
 {
     if (formID) {
         active_form = "#" + formID;
     }
     else {
         active_form = "#login_form";
     }
     
      if(ValidateSignIN(formID))
       {                   
           
           var frm = document.forms[formID]; 
           var querystring = "email=" + frm.email.value + "&pwd=" + frm.login_password.value + "&rememberme=false";
               if(GetPageName().indexOf(PersonalizationRoot + "sign_up.aspx") > -1)
               {
                  querystring += '&PathInfo=signuppage';
               }
               else
               {
                  querystring += '&PathInfo='+ GetPageName();
               }
               // to differentiate between signin, signup and forgot password actions in Personalization.aspx page.
               querystring += '&NameCookie=' + getTempCookie("iname") + '&action=sign_in';
               $("#loadingconnect", active_form).show();
             var strURL = PersonalizationRoot + "AjaxCalls/Personalization.aspx?" + querystring;

             task = _task;
             customdata1 = _customdata1;
             customdata2 = _customdata2;
           
           $AJAX.GetForDelegate(SignInResultDelegate, strURL);
           if(document.getElementById("HomeFacebookBanner") != null ){
                window.setTimeout(reload, 500);

            }
       }
       else
       {
           $("#loadingconnect", active_form).hide();
         return false;
       }
 }

 function HandleClaimWizardLogin() {
     if (task.indexOf('PerformClaimListing') != -1) {
         //claim listing
         //pro user direct claim
         if (readUserPersCookie(PERSONCOOKIE_USERTYPE) == 2) {
             var URL = WebRoot + "Controls/AjaxCalls/AgentProfile/ProListingClaim.aspx?Task=DirectClaim&IdListing=" + customdata1 + "&IdParentAccount=" + customdata2;
             $.get(URL, function(data) {
                 CreateAndFillProListingClaimContainer(data);

                 if ($('#spnListingClaimStatus').html().indexOf('SUCCESS') != -1) {
                     window.location = WebRoot + "pro/claimlisting/" + customdata1;
                 }
                 else {
                     ShowClaimStatusModalWindow();
                 }
             });
         }
         //regular user convert
         else {
             var forward = WebRoot + 'listing/' + customdata1;
             //                        if (task == 'PerformClaimListingLOGIN') {
             //                            forward = WebRoot + 'listing/' + customdata1;
             //                        }
             //                        if (task == 'PerformClaimListingTHISISME') {
             //                            forward = null; //WebRoot + 'pro/claimlistings/step1/' + customdata1;
             //                        }
             var modalInfo = {
                 header: "Pro Account Required",
                 text: "<p>You need to have a pro account to confirm listings. <br/><br/>Would you like to convert to a pro account now?</p>",
                 btntext: "Convert to Pro",
                 btnclick: function() {  OmAgentInt(this,null,null,"Registration : Convert to Pro"); document.location = WebRoot + "pro/upgrade/" + customdata1 + "/" + customdata2; },
                 lnktext: "no, thank you.",
                 lnkclick: function() {
                     //if (forward != null)
                     document.location = forward;
                     //else
                     //CloseProAccountModal();
                 },
                 closeclick: function() {
                     //if (forward != null)
                     document.location = forward;
                     //else
                     //CloseProAccountModal();
                 }
             }

             if ($('#divProAccountModal').length == 0) {
                 var URL = WebRoot + "Controls//AjaxCalls//AgentProfile//ProListingClaim.aspx?Task=GetPlainResponse";
                 $.get(URL, function(data) {
                     CreateAndFillProListingClaimContainer(data);

                     ShowBlockedProAccountModalWindow(modalInfo);
                 });
             }
             else {
                 ShowBlockedProAccountModalWindow(modalInfo);
             }
         }
     }
 }
 
 function reload()
 {
   // window.location.reload(true);
   DisplayNotificationBanner()
 }

 function SignInResultDelegate(AjaxResponse) {
     // Signed in successfully without any action pending.
     if (AjaxResponse == "success") {
         // remove the activation cookie
         RemoveCookie("reg");

         //Connect accounts if logged into facebook
        FB.getLoginStatus(function(response) {
            if ((response.status) && (response.status == "connected")) {
                 Facebook.Connect(readUserPersCookie(PERSONCOOKIE_EMAIL), readUserPersCookie("pwd"), false);
             }
         });

         if (gE("loadingconnect")) {
             gE("loadingconnect").style.display = "none";
         }
         if (task.indexOf("convert_to_proRedirect") == -1)
         {
           Facebook.Confirmation_Modal("Welcome back, " + DisplayName() + ".");
           window.setTimeout(function() {
               Facebook.Modal_Close();
               Facebook.fadeOutBackground();
           }, 5000);
          }
          
         ShowLoggedIn(true);

         ChangeUserAction();
         Facebook.Modal_Close();

         window.setTimeout(function() {
             if(task.indexOf("buyCredits") != -1)
             {
                window.location = "/pro/credits/dashboard";
             }
             else if (task.indexOf("header") != -1) {
                 if (readUserPersCookie(PERSONCOOKIE_USERTYPE) == 2) {
                     window.location = "/pro/account/editprofile";
                 }
                 else {
                     window.location = "/account/recent-activity";
                 }
             }
             else if (window.location.href.indexOf("pro/") != -1 || window.location.href.indexOf("agent-tools/") != -1) {
                 if (window.location.href.indexOf("register") != -1 || window.location.href.indexOf("signup") != -1) {
                     if (readUserPersCookie(PERSONCOOKIE_USERTYPE) == 2) {
                         window.location = "/pro/account/editprofile";
                     }
                     else if (window.location.href.indexOf("signup") != -1) {
                         window.location = "/account/recent-activity";
                     }
                     else if (task.indexOf("convert_to_proRedirect") != -1)
                         {
                           document.location = WebRoot + "pro/upgrade";
                         }
                         else
                         {
                         var modalInfo = {
                             header: "Pro Account Registration",
                             text: "<p>Would you like to convert to a pro account now?</p>",
                             btntext: "Convert to Pro",
                             btnclick: function() { document.location = WebRoot + "pro/account/settings"; },
                             lnktext: "no, thank you.",
                             lnkclick: function() {
                                 document.location = WebRoot + "/pro/account/register";
                             },
                             closeclick: function() {
                                 document.location = WebRoot + "/pro/account/register";
                             }
                         }
                         var URL = WebRoot + "Controls//AjaxCalls//AgentProfile//ProListingClaim.aspx?Task=GetPlainResponse";
                         $.get(URL, function(data) {
                             CreateAndFillProListingClaimContainer(data);
                             ShowBlockedProAccountModalWindow(modalInfo);
                         });
                     }
                 }
                 else if (window.location.href.indexOf("claimlistings/step1") != -1) {
                     HandleClaimWizardLogin();
                 }
                 else {
                     window.location.reload(true);
                 }
             }
             else 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) {
                 window.location = "/account/recent-activity"
             }
         }, 1500);
         if (task == "select_homestyle") {
             eval(customdata1);
             //console.log(homestyleObj.idlisting + ", " + homestyleObj.idaccoutn + ", " + homestyleObj.agentcodestyle + ", " + homestyleObj.idstyle + ", " + homestyleObj.stylename);
             SelectHomestyle(homestyleObj.idlisting, homestyleObj.idaccount, homestyleObj.agentcodestyle, homestyleObj.idstyle, homestyleObj.stylename);
             task = "";
             customdata1 = "";
         }

         $.event.trigger('SignInEvt');
     }
     else if (AjaxResponse.indexOf("pageredirect=") > -1) {
         window.location.href = AjaxResponse.split("=")[1];
     }
     // Signed in but still adding the search action is pending.
     else if (AjaxResponse == "lastaction_addsearch") {

         ShowLoggedIn(true);
         if (SignInOrRegister == "SignIn") {
             if (FB.getAuthResponse() != null) {
                 Facebook.Connect(readUserPersCookie(PERSONCOOKIE_EMAIL), readUserPersCookie("pwd"), false);
             }
             ShowLoggedIn(true);
             ChangeUserAction();
             window.setTimeout(function() {
                 Facebook.Modal_Close();
                 Facebook.fadeInBackground();
                 Facebook.ShareSearch(GetSearchLocation(), SEOSection)
             }, 5000);
         }
         else {
         }
     }
     // Signed in but want to see the item alert dialog.
     else if (AjaxResponse.indexOf("lastaction_showitemalertdialog") > -1) {
         ShowLoggedIn(true);

         if (SignInOrRegister == "SignIn") {
             // If user is logged into facebook already share with facebook if not share with email.
             if (FB.getAuthResponse() != null) {
                 // 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);

         }
     }
     // Signed in but still sharing all listings is pending.
     else if (AjaxResponse.indexOf("lastaction_bmpshare") > -1) {
         ShowLoggedIn(true);
         var ShareType = 'emailshare';
         var Arr = AjaxResponse.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.
             if (FB.getAuthResponse() != null) {
                 // ShareType = 'fbshare';
                 Facebook.Connect(readUserPersCookie(PERSONCOOKIE_EMAIL), readUserPersCookie("pwd"), false);
             }
             Facebook.Modal_Close();
             ChangeUserAction();
             window.setTimeout(function() {
                 Facebook.Modal_Close();
                 Facebook.fadeOutBackground();
                 ShareAllListings(ShareType);
             }, 2000);

         }
     }
     // Signed in but still sharing all listings is pending.
     else if (AjaxResponse.indexOf("lastaction_bmpagentshare") > -1) {
         ShowLoggedIn(true);
         var Arr = AjaxResponse.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.
             if (FB.getAuthResponse() != null) {
                 Facebook.Connect(readUserPersCookie(PERSONCOOKIE_EMAIL), readUserPersCookie("pwd"), false);
             }
             Facebook.Modal_Close();
             window.setTimeout(function() {
                 Facebook.Modal_Close();
                 Facebook.fadeOutBackground();
                 ChangeUserAction();
                 Facebook.SharePropertiesAgentModal(TmpAgentEmail, TmpAgentName);
             }, 2000);

         }
     }
     // Signed in but still View as List action is pending.
     else if (AjaxResponse == "lastaction_bmpviewlist") {
         ShowLoggedIn(true);
         var ShareType = 'emailshare';
         if (SignInOrRegister == "SignIn") {
             // If user is logged into facebook already share with facebook if not share with email.
             if (FB.getAuthResponse() != null) {
                 ShareType = 'fbshare';
                 Facebook.Connect(readUserPersCookie(PERSONCOOKIE_EMAIL), readUserPersCookie("pwd"), false);
             }
             Facebook.Modal_Close();
             //  ChangeUserAction();          
             window.setTimeout(function() {
                 window.location.href = WebRoot + "account/my-folders/";
             }, 2000);

         }
     }
     // Signed in but still some action is pending.
     else if (AjaxResponse.indexOf("lastaction_") > -1) {

         var message = AjaxResponse.split("::");
         if (FB.getAuthResponse() != null) {
             Facebook.Connect(readUserPersCookie(PERSONCOOKIE_EMAIL), readUserPersCookie("pwd"), false);
         }
         Facebook.Modal_Close()
         window.setTimeout(function() {
             Facebook.Confirmation_Modal(message[1] + ' ' + message[0].split("_")[1], "Welcome Back!");
         }, 1000);

         ShowLoggedIn(true);
         ChangeUserAction();
         window.setTimeout(function() {
             Facebook.Modal_Close();
             Facebook.fadeOutBackground();
         }, 6000);



         //window.setTimeout("tb_remove();", 4000);          
     }
     else if (AjaxResponse == "Your account has not been activated.") 
     {
         if (task == "select_homestyle") {
             eval(customdata1);
             //console.log(homestyleObj.idlisting + ", " + homestyleObj.idaccoutn + ", " + homestyleObj.agentcodestyle + ", " + homestyleObj.idstyle + ", " + homestyleObj.stylename);
             SelectHomestyle(homestyleObj.idlisting, homestyleObj.idaccount, homestyleObj.agentcodestyle, homestyleObj.idstyle, homestyleObj.stylename, true);
             task = "";
             customdata1 = "";
         } 
        
         window.location.href = "/Activation.aspx?confirmation=AccountSuccess&email=" + gE("email").value + "&password=" + gE("login_password").value;
     }
     // Unexpected error occured while signing in.
     else {
         $('#pw', active_form).css('color', '#000');
         
         $("#modal").addClass("modal-error");
         if (AjaxResponse.indexOf("email address") > -1) {
             $("#email_input", active_form).addClass("input-error");
             $("#emailErrLogin", active_form).show();
         }
         else {
             $("#password_input", active_form).addClass("input-error");
             $("#pwdErrLogin", active_form).show();
         }
         $("#loadingconnect", active_form).hide();
     }
 }
       
   function ForgotPassword(flag, email)
   {
    Facebook.Modal_Close();
    var strURL = '/controls/ajaxcalls/facebook/ForgotPasswordModal.aspx';
    if(email != undefined)
    {
       strURL += "?email=" + email;
    }
     if(IsDefaultPage())
     {
          $.ajax({
            url:strURL,
            success: function(html){
                $(html).modal({
                    minHeight: 400,
                    minWidth: 400
                });
                // 2011-02-17 MikkoR. Handle focus and blur of input controls in new html 
                ////Facebook.inputChange();
                HandleInputControls();
                FocusToFirstInputInModal();
            }
       });
            
       // tb_showhtml("", PersonalizationRoot + "AjaxCalls/SignIn.aspx?display=forgotpassword&height=230&width=310");   
     }
     else
     {
         if(flag)
         {
     
          $.ajax({
            url:strURL,
            success: function(html){
                $(html).modal({
                    minHeight: 400,
                    minWidth: 400
                });
                // 2011-02-17 MikkoR. Handle focus and blur of input controls in new html 
                ////Facebook.inputChange();
                HandleInputControls();
                FocusToFirstInputInModal();
            }
       });
   
           //tb_showhtml("", PersonalizationRoot + "AjaxCalls/SignIn.aspx?display=forgotpassword&height=230&width=310");   
         }
         else
         {
            $.ajax({
                url:strURL,
                success: function(html){
                    $(html).modal({minWidth: 400});
                    // 2011-02-17 MikkoR. Handle focus and blur of input controls in new html 
                    ////Facebook.inputChange();
                    HandleInputControls();
                    FocusToFirstInputInModal();
                }
           });
           //tb_update(PersonalizationRoot + "AjaxCalls/SignIn.aspx?display=forgotpassword", "310", "230");   
         }
     }
   }
    
   function GetPassword()
   {
       if(validateLoginEmail(gE("Email_Add"), gE("emailErr"),""))
       {
           // to differentiate between signin, signup and forgot password actions in Personalization.aspx page.
           var querystring = "email=" + gE("Email_Add").value + "&action=forgot_password"; 
           
           $AJAX.GetForDelegate(forgotpasswordResultDelegate, PersonalizationRoot + "AjaxCalls/Personalization.aspx?" + querystring);
       }
       else
       {
         return false;
       }
   }
   
   function forgotpasswordResultDelegate(AjaxResponse)
   {
       var html="";
       if(AjaxResponse == "success")
       {
           gE("forgot_pw_result").style.display = 'block';
           gE("forgot_pw").style.display = 'none';
           html = "<div id='pw_result_hdr' class='clearfix'><h2>Password Sent</h2><a href='javascript:void(0);' onclick='tb_remove();' class='close_tb'>close</a></div>";
           html += '<p>Your password was just sent to your e-mail.</p>';
           html += '<div id="tb_tbns"><div class="pw_actions clearfix"><div id="pw_signin_wrapper"><a href="javascript:void(0);" id="pw_signin" onclick="SignIn();">Sign In Now</a></div> <span class="or">OR</span> <a href="javascript:void(0);" onclick="javascript:tb_remove();" id="not_sign">Do Not Sign In Now</a></div></div>';
        // html += '<p class="pw_actions"><a href="javascript:SignIn(false);">Sign In</a></p>';
        
           gE("forgot_pw_result").innerHTML = html;    
       }
       else
       {           
          html = "<p>" + AjaxResponse + "</p>";
          var btnhtml= '<div class="pw_actions" class="clearfix"><a href="javascript:ForgotPassword(false);" id="try_again">Try Again</a></div>';          
          gE("emailNotFoundErr").style.display = 'block';
          gE("emailErr").style.display = 'none';
          gE("emailNotFoundErr").innerHTML = html;
          gE("tb_tbns").innerHTML=btnhtml;
       }
       
//       html += '<div id="tb_tbns"><div class="pw_actions" class="clearfix"><div id="pw_signin_wrapper"><a href="javascript:void(0);" id="pw_signin" onclick="SignIn();">Sign In Now</a></div> <span class="or">OR</span> <a href="javascript:void(0);" onclick="javascript:tb_remove();" id="not_sign">Do Not Sign In Now</a></div></div>';
       
   }
   
   // shows or hides the list of saved items and saved searches and links to those pages.
   function MyFrontdoorList()
   {
//gE("searchbardiv").style.zIndex ="0";

if (gE("searchbar_wrapper") != null) {
gE("searchbar_wrapper").style.zIndex="0";
gE("searchbar_wrapper").style.position ="relative";
}

if (gE("serach_home") != null) {
gE("serach_home").style.zIndex = "0";
}

          var rhtml= "";
          /*
          ------------------------------------------------------------
          Category should appear in MyFrontDoor if it is not 0---mamta
          ------------------------------------------------------
          */
          
                   if(readListingCountPersCookie()!=0 || readSearchCountPersCookie()!=0 || readArticleCountPersCookie()!=0)
          {     
             rhtml += '<div id="my_fd_options_rt_div"><h3>My Saved Items</h3>';
         }
          
          if(readListingCountPersCookie()!=0)
          {      
             rhtml += '<div class="group"><div class="saved_cat"><a href="/accounts.aspx">Listings</a> ('+ readListingCountPersCookie() + ')</div>';
            rhtml += '<ul>';
            
             var arrLatListings = readLatestListingsPersCookie();
             for( var i = 0; i < arrLatListings.length; i++)
             {
               var ItemInfo = arrLatListings[i].split("::");
               rhtml += '<li class="clearfix"><a href="' + WebRoot + 'listing/' + ItemInfo[1] +'" class="item">' + ItemInfo[0] + '</a></li>';
             }
             rhtml += '</ul></div>';
          }
          
           if(readSearchCountPersCookie()!=0)
          {      
         
             rhtml += '<div class="group"><div class="saved_cat"><a href="/accounts.aspx">Searches</a> ('+ readSearchCountPersCookie() + ')</div>';
            
          
           rhtml += '<ul>';
             var arrLatListings = readLatestSearchesPersCookie();
             for( var i = 0; i < arrLatListings.length; i++)
             {
               var ItemInfo = arrLatListings[i].split("::");;
              // html += '<li>' + ItemInfo + '</li>';
//               var searchlink = WebRoot + "results.aspx?" + ItemInfo[1];

               rhtml += '<li class="clearfix"><a href="Javascript:GotoSearchPage(' + ItemInfo[1] +');" class="item">' + ItemInfo[0] + '</a></li>';
             }
             rhtml += '</ul></div>';
}
          
           //html +=  '<div><a href="' + PersonalizationRoot + 'saved_comparisons.aspx">Comparisons ('+ readSearchCountPersCookie() + ')</div>';
          if(readArticleCountPersCookie()!=0)
          {
//            html +=  '<div class="group"><div class="saved_cat"><a href="' + PersonalizationRoot + 'saved_items.aspx">Articles</a> ('+ readArticleCountPersCookie() + ')</div>';
             
             rhtml += '<div class="group"><div class="saved_cat"><a href="/accounts.aspx">Articles</a> ('+ readArticleCountPersCookie() + ')</div><ul>';
             var arrLatListings = readLatestArticlesPersCookie();
             for( var i = 0; i < arrLatListings.length; i++)
             {
               var ItemInfo = arrLatListings[i].split("::");
               rhtml += '<li class="clearfix"><a href="' + WebRoot + 'news/article/' + ItemInfo[1] +'" class="item">' + ItemInfo[0] + '</a></li>';
             }
            rhtml += '</ul></div>';
}
//          if( readVideoCountPersCookie ()!=0)
//          {          
//              html +=  '<div class="group"><a href="' + PersonalizationRoot + 'saved_video.aspx">Videos</a> ('+ readVideoCountPersCookie () + ')</div>';
//          }         
                  
           if(readListingCountPersCookie()!=0 || readSearchCountPersCookie()!=0 || readArticleCountPersCookie()!=0)
          {      
             rhtml += '</div><div id="my_fd_options_bottom"></div>';
          }      
                  
                  var G = new GetWindowBunds();
            gE("MyFDBackOpen").style.left = "1px";
            gE("MyFDBackOpen").style.top = "1px"; //fix
            gE("MyFDBackOpen").style.width = "1000px";
            gE("MyFDBackOpen").style.height = (G.VisibleHeight-30) + "px";
            gE("MyFDBackOpen").style.left = "0px";
            gE("MyFDBackOpen").style.top = "0px";
                  
      if(gE("my_fd_options_rt").style.display == 'none' && rhtml!="")
      {
      gE("my_fd_options_rt").style.display = 'block';
          gE("MyFDBackOpen").style.display = 'block';
       //   gE("powered_by").style.display='none';
      }

       gE("my_fd_options_rt").innerHTML = rhtml;
          }
   
   function CloseMyFD(){
            gE("my_fd_options_rt").style.display = 'none';
            gE("MyFDBackOpen").style.display = 'none';
            //gE("loggedin").className = ""
//gE("searchbardiv").style.zIndex ="";
if (gE("searchbar_wrapper") !=null) {
gE("searchbar_wrapper").style.zIndex="";
gE("searchbar_wrapper").style.position ="static";
}
if (gE("serach_home") != null) {
gE("serach_home").style.zIndex = "0";
}
   }
   
   function HoverMyFD(){
              if(readListingCountPersCookie()==0 && readSearchCountPersCookie() == 0 && readArticleCountPersCookie() == 0){
gE("city-dropdown").style.display ="none";
gE("close-city-dropdown").style.display ="none";
gE("nav_city_url").className ="";
//gE("searchbardiv").style.zIndex ="0";
gE("my_fd_options_rt").style.zIndex ="98";
           }
   }
   ///////////// Validations start
   
   // Validation for email address.
   function validateLoginEmail(emailField, emErr, message) {
        if (fieldHasValue(emailField) && validEmailField(emailField)) {
            $("#email_input", active_form).removeClass("input-error");
             return true;
         }
         else {
         emErr.show();

         $('#eml', active_form).css('color', '#000000')
            
            if(!fieldHasValue(emailField)){
                emErr.html("Please enter your e-mail address.");
            }
            else{
              if(message != "")
              {
                //"*Not a valid e-mail format.";
                emErr.html(message); 
              }
            }
            $("#modal").addClass("modal-error");
            $("#email_input", active_form).addClass("input-error");
            firstErrField=emailField;
            AlertFocus(firstErrField);
            return false;  
         }        
    }
    
    //validation for password. rules - 1)atleast 6 characters. 2) should be alpha numberic
    function validateLoginPassword (pwdField, pwdErr){
        var fieldValue = trim(pwdField.value);
        //  var regex1 = /[0-9]/g;          // must have at least 1 number
        //	var regex2 = /[a-zA-Z]/g;       // must have at least 1 letter
            // should only contain numbers and letters
	        var regex3 = /[^0-9a-zA-Z\!@#\$%^\.\*\+=\_]/g;   

        if ( fieldHasValue(pwdField) && fieldValue.length > 5 && !regex3.test(fieldValue)) {
             pwdErr.hide();
             return true;
             
         }
         else {
             pwdErr.show();
             $("#pw", active_form).css('color', '#000000');
            $("#modal").addClass("modal-error");
            $("#password_input", active_form).addClass("input-error");
            if(pwdField == ""){
                pwdErr.html("Please enter your password.");
            }
            else{
                pwdErr.html("Oops! The password you entered does not match our records. Please try again.");
            }
            
           return false;  
         }
     }
     
     function ValidateSignIN(formID)
     {        
        var frm = document.forms[formID];
        var isValidForm = true;
        //var emErrHeader=document.getElementById("emailErrHead");
        var emErr = $('#emailErrLogin', active_form);
        var pwdErr = $('#pwdErrLogin', active_form); 
        var arrErrSum = new Array();
        var firstErrField;

        emErr.hide();
        pwdErr.hide();
        $('#error', active_form).hide(); 
        
        //email
        if (!validateLoginEmail(frm.email, emErr, "Please check the format of your e-mail address and re-enter. (i.e. joe@frontdoor.com).")) {
            //arrErrSum[arrErrSum.length]= "<li>Email Address</li>";
            
            if (firstErrField==undefined){
                firstErrField = frm.email;
            }
            $("#email_input", active_form).addClass("input-error");
            isValidForm = false;
        }
        
        //password and confirm
        if (!validateLoginPassword(frm.login_password, pwdErr)) {
        
            //arrErrSum[arrErrSum.length]= "<li>Password / Confirm Password</li>";
            if (firstErrField==undefined){
                firstErrField = frm.password;
               
            }
            $("#password_input", active_form).addClass("input-error");
            isValidForm = false;
        }
        
        //toErrSummary(arrErrSum);
        if(isValidForm) {
            return true;
        }
        else {
            if(firstErrField!=undefined)
            {
                AlertFocus(firstErrField);
            }
            return false;
        }
       
     }    
     
     // displays all the validation errors as a list.
     function toErrSummary(arrErrSum){
           var errList = document.getElementById("errSummaryList");
           var reqSum  = document.getElementById("valid_req");
           if (arrErrSum.length != 0) {
               reqSum.style.display = 'inline';
               errList.innerHTML = arrErrSum.join('');
           }
           else  {
               reqSum.style.display = 'none';
               errList.innerHTML = '';
           }           
    }     
    
    ///////// Validation End.
    
    function rollOn(listingId)
    {            
        gE("rolloff_" + listingId).className = "rollon_item";
        document.getElementById("listingBtns_" + listingId).style.display = 'block';
    }

    function rollOff(listingId)
    {       
        gE("rolloff_" + listingId).className = "rolloffmode";
        document.getElementById("listingBtns_" + listingId).style.display = 'none';
    }
    
   function rollOnSearch(listingId)
   {               
      if(!IsEditOn)
      {
        gE("rolloff_" + listingId).className = "rollon_item";
        document.getElementById("listingBtns_" + listingId).style.display = 'block';
        gE("edittitle_" + listingId).style.display = 'inline';
      }
   }

   function rollOffSearch(listingId)
   {        
        if(gE("searchname_edit_" + listingId).style.display == 'none')
        {
            gE("rolloff_" + listingId).className = "rolloffmode";
            document.getElementById("listingBtns_" + listingId).style.display = 'none';
            gE("edittitle_" + listingId).style.display = 'none';
        }
   }
   
   function GotoSearchPage(SearchId)
   {
      var query = "action=getsearchlink&SearchId=" + SearchId; 
      $AJAX.GetForDelegate(GotoResults, PersonalizationRoot + "AjaxCalls/My_Options.aspx?" + query); 
   }
   
   function GotoResults(AjaxResponse)
   {  
      if(AjaxResponse != "")
      {
         window.location.href = AjaxResponse;
      }
   }
   
   function UserOptionsDelegate(AjaxResponse)
   {        

     var html = "";
     var caption = "";
     var width = 250;
     var height = 100;     
     var returnVal=AjaxResponse.split("::")[1]; 
     if(returnVal!=undefined)
     {
        if(returnVal.charAt(0)==",")
        {
            returnVal=returnVal.substring(1,returnVal.length);
        }
     }
     if (AjaxResponse.indexOf("success_add_listing")!=-1)
     { 
        ChangeUserAction();          
        
        var conf = getBookmarkCookieValue();
        var showChecked = conf;
        
        if (conf.length == 0) {
            setBookmarkCookieValue(true);
            showChecked = "1";
        }
        
        if (conf != "1") {
            html = returnVal + ' was saved to your account.';
            Facebook.BMConfirmation_Modal(html, undefined, showChecked);
            
            TimeOutModal = window.setTimeout(function(){
                Facebook.Modal_Close();
                Facebook.fadeOutBackground();
              }, 
              5000)   
        }
      }
      else if (AjaxResponse.indexOf("success_add_alert_listing")!=-1)
      { 
        SaveListingAlert(returnVal);        
        //ChangeUserAction();      
      }
      else if (AjaxResponse.indexOf("success_update_item_alert")!=-1)
      { 
        Facebook.Modal_Close();
        
        Facebook.Confirmation_Modal(returnVal);
     
        TimeOutModal = window.setTimeout(function(){
            Facebook.Modal_Close();
            Facebook.fadeOutBackground();
          }, 
          5000);
                                     
        ChangeUserAction();
      }
      else if (AjaxResponse.indexOf("success_add_article")!=-1)
      {        
         ChangeUserAction(); 
         
         html = '"' + returnVal + '" was saved to your account.';
         Facebook.Confirmation_Modal(html);
        
        TimeOutModal = window.setTimeout(function(){
            Facebook.Modal_Close();
            Facebook.fadeOutBackground();
          }, 
          5000)   
      } 
      else if (AjaxResponse.indexOf("success_add_video") != -1)
      {   
          ChangeUserAction();
          caption = "Save Video";
          html='<div id="not_signedin_hdr" class="clearfix"><h2>Success!</h2></div>'
          html += '<div id="success_saved"><span class="b">"'+ returnVal+'"</span> was saved to your account.';
        html += '<div id="tb_tbns"><a href="javascript:void(0);" onclick="tb_remove();"  id="success_ok">OK</a></div></div>';
      tb_updateHTML(caption, html, width, height);
      window.setTimeout("tb_remove();", 4000);
      } 
      else if(AjaxResponse.indexOf("success_add_search")!=-1)
      {
        Facebook.Modal_Close();         
        ChangeUserAction();
        html = '"' + returnVal + '" was saved to your account.';
            
        Facebook.Confirmation_Modal(html);
     
        TimeOutModal = window.setTimeout(function(){
            Facebook.Modal_Close();
            Facebook.fadeOutBackground();
          }, 
          5000)  
            
              
         
        
      }    
      else if(AjaxResponse.indexOf("success_show_alert_dialog") > -1)
      {
         var params = AjaxResponse.split(":");
         var bNewAlert = true;
         if(params.length > 1)
         {
            bNewAlert = params[1].split("=")[1];
         }
         Facebook.ItemAlert_Modal(bNewAlert);
      }
      else if(AjaxResponse == "success_remove_listing")
      { 
        if (gE("properties-drop-box"))
        {
            ChangeUserAction();
        }
        else
        {
            SuccessAction(false);
        }
//          caption = "Remove Lisitng";
//          html = '<p>Success!</p>';
//          html += '<p>This listing was removed from your Saved listings</p>';
//          html += '<div> <input type="button" value="Close" onclick="tb_remove();" /> </div>';
//          window.setTimeout("tb_remove();", 3000);
//      tb_updateHTML(caption, html, width, height);
      window.setTimeout("tb_remove();", 4000);
      }    
      else if(AjaxResponse == "success_remove_article")
      { 
          SuccessAction(false);
//          caption = "Remove Article";
//          html = ' <p>Success!</p>';
//          html += ' <p>This article was removed from your Saved list</p>';
//          html += ' <div> <input type="button" value="Close" onclick="tb_remove();" /> </div>';
//      tb_updateHTML(caption, html, width, height);
      window.setTimeout("tb_remove();", 4000);
      }  
      else if(AjaxResponse == "success_remove_video")
      { 
          SuccessAction(false);
//          caption = "Remove Video";
//          html = ' <p>Success!</p>';
//          html += ' <p>This video was removed from your Saved list</p>';
//          html += ' <div> <input type="button" value="Close" onclick="tb_remove();" /> </div>';
 //     tb_updateHTML(caption, html, width, height);
      window.setTimeout("tb_remove();", 4000);
      }      
      else if(AjaxResponse == "success_remove_search")
      { 
         SuccessAction(false);
//         caption = "Remove Search";
//         html = ' <p>Success!</p>';
//         html += ' <p>This search was removed from your Saved list</p>';
//         html += ' <div> <input type="button" value="Close" onclick="tb_remove();" /> </div>';
//      tb_updateHTML(caption, html, width, height);
      window.setTimeout("tb_remove();", 5000);
      }
      else if (AjaxResponse.indexOf("search_limit_exceeded") > -1)
      { 
         caption = "Save Search";
         width = 250;
         height = 200;
         var params = AjaxResponse.split(":");
         var searchname = "No Search Name";
         var emailalert = false;
         if(params.length > 2)
         {
            searchname = params[1].split("=")[1];
            emailalert = params[2].split("=")[1].toLowerCase();
         }
//         
//           html = '<div id="ten_searches">';
//         html += ' <p class="b">You\'ve reached the maximum of 10 saved searches.</p>';
//         html += ' <p> Do you want to remove the oldest saved search and save this search? </p>';
//         html += ' <div id="tb_tbns"><div id="ten_btns_wrapper"> <input type="button" value="Save" class="save_search_btn" onclick="ForcedAddSearch(\'' + searchname + '\',' + emailalert + ');" /> ';
//         html += ' <span class="or">OR</span><a href="javascript:void(0);" onclick="tb_remove();" class="not_save">Do Not Save</a></div> </div></div>';
//      tb_updateHTML(caption, html, width, height);
          Facebook.Modal_Close()
        window.setTimeout(function(){  
            Facebook.MaxLimit();
         }, 
          5000) 
      }
      else if (AjaxResponse.indexOf("not signed in") != -1)
      { 
        bmarkType = ""
        
        if(AjaxResponse.indexOf(":") != -1)
        {
            bmarkType = AjaxResponse.split(":")[1];
        }
        
       if(FB.getAuthResponse() == null)
        {    
            Facebook.Bookmark_Login(bmarkType); 
        }
        else
        {
            Facebook.Bookmark_Modal(bmarkType);
        }

      }
      else if (AjaxResponse.indexOf("not activated") != -1)
      { 
         html = "Account activation is required to set listing alerts. You are registered but still need to activate using the activation link we sent you within the past 24 hours. Please check your email.";
         Facebook.Confirmation_Error_Modal(html, "Oops!");

         TimeOutModal = window.setTimeout(function(){
            Facebook.Modal_Close();
            Facebook.fadeOutBackground();
          }, 
          5000)   
      }
      else if (AjaxResponse == "error_action_listing")
      {       
         html = "We're sorry, but this listing was not saved to your account. Please try again later.";
         Facebook.Confirmation_Error_Modal(html, "Oops!");
         $("#properties-success").hide();
        
        if (gE("properties-drop-box"))
        {
            ChangeUserAction();
        }

         TimeOutModal = window.setTimeout(function(){
            Facebook.Modal_Close();
            Facebook.fadeOutBackground();
          }, 
          5000)   
      }
      else if (AjaxResponse == "maxlimit")
      {       
         html = "You have reached the maximum number of saved items. Please remove some if you wish to add more.";
        Facebook.Confirmation_Error_Modal(html, "Oops!");
        
         TimeOutModal = window.setTimeout(function(){
            Facebook.Modal_Close();
            Facebook.fadeOutBackground();
          }, 
          5000)   
      }
      
      else if (AjaxResponse == "error_action_search")
      {       
      width = 300;
         height = 115;
         html = "<div id='oops_save'><div id='not_signedin_hdr' class='clearfix'><h2>Oops!</h2><a href='javascript:void(0);' onclick='tb_remove();' class='close_tb'>close</a></div>";
         html += " <p>We're sorry, but this search was not saved to your account. Please try again later.</p>";
         html += '<div id="tb_tbns" class="clearfix"><a href="javascript:void(0);" onclick="tb_remove();" id="try_again">Please Try Again</a></div></div></div>';
      tb_updateHTML(caption, html, width, height);
      }
        else if (AjaxResponse == "error_action_article")
      {       
      width = 300;
         height = 115;
         html = "<div id='oops_save'><div id='not_signedin_hdr' class='clearfix'><h2>Oops!</h2><a href='javascript:void(0);' onclick='tb_remove();' class='close_tb'>close</a></div>";
         html += " <p>We're sorry, but this article was not saved to your account. Please try again later.</p>";
         html += '<div id="tb_tbns" class="clearfix"><a href="javascript:void(0);" onclick="tb_remove();" id="try_again">Please Try Again</a></div></div></div>';
      tb_updateHTML(caption, html, width, height);
      }
        else if (AjaxResponse == "error_action_video")
      {       
      width = 300;
         height = 115;
         html = "<div id='oops_save'><div id='not_signedin_hdr' class='clearfix'><h2>Oops!</h2><a href='javascript:void(0);' onclick='tb_remove();' class='close_tb'>close</a></div>";
         html += " <p>We're sorry, but this video was not saved to your account. Please try again later.</p>";
         html += '<div id="tb_tbns" class="clearfix"><a href="javascript:void(0);" onclick="tb_remove();" id="try_again">Please Try Again</a></div></div></div>';
      tb_updateHTML(caption, html, width, height);
      }
//      functionality to save from item page removed      
//       else if (AjaxResponse == "error_action_remove")
//      {       
//      width = 300;
//         height = 115;
//         html = "<div id='oops_save'><div id='not_signedin_hdr' class='clearfix'><h4>Oops!</h4><a href='javascript:void(0);' onclick='tb_remove();' class='close_tb'>close</a></div>";
//         html += " <p>We're sorry, but <span class='b'>"+ AjaxResponse.split('::')[1] + "</span> was not removed from your account. Please try again later.</p>";
//         html += '<div id="tb_tbns" class="clearfix"><a href="javascript:void(0);" onclick="tb_remove();" id="try_again">Please Try Again</a></div></div></div>';
//      tb_updateHTML(caption, html, width, height);
//      }
       else if (AjaxResponse == "error_action")
      {       
      width = 300;
         height = 115;
         html = "<div id='oops_save'><div id='not_signedin_hdr' class='clearfix'><h2>Oops!</h2><a href='javascript:void(0);' onclick='tb_remove();' class='close_tb'>close</a></div>";
         html += " <p>We were unable to complete your request. Please try again later.</p>";
         html += '<div id="tb_tbns" class="clearfix"><a href="javascript:void(0);" onclick="tb_remove();" id="try_again">Please Try Again</a></div></div></div>';
      tb_updateHTML(caption, html, width, height);
      }
      else if (AjaxResponse == "error_action_alert_listing")
      {
      }
      else
      {
        html = AjaxResponse;
        tb_updateHTML(caption, html, width, height);
        
      }
   }
   
   // Saves the search is user logged in otherwise creates temporary cookie.      
   function SaveSearch()
   {       
       if(IsAlreadySignedIn())
       {   
         Facebook.ShareSearch(GetSearchLocation(), SEOSection)       
         //tb_showhtml('', PersonalizationRoot + "AjaxCalls/SignIn.aspx?display=savesearch&islastaction=false&searchcriteria=" + GetSearchLocation() + "&width=350&height=190", false);
       }
       else
       {
         SaveSearchSubmit();
       // tb_show('You must be signed in to do that', PersonalizationRoot  + "AjaxCalls/SignIn.aspx?display=notsignedin&width=340&height=240", false);
       }
    }
    
    function SaveSearchSubmit()
    {
   
        var searchname = "No Search Name";
        var isalert = false;
        if(gE("SearchName") != undefined)
        {
            if(gE("SearchName").value == "")
            {
                gE("errmsg_savesearch").style.display="block"
                 $("#email_input").addClass("input-error");
                  $("#modal").addClass("modal-error");  
                gE("errmsg_savesearch").innerHTML = "Please enter a search name";
                
                return false;
            }
            if(gE("SearchName").value.indexOf("#&#") > -1)
            {
                gE("errmsg_savesearch").style.display="block"  
                  $("#email_input").addClass("input-error");
                  $("#modal").addClass("modal-error");  
              gE("errmsg_savesearch").innerHTML = "The search name cannot contain an #&#. Please change your search name.";
              return false;
            }
            else
            {
                gE("errmsg_savesearch").style.display="none"   
                searchname = gE("SearchName").value;
            }
        }
        if(gE("EmailAlert") != undefined)
        {
            isalert = gE("EmailAlert").checked;
        }
        var query = "SearchName=" + encodeURIComponent(searchname) + "&EmailAlert=" + isalert + "&SearchQuery=";
        if(PageCache.SEOPath != "")
        {
            //.replace(/\&/g,':');
             query += encodeURIComponent(PageCache.SEOPath); 
        }
        else
        {
           //.replace(/\&/g,':');
           query += encodeURIComponent(PageCache.QueryString); 
        }
        query += '&PathInfo='+ GetPageName();
        query += '&action=addsearch';
        query += '&bookmarkSection=search'
        $AJAX.GetForDelegate(UserOptionsDelegate, PersonalizationRoot + "AjaxCalls/My_Options.aspx?" + query); 
     //   tb_show('Search Name', PersonalizationRoot + "AjaxCalls/My_Options.aspx?width=340&height=240&" + query);
    }
    
    function UpdateSearchName(SearchId)
     {
        if(gE("new_searchname_" + SearchId).value == "")
        {
           gE("searchname_update_" + SearchId).innerHTML = "The search title cannot be empty. Please enter a search title.";
           gE("searchname_update_" + SearchId).style.display = 'block';
           return false;
        }
        
        if(gE("new_searchname_" + SearchId).value.indexOf("#&#") > -1)
        {
           gE("searchname_update_" + SearchId).innerHTML = "The search title cannot contain an #&#. Please change your search title.";
           gE("searchname_update_" + SearchId).style.display = 'block';
           return false;
        }        
        
           gE("searchname_update_"+SearchId).style.display = 'none';
           var newsearchname = gE("new_searchname_" + SearchId).value;
           var query = "NewSearchName=" + encodeURIComponent(newsearchname) + "&SearchId=" + SearchId;
            query += '&PathInfo='+ GetPageName() + '&action=updatesearchname';
           var strURL = PersonalizationRoot + "AjaxCalls/My_Options.aspx?" + query;
           //alert(strURL);
           $AJAX.GetForDelegate(Update_SearchNameDelegate, strURL); 
        
     }
     
     function Update_SearchNameDelegate(AjaxResponse)
     {        
        var searchId = AjaxResponse.split("::")[1];
        if(AjaxResponse.indexOf("success") > -1)
        {
            gE("orig_searchname_" + searchId).innerHTML = gE("new_searchname_" + searchId).value;
            Show_EditTitle(searchId, false);            
        }
        else if(AjaxResponse.indexOf("error") > -1)
        {        
            gE("searchname_update_"+searchId).innerHTML = "An unexpected error occured while trying to update your title. Please try again.";
            gE("searchname_update_"+searchId).style.display = 'block';
        }        
     }
     
     // reads the temporary cookie and saves the search in the database.
     function CompleteSearchNameSubmit()
     {
       if(gE("SearchName").value == "")
       {
          gE("errmsg_savesearch").innerHTML = "The search title cannot be empty. Please enter a search title.";
          return false;
       }
       
       if(gE("SearchName").value.indexOf("#&#") > -1)
       {
          gE("errmsg_savesearch").innerHTML = "The search name cannot contain an #&#. Please change your search name.";
          return false;
       }
       
          var querystring = "SearchName=" + encodeURIComponent(gE("SearchName").value) + "&EmailAlert=" + gE("EmailAlert").checked;
          querystring += '&PathInfo='+ GetPageName() + '&action=completelastaction'; 
        
          $AJAX.GetForDelegate(CompleteLastActionDelegate,   PersonalizationRoot + "AjaxCalls/Personalization.aspx?" + querystring);         
          // tb_show('Search Name', PersonalizationRoot + "AjaxCalls/Personalization.aspx?width=250&height=100&" + querystring);
     }
          
     function ForcedAddSearch(searchname, isalert)
     {
//        var searchname = "No Search Name";
//        var isalert = false;
//        if(gE("SearchName") != undefined)
//        {
//            searchname = gE("SearchName").value;
//        }
//        if(gE("EmailAlert") != undefined)
//        {
//            isalert = gE("EmailAlert").checked;
//        }
        var query = "SearchName=" + encodeURIComponent(searchname) + "&EmailAlert=" + isalert + "&SearchQuery=";         
        if(PageCache.SEOPath != "")
        {
           //.replace(/\&/g,':');
           query += encodeURIComponent(PageCache.SEOPath); 
        }
        else
        {
           //.replace(/\&/g,':');
           query += encodeURIComponent(PageCache.QueryString); 
        }
        query += '&action=forcedaddsearch&PathInfo='+ GetPageName();
      //  alert(query);
        $AJAX.GetForDelegate(UserOptionsDelegate, PersonalizationRoot + "AjaxCalls/My_Options.aspx?" + query); 
     }
     
//    function RemoveThisListing(listingId, address, IsPageRefresh)
//    { 
//        if(IsPageRefresh == undefined)
//        {
//            IsPageRefresh = false;
//        }
//        tb_showhtml('', PersonalizationRoot + "AjaxCalls/Remove.aspx?display=listing&height=130&width=300&id=" + listingId + "&IsPageRefresh=" + IsPageRefresh + "&add="+ address , false);
//    }
    
    function RemoveThisarticle(articleId,articleName, IsPageRefresh)
    {
     
        if(IsPageRefresh == undefined)
        {
            IsPageRefresh = false;
        }        
     tb_showhtml('Remove Article', PersonalizationRoot + "AjaxCalls/Remove.aspx?display=article&height=130&width=300&id=" + articleId + "&IsPageRefresh=" + IsPageRefresh + "&name=" + articleName, false);       
    }
    
    function RemoveThisvideo(videoId,videoName,IsPageRefresh)
    {  
        if(IsPageRefresh == undefined)
        {
            IsPageRefresh = false;
        }
     tb_showhtml('Remove Video', PersonalizationRoot + "AjaxCalls/Remove.aspx?display=video&height=130&width=300&id=" + videoId + "&IsPageRefresh=" + IsPageRefresh + "&name=" + videoName, false);
    }
    
    function RemoveThisSearch(searchId, SearchName,IsPageRefresh)
    { 
   
        if(IsPageRefresh == undefined)
        {
            IsPageRefresh = false;
        }
      tb_showhtml('Remove Search', PersonalizationRoot + "AjaxCalls/Remove.aspx?display=search&height=130&width=300&id=" + searchId + "&IsPageRefresh=" + IsPageRefresh +"&name="+ encodeURIComponent(SearchName), false);       
    }
    
    function RemoveAddAlert(searchId, isChecked)
    {
         AddRemoveEmailAlert(searchId);
    }

    function AddRemoveEmailAlert(Id)
    {
        var querystring = 'Id=' + Id + '&PathInfo='+ GetPageName() + '&action=addremovealert';
        var strURL = PersonalizationRoot + "AjaxCalls/My_Options.aspx?" + querystring;
        //tb_show('Add/Remove Alert', PersonalizationRoot  + "AjaxCalls/My_Options.aspx?height=130&width=340&" + querystring, false);
        //$AJAX.GetForDelegate(User_ActionDelegate, strURL);
        $AJAX.GetAsync(strURL);
    }

    function AddRemoveItemEmailAlert(IdItem, AlertChecked)
    {
        var querystring = 'Id=' + IdItem + '&EmailAlert='+ AlertChecked + '&action=addremoveitemalert';
        var strURL = PersonalizationRoot + "AjaxCalls/My_Options.aspx?" + querystring;
        //tb_show('Add/Remove Alert', PersonalizationRoot  + "AjaxCalls/My_Options.aspx?height=130&width=340&" + querystring, false);
        //$AJAX.GetForDelegate(User_ActionDelegate, strURL);
        $AJAX.GetAsync(strURL);
    }

    function RemoveItemFromList(Id, ItemType, IsPageRefresh)
    {    
        var querystring = "Id="+Id + "&ItemType=" + ItemType;
            querystring += '&PathInfo='+ GetPageName() + '&action=removeitem&IsPageRefresh=' + IsPageRefresh;
       // var strURL = "BASE.PersonalizationRootAjaxCalls/My_Options.aspx?" + querystring;
      // tb_update(PersonalizationRoot + "AjaxCalls/My_Options.aspx?" + querystring, 300, 100);
      $AJAX.GetForDelegate(UserOptionsDelegate, PersonalizationRoot + "AjaxCalls/My_Options.aspx?" + querystring); 
     }

  // reloads the page or updates the div tags depending on the page.
   function SuccessAction(IsPageRefresh)
   {
    // if(IsPageRefresh)
       var url = window.location.href.split('?')[0];      
       if(url.indexOf(PersonalizationRoot) > -1)
         {
            window.location.reload(true);           
         }
         else
         {
            ChangeUserAction();
    //       tb_remove();
         }  
   }
   
   // completes the action if any temporary cookie exists upon page load.
   function CompleteUserAction(tc_pageurl, CheckSignIn)
   {  
        if(CheckSignIn == undefined)
        {
            CheckSignIn = true;
        }
        
        var IsSignedIn = true;
        
        if(CheckSignIn)
        {
            IsSignedIn = IsAlreadySignedIn();
        }
        
        if(window.location.href == tc_pageurl && IsSignedIn)
        {
           if(readTempCookie("issignin") == "true")
           {
            SignInOrRegister = "SignIn";
           }
           else if(readTempCookie("issignin") == "false")
           {
            SignInOrRegister = "Register";
           }
           var querystring = 'action=completelastaction&PathInfo='+ GetPageName() + '&NameCookie='+ readTempCookie("iname"); 
          
      //  alert("here 1");
        
           $AJAX.GetForDelegate(CompleteLastActionDelegate,   PersonalizationRoot + "AjaxCalls/Personalization.aspx?" + querystring);
           // alert(PersonalizationRoot  + "AjaxCalls/Personalization.aspx?width=250&height=100&" + querystring);
          // tb_show('user action', PersonalizationRoot + "AjaxCalls/Personalization.aspx?width=250&height=100&" + querystring);
          // window.setTimeout(function(){ ChangeUserAction();},500);
          // ChangeUserAction();
        }
   }        
   
   // completes the search action if any temporary cookie exists upon page load.  
   function CompleteSearchUserAction(tc_pageurl)
   {         
       if(window.location.href == tc_pageurl && IsAlreadySignedIn())
       {    
         if(readTempCookie("issignin") == "true")
         {
          SignInOrRegister = "SignIn";
          Facebook.ShareSearch(GetSearchLocation(), SEOSection)
          //tb_showhtml('Save this search', PersonalizationRoot + "AjaxCalls/SignIn.aspx?display=savesearch&Flag=S&islastaction=true&searchcriteria=" + GetSearchLocation() + "&width=350&height=190", false);                     
         }
         else if(readTempCookie("issignin") == "false")
         {
           SignInOrRegister = "Register";
           Facebook.ShareSearch(GetSearchLocation(), SEOSection)
          //tb_showhtml('Save this search', PersonalizationRoot + "AjaxCalls/SignIn.aspx?display=savesearch&Flag=R&islastaction=true&searchcriteria=" + GetSearchLocation() + "&width=350&height=190", false);                     
         }
       } 
   }
   
   function CompleteBMPAction(tc_pageurl)
   {       
      if(window.location.href == tc_pageurl && IsAlreadySignedIn())
      {
          switch(getTempCookie("uact"))
          {
            case "BMPViewList": Facebook.CompleteTempCAction("lastaction_bmpviewlist");break;
            case "BMPShare": Facebook.CompleteTempCAction("lastaction_bmpshare::" + getTempCookie("shrtype"));break;
            case "BMPZoneShare": Facebook.CompleteTempCAction("lastaction_bmpagentshare::" + getTempCookie("name") + "::" + getTempCookie("email"));break;
          }
      }
    }
    
   function CompleteLastActionDelegate(AjaxResponse)
   {
        var html = "";
        var width= 280;
        var height = 185;
        if (AjaxResponse.indexOf("search_limit_exceeded") > -1)
          { 
           // if the user exceeds the saves searches limit, ask the user whether he wants to remove the oldest search and add the current search.
           // reads the search name and isemailalert fromt he ajax response.
             caption = "Save Search";
             width = 250;
             height = 145;
             var params = AjaxResponse.split(":");
             var searchname = "No Search Name";
             var emailalert = false;
             var address="";
             if(params.length > 2)
             {
                searchname = params[1].split("=")[1];
                emailalert = params[2].split("=")[1].toLowerCase();
             }
         
               html = '<div id="ten_searches">';
         html += ' <p class="b">You\'ve reached the maximum of 10 saved searches.</p>';
         html += ' <p> Do you want to remove the oldest saved search and save this search? </p>';
         html += ' <div id="tb_tbns"><div id="ten_btns_wrapper"> <input type="button" value="Save" class="save_search_btn" onclick="ForcedAddSearch(\'' + searchname + '\',' + emailalert + ');" /> ';
         html += ' <span class="or">OR</span><a href="javascript:void(0);" onclick="tb_remove();" class="not_save">Do Not Save</a></div> </div></div>';
        }
        else
        {                     
            var param= AjaxResponse.split("::");     
            var actiontype = param[0].split("&")[0];
            if(actiontype == "type=search")
            { 
                width = 250;
                height = 130;
                caption = "Save Search";
                html = '<div id="not_signedin_hdr" class="clearfix"><h2>Success!</h2></div>';
                html += '<div id="success_saved" class="clearfix">This search' + param[0].split("&")[1] ;
                if(SignInOrRegister == "Register")
                { 
                  html += '<p>Please check your e-mail for important <span class="b">MyFrontDoor</span> information.</p>'; 
                }
            }
            else
            {   
                caption = "User Action";   
                html = '<div id="not_signedin_hdr" class="clearfix">';
                if(SignInOrRegister == "SignIn")
                { 
                width= 300;
                height = 100;                 
                html+='<h2>Welcome Back!</h2><a href="javascript:void(0);" onclick="tb_remove();" class="close_tb">close</a></div>';
                html+= '<div id="welcome_back">';
                }
                else
                {                
                html = "<span>Thanks for registering!  Check your email for a confirmation of your registration.</span>";  
                }                        
                html +=  '<span class="b"><br/><br/>' + param[1] + ' ' + param[0].split("&")[1] + '</span>';     
            }   
            ChangeUserAction(); 
        } 
        Facebook.Confirmation_Modal(html);
          window.setTimeout(function(){
            Facebook.Modal_Close();
            Facebook.fadeOutBackground();
          }, 
          5000) 
       
   }
   
   // removes the temporary cookie if any exists.
   function RemoveLastAction()
   {
       $AJAX.GetAsync(PersonalizationRoot + "AjaxCalls/Personalization.aspx?action=removelastaction");
   }
   
   // reloads the saved items and saved searches pages upon sorting and paging. 
   function ReQuery(param_key, param_value)
   {   
     var url = window.location.href.split("?");
     if(url.length > 1)
     {
         var UGen = new UrlGen(url[1]);
         UGen.RemoveParam(param_key);
         UGen.AddParam(param_key, param_value);
         window.location.href = url[0] + "?" + UGen.ToString();
     }
     else
     {
        window.location.href = url[0] + "?" + param_key + "=" + param_value;
     }
   }
   
   // gets the current page name without the http://
   function GetPageName()
   {
        var url = window.location.href;
            if(url.indexOf("http://") > -1)
            {
                url = url.substr(7);
            }
        if(url.indexOf("#") > -1)
        {         
          var arr = url.split("#");
          url = window.location.hostname + arr[arr.length-1];  
        }
        
        return url;
   }
   
   function MyPagingQuery(QueryString)
   {   
       window.location.href = window.location.href.split("?")[0] + "?" + QueryString;    
   }
  
  function GetSearchLocation()
  {     
        var location="";
        //to get zipcode,state for saving user search ....mamta/////
        var url= GetPageName().split('/');
         if(url.length==5 && IsNumeric(url[4]))
         {                   
           location=(url[3]+" "+url[4]).toUpperCase();
         }
         else
        {        
         location=SearchCriteria;
        }
        return escape(location);
  }
  
  // sets the default values when the thickbox open's
function LoadPageDefaults()
{
     if(gE("email") != undefined)
     {
       gE("email").focus();
     }
     if(gE("SearchName") != undefined)
     {
       gE("SearchName").focus();
     }
     if(gE("Email_Add") != undefined)
     {
       gE("Email_Add").focus();
     }
     if(gE("flName") != undefined)
     {
       gE("flName").focus();
     }
}































