//========================================================
// 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;
    }
}





//========================================================
// 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 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)
{
    if(flag)
    {
        gE("loggedin").style.display = 'block';
        gE("notloggedin").style.display = 'none';
        SignInOrRegister = "SignIn"
        //gE("displayName").style.display = 'block';
    }
    else
    {
        gE("loggedin").style.display = 'none';
        gE("notloggedin").style.display = 'block';
        SignInOrRegister = "";
        //gE("displayName").style.display = 'none';
    }
    // gE("displayName").innerHTML = "Welcome,<br /> " + DisplayName();
}





//========================================================
// 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 (typeof document.body.style.maxHeight === "undefined") //if IE 6
    {
        $("body","html").css({height: "100%", width: "100%"});
        $("html").css("overflow","hidden");
        if (document.getElementById("TB_HideSelect") === null) //iframe to hide select elements in ie6
        {
            $("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
            $("#TB_overlay").click(tb_remove);
        }
    }
    else //all others
    {
        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="";}
    $("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>"); //add loader to the page
    $('#TB_load').show(); //show loader
		
    TB_WIDTH = (Width*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
    TB_HEIGHT = (Height*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
    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){ 	
        if (e == null) // ie
        { 
            keycode = event.keyCode;
        }
        else // mozilla
        { 
            keycode = e.which;
        }
        if(keycode == 27) // close
        {
            tb_remove();
        }
    };		
}
 
function tb_position_gt(gt_WIDTH)
{
    $("#TB_window").css({marginLeft: '-' + parseInt((gt_WIDTH / 2),10) + 'px', width: gt_WIDTH});
	if ( !(jQuery.browser.msie && typeof XMLHttpRequest == 'function')) { // take away IE6
		$("#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(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_show('', PersonalizationRoot + "AjaxCalls/SignIn.aspx?display=login&height=285&width=310&emailadd=" + gE("email").value, false); 
        }
        else
        {
            tb_show('', PersonalizationRoot + "AjaxCalls/SignIn.aspx?display=login&height=285&width=310", false); 
        }
    }
    else if (gE("Email_Add")!=null)
    {  
        tb_show('', 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");   
}



                  
function SignOutDelegate(AjaxResponse)
{
    ShowLoggedIn(false);
    if(AjaxResponse != "success") // || AjaxResponse.indexOf("has been saved") > -1
    {
        window.location.reload(true); 
    }       
    else
    {
        var url = window.location.href.split('?')[0];
        if(url.indexOf(PersonalizationRoot) > -1)
        {
            window.location.href = PersonalizationRoot;
        }
        else
        {
            ChangeUserAction();
        } 
    }
}





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);
            }
            else if(formID=="forgot_pw_form")
            {
                GetPassword();                 
            }
            else
            {
                ValidateEmailFriend(formID);
            }
        }
        else
        {
            SaveSearchSubmit();
        }
    }
    else
    {
        return false;
    }
}





function SignInSubmit(formID)
{
    if(ValidateSignIN(formID))
    {                   
        var frm = document.forms[formID]; 
        var querystring = "email=" + frm.email.value + "&pwd=" + frm.password.value + "&rememberme=" + frm.remember_me.checked;

        if ((GetPageName().indexOf("sign_up.aspx") > -1) || (GetPageName().indexOf("default.aspx") > -1))
        {
            querystring += '&PathInfo=signuppage';
        }
        else
        {
            querystring += '&PathInfo='+ GetPageName();
        }
        querystring += '&NameCookie='+ getTempCookie("iname")+ '&action=sign_in'; // to differentiate between signin, signup and forgot password actions in Personalization.aspx page.
        
        var strURL = PersonalizationRoot + "AjaxCalls/Personalization.aspx?" + querystring;                  
          
        $AJAX.GetForDelegate(SignInResultDelegate, strURL);
         
        // tb_show("<%=BASE.PersonalizationRoot %>AjaxCalls/Personalization.aspx?width=340&height=200&" + querystring, false)
    }
    else
    {
        return false;
    }
}





function SignInResultDelegate(AjaxResponse)
{
    if(AjaxResponse == "success")  // Signed in successfully without any action pending.
    {
        ShowLoggedIn(true);  
        ChangeUserAction();
        tb_remove();
    }
    else if(AjaxResponse.indexOf("pageredirect=") > -1)
    {
        //window.location.href = "http://" + AjaxResponse.split("=")[1];
        window.location.href = AjaxResponse.split("=")[1];
    }
    else if(AjaxResponse == "lastaction_addsearch") // Signed in but still adding the search action is pending.
    {                
        ShowLoggedIn(true);
        if(SignInOrRegister == "SignIn")
        {
            tb_show('Save this search', PersonalizationRoot + "AjaxCalls/SignIn.aspx?width=350&height=210&display=savesearch&Flag=S&islastaction=true&searchcriteria=" + escape(GetSearchLocation()), false);
        }
        else
        {
            tb_show('Save this search', PersonalizationRoot + "AjaxCalls/SignIn.aspx?width=350&height=210&display=savesearch&Flag=R&islastaction=true&searchcriteria=" + escape(GetSearchLocation()), false);
        }  
    }
    else if(AjaxResponse.indexOf("lastaction_") > -1) // Signed in but still some action is pending.
    {          
        var message=AjaxResponse.split("::");
        tb_update(null, 300, 100) ;
        
        var html =  '<div id="personalization_tb_hd">';            
            html +=     '<h2>Welcome Back!</h2>';
            html +=     '<div class="close"><a href="javascript:void(0);" onclick="tb_remove();">close</a></div>';
            html += '</div>';
            html += '<div class="personalization_tb_body">';         
            html +=     '<p><strong>'+ message[1] + '</strong>' + message[0].split("_")[1] +'</p>';
            html += '</div>';
            html += '<div id="personalization_tb_footer">';
            html +=     '<a href="javascript:void(0);" onclick="tb_remove();" class="btn">Ok</a>';
            html += '</div>';
        
        gE("TB_ajaxContent").innerHTML = html;
        ShowLoggedIn(true);  
        ChangeUserAction();
    }
    else // Unexpected error occured while signing in.
    {
        //var html = AjaxResponse;
        //html += '<div> <input type="button" value="Close" onclick="window.location.reload(true);" /> </div>';
        gE("error").style.display = 'block';
        gE("error").innerHTML = AjaxResponse;
        //UserFormDelegate(html);
        //gE("TB_ajaxContent").innerHTML = html;
    }
}




   
function ForgotPassword(flag)
{
    if(IsDefaultPage())
    {
        tb_show("", PersonalizationRoot + "AjaxCalls/SignIn.aspx?display=forgotpassword&height=230&width=310");   
    }
    else
    {
        if(flag)
        {
            tb_show("", PersonalizationRoot + "AjaxCalls/SignIn.aspx?display=forgotpassword&height=230&width=310");   
        }
        else
        {
            tb_update(PersonalizationRoot + "AjaxCalls/SignIn.aspx?display=forgotpassword", "310", "230");   
        }
    }
}





function GetPassword()
{
    if(validateLoginEmail(gE("Email_Add"), gE("emailErr"),""))
    {
        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);
    }
    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="personalization_tb_hd">';            
        html +=     '<h2>Password Sent</h2>';
        html +=     '<div class="close"><a href="javascript:void(0);" onclick="tb_remove();">close</a></div>';
        html += '</div>';
        html += '<div class="personalization_tb_body">';         
        html +=     '<p>Your password was just sent to your e-mail.</p>';
        html += '</div>';
        html += '<div id="personalization_tb_footer">';
        html +=     '<a href="javascript:void(0);" onclick="SignIn();" class="btn">Sign In Now</a>';
        html +=     '<span>or</span>';
        html +=     '<a href="javascript:void(0);" onclick="javascript:tb_remove();">Do Not Sign In Now</a>';
        html += '</div>';

        gE("forgot_pw_result").innerHTML = html;    
    }
    else
    {           
        html = AjaxResponse;
        var btnhtml= '<a href="' + PersonalizationRoot + 'sign_up.aspx" class="btn">Sign Up</a> <span>or</span> <a href="javascript:ForgotPassword(false);" class="btn">Try Again</a>';          
        gE("emailNotFoundErr").style.display = 'block';
        gE("emailErr").style.display = 'none';
        gE("emailNotFoundErr").innerHTML = html;
        gE("personalization_tb_footer").innerHTML=btnhtml;
    }
}





// shows or hides the list of saved items and saved searches and links to those pages.
function show_personalization_list()
{
    var html= "";
    /*
    ------------------------------------------------------------
    Category should appear in list if it is not 0---mamta
    ------------------------------------------------------
    */
    if(readListingCountPersCookie()!=0)
    {      
        html += '<li><a href="' + PersonalizationRoot + 'saved_listings.aspx">Saved Listings ('+ readListingCountPersCookie() + ')</a></li>';
    }
    if(readSearchCountPersCookie()!=0)
    {      
        html += '<li><a href="' + PersonalizationRoot + 'saved_searches.aspx">Saved Searches ('+ readSearchCountPersCookie() + ')</a></li>';
    }
    //if(readArticleCountPersCookie()!=0)
    //{
        //html +=  '<li><a href="' + PersonalizationRoot + 'saved_items.aspx">Articles ('+ readArticleCountPersCookie() + ')</a></li>';
    //}
    //if( readVideoCountPersCookie ()!=0)
    //{          
    //  html +=  '<li><a href="' + PersonalizationRoot + 'saved_video.aspx">Videos ('+ readVideoCountPersCookie () + ')</a></li>';
    //}         
                  
    if(html!="")
    {
        gE("personalization_items").className = "open";
        gE("personalization_nav_close").style.display = "block";
    }
    else
    {
        gE("personalization_items").className = "";
        gE("personalization_nav_close").style.display = "none";
    }
    gE("personalization_items_list").innerHTML = html;
}





function close_personalization_list()
{
    gE("personalization_items").className = "";
    gE("personalization_nav_close").style.display = "none";
}





///////////// Validations start
   
// Validation for email address.
function validateLoginEmail(emailField, emErr, message)
{
    if (fieldHasValue(emailField) && validEmailField(emailField))
    {
        return true;
    }
    else
    {
        emErr.style.display='block';
        //if(gE("eml"))
        //{
            //gE("eml").style.color= '#A41D21';
        //}
            
        if(!fieldHasValue(emailField))
        {
            emErr.innerHTML = "Please enter your e-mail address.";
        }
        else
        {
            if(message != "")
            {
                emErr.innerHTML = message; //"*Not a valid e-mail format.";
            }
        }
        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
    var regex3 = /[^0-9a-zA-Z]/g;   // should only contain numbers and letters

    if ( fieldHasValue(pwdField) && fieldValue.length > 5 && !regex3.test(fieldValue))
    {
        pwdErr.style.display='none';
        return true;
    }
    else
    {
        pwdErr.style.display='block';
        //document.getElementById("pw").style.color= '#A41D21';
            
        if(!fieldHasValue(pwdField))
        {
            pwdErr.innerHTML = "Please enter your password.";
        }
        else
        {
            pwdErr.innerHTML = "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 = document.getElementById("emailErrLogin");
    var pwdErr = document.getElementById("pwdErrLogin");
    var arrErrSum = new Array();
    var firstErrField;
        
    emErr.style.display = 'none';
    //gE("eml").style.color = '#575744';
    pwdErr.style.display = 'none';
    //gE("pw").style.color = '#575744';
    gE("error").style.display = 'none';
    
    //email
    if (!validateLoginEmail(frm.email, emErr, "Please check the format of your e-mail address and re-enter. (i.e. joe@domain.com)."))
    {
        //arrErrSum[arrErrSum.length]= "<li>Email Address</li>";
            
        if (firstErrField==undefined)
        {
            firstErrField = frm.email;
        }
        isValidForm = false;
    }
        
    //password and confirm
    if (!validateLoginPassword(frm.password, pwdErr))
    {
        //arrErrSum[arrErrSum.length]= "<li>Password / Confirm Password</li>";
        if (firstErrField==undefined)
        {
            firstErrField = frm.password;
        }
        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 UserOptionsDelegate(AjaxResponse)
    {
        var html = "";
        var caption = "";
        var width = 250;
        var height = 120;     
        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();  
            caption = "Save Listing";
            
            html =  '<div id="personalization_tb_hd">';
            html +=     '<h2>Success!</h2>';
            html += '</div>';
            html +=  '<div class="personalization_tb_body">';
            html +=     '<p><strong>'+ returnVal +'</strong> was saved to your account.</p>';
            html += '</div>';
            html += '<div id="personalization_tb_footer">';
            html +=     '<a href="javascript:void(0);" onclick="tb_remove();" class="btn">Ok</a>';
            html += '</div>';
            
            tb_updateHTML(caption, html, width, height);
        }

        else if (AjaxResponse.indexOf("success_add_article")!=-1)
        {
            ChangeUserAction(); 
            caption = "Save Article";
            
            html =  '<div id="personalization_tb_hd">';
            html +=     '<h2>Success!</h2>';
            html += '</div>';
            html +=  '<div class="personalization_tb_body">';
            html +=     '<p><strong>'+ returnVal +'</strong> was saved to your account.</p>';
            html += '</div>';
            html += '<div id="personalization_tb_footer">';
            html +=     '<a href="javascript:void(0);" onclick="tb_remove();" class="btn">Ok</a>';
            html += '</div>';
            
            tb_updateHTML(caption, html, width, height);
        }

        else if (AjaxResponse.indexOf("success_add_video") != -1)
        {
            ChangeUserAction();
            caption = "Save Video";
            
            html =  '<div id="personalization_tb_hd">';
            html +=     '<h2>Success!</h2>';
            html += '</div>';
            html +=  '<div class="personalization_tb_body">';
            html +=     '<p><strong>'+ returnVal +'</strong> was saved to your account.</p>';
            html += '</div>';
            html += '<div id="personalization_tb_footer">';
            html +=     '<a href="javascript:void(0);" onclick="tb_remove();" class="btn">Ok</a>';
            html += '</div>';
            
            tb_updateHTML(caption, html, width, height);
        }

        else if(AjaxResponse.indexOf("success_add_search")!=-1)
        {
            ChangeUserAction();
            caption = "Save Search";
            
            html =  '<div id="personalization_tb_hd">';
            html +=     '<h2>Success!</h2>';
            html += '</div>';
            html +=  '<div class="personalization_tb_body">';
            html +=     '<p>This search was saved to your account.</p>';
            html += '</div>';
            html += '<div id="personalization_tb_footer">';
            html +=     '<a href="javascript:void(0);" onclick="tb_remove();" class="btn">Ok</a>';
            html += '</div>';
            
            tb_updateHTML(caption, html, width, height);
        }

        else if(AjaxResponse == "success_remove_listing")
        {
            SuccessAction(false);
            //caption = "Remove Lisitng";
            //html =  '<div id="personalization_tb_hd">';
            //html +=     '<h2>Success!</h2>';
            //html += '</div>';
            //html +=  '<div class="personalization_tb_body">';
            //html +=     '<p>This saved listing was removed from your account.</p>';
            //html += '</div>';
            //html += '<div id="personalization_tb_footer">';
            //html +=     '<a href="javascript:void(0);" onclick="tb_remove();" class="btn">Ok</a>';
            //html += '</div>';
            //tb_updateHTML(caption, html, width, height);
        }

        else if(AjaxResponse == "success_remove_article")
        {
            SuccessAction(false);
            //caption = "Remove Article";
            //html =  '<div id="personalization_tb_hd">';
            //html +=     '<h2>Success!</h2>';
            //html += '</div>';
            //html +=  '<div class="personalization_tb_body">';
            //html +=     '<p>This saved article was removed from your account.</p>';
            //html += '</div>';
            //html += '<div id="personalization_tb_footer">';
            //html +=     '<a href="javascript:void(0);" onclick="tb_remove();" class="btn">Ok</a>';
            //html += '</div>';
            //tb_updateHTML(caption, html, width, height);
        }

        else if(AjaxResponse == "success_remove_video")
        { 
            SuccessAction(false);
            //caption = "Remove Video";
            //html =  '<div id="personalization_tb_hd">';
            //html +=     '<h2>Success!</h2>';
            //html += '</div>';
            //html +=  '<div class="personalization_tb_body">';
            //html +=     '<p>This saved video was removed from your account.</p>';
            //html += '</div>';
            //html += '<div id="personalization_tb_footer">';
            //html +=     '<a href="javascript:void(0);" onclick="tb_remove();" class="btn">Ok</a>';
            //html += '</div>';
            //tb_updateHTML(caption, html, width, height);
        }      

        else if(AjaxResponse == "success_remove_search")
        { 
            SuccessAction(false);
            //caption = "Remove Search";
            //html =  '<div id="personalization_tb_hd">';
            //html +=     '<h2>Success!</h2>';
            //html += '</div>';
            //html +=  '<div class="personalization_tb_body">';
            //html +=     '<p>This saved search was removed from your account.</p>';
            //html += '</div>';
            //html += '<div id="personalization_tb_footer">';
            //html +=     '<a href="javascript:void(0);" onclick="tb_remove();" class="btn">Ok</a>';
            //html += '</div>';
            //tb_updateHTML(caption, html, width, height);
        }

        else if (AjaxResponse.indexOf("search_limit_exceeded") > -1)
        { 
            caption = "Save Search";
            width = 300;
            height = 150;
            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="personalization_tb_hd">';
            html +=     '<h2>We\'re Sorry...</h2>';
            html += '</div>';
            html += '<div class="personalization_tb_body">';
            html +=     '<p>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>';
            html += '<div id="personalization_tb_footer">';
            html +=     '<input type="button" value="Save" class="save_search_btn" onclick="ForcedAddSearch(\'' + searchname + '\',' + emailalert + ');" />';
            html +=     '<span>or</span>';
            html +=     '<a href="javascript:void(0);" onclick="tb_remove();" class="not_save">Do Not Save</a>';
            html += '</div>';
            
            tb_updateHTML(caption, html, width, height);
        }

        else if (AjaxResponse == "not signed in")
        { 
            $AJAX.GetForDelegate(NotSignedInDelegate, PersonalizationRoot + "AjaxCalls/SignIn.aspx?display=notsignedin");
        }

        else if (AjaxResponse == "error_action_listing")
        {       
            width = 300;
            height = 115;
         
            html =  '<div id="personalization_tb_hd">';
            html +=     '<h2>We\'re sorry...</h2>';
            html += '</div>';
            html += '<div class="personalization_tb_body">';
            html +=     '<p>This listing was not saved to your account. We\'ve notified our team to look into this ASAP.</p>';
            html += '</div>';
            html += '<div id="personalization_tb_footer">';
            html +=     '<a href="javascript:void(0);" onclick="tb_remove();" class="btn">Please Try Again</a>';
            html += '</div>';
            
            tb_updateHTML(caption, html, width, height);
        }

        else if (AjaxResponse == "error_action_search")
        {       
            width = 300;
            height = 115;
         
            html =  '<div id="personalization_tb_hd">';
            html +=     '<h2>We\'re sorry...</h2>';
            html += '</div>';
            html += '<div class="personalization_tb_body">';
            html +=     '<p>This search was not saved to your account. We\'ve notified our team to look into this ASAP.</p>';
            html += '</div>';
            html += '<div id="personalization_tb_footer">';
            html +=     '<a href="javascript:void(0);" onclick="tb_remove();" class="btn">Please Try Again</a>';
            html += '</div>';
            
            tb_updateHTML(caption, html, width, height);
        }

        else if (AjaxResponse == "error_action_article")
        {       
            width = 300;
            height = 115;
         
            html =  '<div id="personalization_tb_hd">';
            html +=     '<h2>We\'re sorry...</h2>';
            html += '</div>';
            html += '<div class="personalization_tb_body">';
            html +=     '<p>This article was not saved to your account. We\'ve notified our team to look into this ASAP.</p>';
            html += '</div>';
            html += '<div id="personalization_tb_footer">';
            html +=     '<a href="javascript:void(0);" onclick="tb_remove();" class="btn">Please Try Again</a>';
            html += '</div>';
            
            tb_updateHTML(caption, html, width, height);
        }

        else if (AjaxResponse == "error_action_video")
        {       
            width = 300;
            height = 115;
         
            html =  '<div id="personalization_tb_hd">';
            html +=     '<h2>We\'re sorry...</h2>';
            html += '</div>';
            html += '<div class="personalization_tb_body">';
            html +=     '<p>This video was not saved to your account. We\'ve notified our team to look into this ASAP.</p>';
            html += '</div>';
            html += '<div id="personalization_tb_footer">';
            html +=     '<a href="javascript:void(0);" onclick="tb_remove();" class="btn">Please Try Again</a>';
            html += '</div>';
            
            tb_updateHTML(caption, html, width, height);
        }

        //else if (AjaxResponse == "error_action_remove")
        //{       
        //  width = 300;
        //  height = 115;
        //  html =  '<div id="personalization_tb_hd">';
        //  html +=     '<h2>We\'re sorry...</h2>';
        //  html += '</div>';
        //  html += '<div class="personalization_tb_body">';
        //  html +=     '<p><strong>"+ AjaxResponse.split('::')[1] + "</strong> was not removed from your account. We\'ve notified our team to look into this ASAP.</p>';
        //  html += '</div>';
        //  html += '<div id="personalization_tb_footer">';
        //  html +=     '<a href="javascript:void(0);" onclick="tb_remove();" class="btn">Please Try Again</a>';
        //  html += '</div>';
        //  tb_updateHTML(caption, html, width, height);
        //}

        else if (AjaxResponse == "error_action")
        {
            width = 300;
            height = 115;
         
            html =  '<div id="personalization_tb_hd">';
            html +=     '<h2>We\'re sorry...</h2>';
            html += '</div>';
            html += '<div class="personalization_tb_body">';
            html +=     '<p>We were unable to complete your request. We\'ve notified our team to look into this ASAP.</p>';
            html += '</div>';
            html += '<div id="personalization_tb_footer">';
            html +=     '<a href="javascript:void(0);" onclick="tb_remove();" class="btn">Please Try Again</a>';
            html += '</div>';
            
            tb_updateHTML(caption, html, width, height);
        }
        
        else
        {
            html = AjaxResponse;
            tb_updateHTML(caption, html, width, height);
        }
    }
    
    
    
    
     
    function SaveSearch()
    {       
        if(IsAlreadySignedIn())
        {                  
            tb_show('', PersonalizationRoot + "AjaxCalls/SignIn.aspx?display=savesearch&islastaction=false&searchcriteria=" + escape(GetSearchLocation()) + "&width=350&height=190", false);
        }
        else
        {
            SaveSearchSubmit();
        }
    }
    
    
    
    
    
    function SaveSearchSubmit()
    {
        var searchname = "No Search Name";
        var isalert = false;
        
        if(gE("SearchName") != undefined)
        {
            if(gE("SearchName").value == "")
            {
                gE("errmsg_savesearch").style.display = "block";
                gE("errmsg_savesearch").innerHTML = "Please enter a search name.";
                return false;
            }
            if(gE("SearchName").value.indexOf("#&#") > -1)
            {
                gE("errmsg_savesearch").style.display = "block";
              gE("errmsg_savesearch").innerHTML = "Your search name cannot contain the following string '#&#'.";
              return false;
            }
            else
            {
                searchname = gE("SearchName").value;
            }
        }
        
        if(gE("EmailAlert") != undefined)
        {
            isalert = gE("EmailAlert").checked;
        }
        
        var query = "SearchName=" + encodeURIComponent(searchname) + "&EmailAlert=" + isalert + "&SearchQuery=";

        if(PageCache.SEOPath != "")
        {
            query += encodeURIComponent(PageCache.SEOPath); //.replace(/\&/g,':');
        }
        else
        { 
           query += encodeURIComponent(PageCache.QueryString); //.replace(/\&/g,':');
        }

        query += '&PathInfo='+ GetPageName();
        query += '&action=addsearch';
        
        $AJAX.GetForDelegate(UserOptionsDelegate, PersonalizationRoot + "AjaxCalls/My_Options.aspx?" + query); 
    }
     
     
     
     
     
    function CompleteSearchNameSubmit()
    {
        if(gE("SearchName").value == "")
        {
            gE("errmsg_savesearch").style.display = "block";
            gE("errmsg_savesearch").innerHTML = "Please enter a search name.";
            return false;
        }
       
        if(gE("SearchName").value.indexOf("#&#") > -1)
        {
            gE("errmsg_savesearch").style.display = "block";
            gE("errmsg_savesearch").innerHTML = "Your search name cannot contain the following string '#&#'.";
            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);
    }





    function UpdateSearchName(SearchId)
    {
        if(gE("new_searchname_" + SearchId).value == "")
        {
            gE("searchname_update_" + SearchId).innerHTML = "Please enter a search name.";
            gE("searchname_update_" + SearchId).style.display = 'block';
            return false;
        }
        
        if(gE("new_searchname_" + SearchId).value.indexOf("#&#") > -1)
        {
           gE("searchname_update_" + SearchId).innerHTML = "Your search name cannot contain the following string '#&#'.";
           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;

        $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 search name. Please try again.";
            gE("searchname_update_"+searchId).style.display = 'block';
        }
    }
    
    
    
    
    
    function ForcedAddSearch(searchname, isalert)
    {
        var query = "SearchName=" + encodeURIComponent(searchname) + "&EmailAlert=" + isalert + "&SearchQuery=";         
        
        if(PageCache.SEOPath != "")
        {
           query += encodeURIComponent(PageCache.SEOPath); //.replace(/\&/g,':');
        }
        else
        { 
           query += encodeURIComponent(PageCache.QueryString); //.replace(/\&/g,':');
        }
        query += '&action=forcedaddsearch&PathInfo='+ GetPageName();
        $AJAX.GetForDelegate(UserOptionsDelegate, PersonalizationRoot + "AjaxCalls/My_Options.aspx?" + query); 
    }
    
    
    
    
    
    function RemoveThisListing(listingId, address, IsPageRefresh)
    { 
        if(IsPageRefresh == undefined)
        {
            IsPageRefresh = false;
        }
        tb_show('', 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_show('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_show('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_show('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;
        $AJAX.GetAsync(strURL);
    }
    
    
    
    
    
    function RemoveItemFromList(Id, ItemType, IsPageRefresh)
    {    
        var querystring =  "Id="+Id + "&ItemType=" + ItemType;
            querystring += '&PathInfo='+ GetPageName() + '&action=removeitem&IsPageRefresh=' + IsPageRefresh;
        $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();
        }  
    }
    
    
    
    
    
    // completes the action if any temporary cookie exists upon page load.
    function CompleteUserAction(tc_pageurl)
    {
        if(window.location.href == tc_pageurl && IsAlreadySignedIn())
        {
            if(getTempCookie("issignin") == "true")
            {
                SignInOrRegister = "SignIn";
            }
            else if(getTempCookie("issignin") == "false")
            {
                SignInOrRegister = "Register";
            }
            var querystring = 'action=completelastaction&PathInfo='+ GetPageName() + '&NameCookie='+ getTempCookie("iname"); 
            $AJAX.GetForDelegate(CompleteLastActionDelegate,   PersonalizationRoot + "AjaxCalls/Personalization.aspx?" + querystring);
        }
    }
    
    
    
    
   
    // completes the search action if any temporary cookie exists upon page load.  
    function CompleteSearchUserAction(tc_pageurl)
    {              
        if(window.location.href == tc_pageurl && IsAlreadySignedIn())
        { 
            if(getTempCookie("issignin") == "true")
            {
                SignInOrRegister = "SignIn";
                tb_show('Save this search', PersonalizationRoot + "AjaxCalls/SignIn.aspx?display=savesearch&Flag=S&islastaction=true&searchcriteria=" + escape(GetSearchLocation()) + "&width=350&height=210", false);                     
            }
            else if(getTempCookie("issignin") == "false")
            {
                SignInOrRegister = "Register";
                tb_show('Save this search', PersonalizationRoot + "AjaxCalls/SignIn.aspx?display=savesearch&Flag=R&islastaction=true&searchcriteria=" + escape(GetSearchLocation()) + "&width=350&height=210", false);                     
            }
        } 
    }
    
    
    
    
    
    function CompleteLastActionDelegate(AjaxResponse)
    {
        var html = "";
        var width= 350;
        var height = 190;
        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="personalization_tb_hd">';
            html +=     '<h2>We\'re Sorry...</h2>';
            html += '</div>';
            html += '<div class="personalization_tb_body">';
            html +=     '<p>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>';
            html += '<div id="personalization_tb_footer">';
            html +=     '<input type="button" value="Save" class="save_search_btn" onclick="ForcedAddSearch(\'' + searchname + '\',' + emailalert + ');" />';
            html +=     '<span>or</span>';
            html +=     '<a href="javascript:void(0);" onclick="tb_remove();" class="not_save">Do Not Save</a>';
            html += '</div>';
        }
        else
        {                     
            var param= AjaxResponse.split("::");     
            var actiontype = param[0].split("&")[0];
            if(actiontype == "type=search")
            { 
                width = 350;
                height = 190;
                caption = "Save Search";
         
                html =  '<div id="personalization_tb_hd">';
                html +=     '<h2>Success!</h2>';
                html +=     '<div class="close"><a href="javascript:void(0);" onclick="tb_remove();">close</a></div>';
                html += '</div>';
                html += '<div class="personalization_tb_body">';
                html +=     '<p>This search' + param[0].split("&")[1] + '</p>';
                
                if(SignInOrRegister == "Register")
                { 
                    html += '<p>Please check your e-mail for important account information.</p>'; 
                }
            }
            else
            {      
                caption = "User Action";   
                if(SignInOrRegister == "SignIn")
                { 
                    width= 300;
                    height = 100;
                    html =  '<div id="personalization_tb_hd" class="clearfix">';
                    html +=     '<h2>Welcome back,</h2>';
                    html +=     '<div class="close"><a href="javascript:void(0);" onclick="tb_remove();">close</a></div>';
                    html += '</div>';
                    html += '<div class="personalization_tb_body">';
                }
                else
                {         
                    html =  '<div id="personalization_tb_hd" class="clearfix">';       
                    html +=     '<h2>Thank you for registering!</h2>';
                    html +=     '<div class="close"><a href="javascript:void(0);" onclick="tb_remove();">close</a></div>';
                    html += '</div>';
                    html += '<div class="personalization_tb_body">';
                    html +=     '<p>Please check your e-mail for important account information.</p>';    
                }                        
                html +='<p><strong>This search' + param[0].split("&")[1] + '</p>';     
            }   
            
            html += '</div>';
            html += '<div id="personalization_tb_footer">';
            html +=     '<a href="javascript:void(0);" onclick="tb_remove();" class="btn">Ok</a></div>';
            html += '</div>';
            ChangeUserAction();
        } 
        tb_updateHTML("User Action", html, width, height);
    }
    
    
    
    
    
    // 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="";
        var url= GetPageName().split('/');//to get zipcode,state for saving user search ....mamta/////
        if(url.length==5 && IsNumeric(url[4]))
        {                   
            location=(url[3]+" "+url[4]).toUpperCase();
            //alert(location);                
        }
        else
        {        
            location=SearchCriteria;
        }
        return 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();
        }
    }
