﻿var RenoEventsNS = ".RENO";
//========================================================
//  Membership Events
//========================================================
var RenoEvent = [];
RenoEvent.SignIn = "RENO_SignIn";
RenoEvent.SignOut = "RENO_SignOut";
RenoEvent.ForgotPasswordSelectMember = "RENO_ForgotPasswordSelectMember";
RenoEvent.ForgotPasswordSelectHint = "RENO_ForgotPasswordSelectHint";
RenoEvent.ForgotPasswordResetPassword = "RENO_ForgotPasswordResetPassword";
RenoEvent.Register = "RENO_Register";
RenoEvent.UpdateProfile = "RENO_UpdateProfile";

//========================================================
//  MyPortfolio Events
//========================================================
RenoEvent.Save = "RENO_Save";
RenoEvent.Edit = "RENO_Edit";
RenoEvent.Delete = "RENO_Delete";
RenoEvent.GetSavedItems = "RENO_GetSavedItems";
RenoEvent.SaveNote = "RENO_SaveNote";
RenoEvent.EditNote = "RENO_EditNote";
RenoEvent.DeleteNote = "RENO_DeleteNote";
RenoEvent.SavePhoto = "RENO_SavePhoto";
RenoEvent.DeletePhoto = "RENO_DeletePhoto";



//========================================================
//  Show AccountHeader menu
//========================================================
$(document).ready(function() {
    ShowAccountHeaderMenu();
});

function ShowAccountHeaderMenu()
{
    $.ajax({
        url: '/Reno/Personalization/AjaxCalls/AccountHeader.aspx',
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            $.log("Json Error Message: error(" + errorThrown + ") \"" + textStatus + "\"");
        },
        success: function(html) {
            $("#AccountHeader").html(html);

            // first unbind the events
            $("#AccountHeader").unbind(RenoEventsNS);

            // bind the events
            $("#AccountHeader").bind(RenoEvent.SignIn + RenoEventsNS, function() { ShowAccountHeaderMenu(); });
            $("#AccountHeader").bind(RenoEvent.SignOut + RenoEventsNS, function() { ShowAccountHeaderMenu(); });
            $("#AccountHeader").bind(RenoEvent.Register + RenoEventsNS, function() { ShowAccountHeaderMenu(); });
            $("#AccountHeader").bind(RenoEvent.UpdateProfile + RenoEventsNS, function() { ShowAccountHeaderMenu(); });
            $("#AccountHeader").bind(RenoEvent.ForgotPasswordResetPassword + RenoEventsNS, function() { ShowAccountHeaderMenu(); });
        }
    });
}

//========================================================
//  Sign Out
//========================================================
function SignOut()
{
    if (!confirm("Are you sure that you want to sign out?"))
    {
        return;
    }

    var querystring = "action=signout";
    var URL = "/Reno/Personalization/AjaxCalls/LoginAction.aspx?" + querystring;

    //add a timestamp to the call, to prevent caching
    var currentTime = new Date();
    var timestamp = { ts: currentTime.getTime() };
    
    $.get(URL, timestamp, function(response) {
    if (response.indexOf("pageredirect=") > -1) {
            PerformPageRedirect(response.split("=")[1]);
        }
        if (response == "success") {

            ClearLastActionCookie();
            
            // trigger the SignOut event, for the registered controls to update themselves
            $.event.trigger(RenoEvent.SignOut);
            

            ShowConfirmationDialog("Sign out successful");

            if (typeof ReloadSavedListings == 'function') {
                ReloadSavedListings();
            }

            CloseDialog(5000);
        }
    });
}

//========================================================
//  Login Related functions
//========================================================
function Login() {

    if (UseModalLoginRegister) {
        var URL = "/Reno/Personalization/AjaxCalls/LoginModal.aspx?type=login";
        ShowDialog(URL);
    }
    else {
        if (!IsPageRedirectSet()) {
            // user simply pressed the login button
            BuildPageRedirectCookie();
        }
        window.location = Personalization_Root + "Login";
    }
}

function SubmitLogin() {
    
    ValidateLoginForm();

    if (!$("#login_form").validate().form()) {
        ClearModalError();
        ResizeDialog();
        return;
    }

    // submit the login form
    var querystring = "email=" + $("#log_email").val();
    querystring += "&password=" + $("#log_password").val();
    querystring += "&rememberme=" + $('input[name=log_rememberme]').is(':checked');
    querystring += "&action=signin";

    var URL = "/Reno/Personalization/AjaxCalls/LoginAction.aspx?" + querystring;

    $.ajax({
        type: "GET",
        url: URL,
        data: "{}",
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            DisplayModalError("Unable to login at this time. Please try again");
            $.log("Json Error Message: error(" + errorThrown + ") \"" + textStatus + "\"");
        },
        success: function(response) {
            if (response.indexOf("pageredirect=") > -1) {
                ClearLastActionCookie();
                PerformPageRedirect(response.split("=")[1]);
            }
            else if (response == "success") {
                CloseDialog();

                // trigger the SignIn event, for the registered controls to update themselves
                $.event.trigger(RenoEvent.SignIn);

                if (typeof ReloadSavedListings == 'function') {
                    ReloadSavedListings();
                }

                if (IsLastActionSet()) {
                    ExecuteLastAction();
                }
                else {
                    ShowConfirmationDialog("You have successfully logged in!");
                    CloseDialog(5000);
                }
            }
            else {
                DisplayModalError(response);
            }
        }
    });
}

function ValidateLoginForm()
{
    $("#login_form").validate({
        rules: {
            log_email:      { required: true, email: true },
            log_password:   { required: true }
        }
    });
}






//========================================================
//  Forgot password Select Member functions
//========================================================
function ForgotPasswordSelectMember() 
{
    if (UseModalLoginRegister) {
        CloseDialog();
        var URL = "/Reno/Personalization/AjaxCalls/LoginModal.aspx?type=ForgotPasswordSelectMember";
        ShowDialog(URL);
    }
    else {
        window.location = Personalization_Root + "forgot-password-step1";
    }
    
}

function SubmitForgotPasswordSelectMember()
{
    VerifyForgotPasswordSelectMemberForm();

    if (!$("#forgot_password_form").validate().form()) {
        ClearModalError();
        ResizeDialog();
        return;
    }

    //submit the ForgotPasswordSelectMember form
    var querystring = "email=" + $("#log_email").val();
    querystring += "&action=ForgotPasswordSelectMember";

    var URL = "/Reno/Personalization/AjaxCalls/LoginAction.aspx?" + querystring;

    $.ajax({
        type: "GET",
        url: URL,
        data: "{}",
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            DisplayModalError("Error! Please try again");
            $.log("Json Error Message: error(" + errorThrown + ") \"" + textStatus + "\"");
        },
        success: function(response) {
            if (response.indexOf("pageredirect=") > -1) {
                PerformPageRedirect(response.split("=")[1]);
            }
            else if (response == "success") {
                CloseDialog();
                ForgotPasswordSelectHint();
            }
            else {
                DisplayModalError(response);
            }
        }
    });
}

function VerifyForgotPasswordSelectMemberForm()
{
    var validator = $("#forgot_password_form").validate({
        rules: {
            log_email: { required: true, email: true }
        },
        messages: {
            log_email: {
                required: "Please enter a valid email address",
                minlength: "Please enter a valid email address"
            }
        }
    }); 
}






//========================================================
//  Forgot password Select Hint functions
//========================================================
function ForgotPasswordSelectHint() 
{
    if (UseModalLoginRegister) {
        CloseDialog();
        var URL = "/Reno/Personalization/AjaxCalls/LoginModal.aspx?type=ForgotPasswordSelectHint";
        ShowDialog(URL);
    }
    else {
        window.location = Personalization_Root + "forgot-password-step2";
    }
}

function SubmitForgotPasswordSelectHint()
{
    VerifyForgotPasswordSelectHintForm();

    if (!$("#forgot_password_form").validate().form()) {
        ClearModalError();
        ResizeDialog();
        return;
    }

    //submit the ForgotPasswordSelectHint form
    var querystring = "hintanswer=" + $("#log_hintanswer").val();
    querystring += "&action=ForgotPasswordSelectHint";

    var URL = "/Reno/Personalization/AjaxCalls/LoginAction.aspx?" + querystring;

    $.ajax({
        type: "GET",
        url: URL,
        data: "{}",
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            DisplayModalError("Error! Please try again");
            $.log("Json Error Message: error(" + errorThrown + ") \"" + textStatus + "\"");
        },
        success: function(response) {
            if (response.indexOf("pageredirect=") > -1) {
                PerformPageRedirect(response.split("=")[1]);
            }
            else if (response == "success") {
                CloseDialog();
                ForgotPasswordResetPassword();
            }
            else {
                DisplayModalError(response);
            }
        }
    });
}

function VerifyForgotPasswordSelectHintForm()
{
    var validator = $("#forgot_password_form").validate({
        rules: {
            log_hintanswer: { required: true }
        },
        messages: {
            log_hintanswer: "Fill in a hint answer"
        }
    }); 
}



//========================================================
//  Forgot password Reset Password functions
//========================================================
function ForgotPasswordResetPassword()
{
    if (UseModalLoginRegister) {
        CloseDialog();
        var URL = "/Reno/Personalization/AjaxCalls/LoginModal.aspx?type=ForgotPasswordResetPassword";
        ShowDialog(URL);
    }
    else {
        window.location = Personalization_Root + "forgot-password-step3";
    }
}


function SubmitForgotPasswordResetPassword()
{
    VerifyForgotPasswordResetPasswordForm();

    if (!$("#forgot_password_form").validate().form()) {
        ClearModalError();
        ResizeDialog();
        return;
    }

    //submit the ForgotPasswordResetPassword form
    var querystring = "password=" + $("#log_password").val();
    querystring += "&action=ForgotPasswordResetPassword";

    var URL = "/Reno/Personalization/AjaxCalls/LoginAction.aspx?" + querystring;

    $.ajax({
        type: "GET",
        url: URL,
        data: "{}",
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            DisplayModalError("Error! Please try again");
            $.log("Json Error Message: error(" + errorThrown + ") \"" + textStatus + "\"");
        },
        success: function(response) {
            if (response.indexOf("pageredirect=") > -1) {
                PerformPageRedirect(response.split("=")[1]);
            }
            else if (response == "success") {
                CloseDialog();
                ShowConfirmationDialog("You have successfully changed your password!");

                // trigger the ForgotPasswordResetPassword event, for the registered controls to update themselves
                $.event.trigger(RenoEvent.ForgotPasswordResetPassword);

                window.setTimeout(function() {
                    CloseDialog();
                }, 5000);
            }
            else {
                DisplayModalError(response);
            }
        }
    });
}


function VerifyForgotPasswordResetPasswordForm()
{
    var validator = $("#forgot_password_form").validate({
        rules: {
            log_password:   { required: true, minlength: 5 },
            log_password1:  { required: true, minlength: 5, equalTo: "#log_password" }
        },
        messages: {
            log_password: {
                required: "Provide a password",
                rangelength: jQuery.format("Enter at least {0} characters")
            },
            log_password1: {
                required: "Repeat your password",
                minlength: jQuery.format("Enter at least {0} characters"),
                equalTo: "Enter the same password as above"
            }
        }
    });       
}




//========================================================
//  Register related functions
//========================================================
function CreateTermsAndConditionTooltip ()
{
    //create Terms And Conditions Tooltip
    $('#reg_termsandconditions').qtip({
        style: {
            name: 'blue', 
            tip: 'bottomLeft'
        }, 
        position: {
            corner: {
                target: 'topRight', 
                tooltip: 'bottomLeft'
            }
        }, 
        show: {
            delay: 0, 
            when: { event: 'mouseover' }
        }, 
        hide: {
            delay: 0, 
            when: { event: 'mouseout' }
        }
    });
    $('#reg_termsandconditions').click(function() {
        $('.qtip').remove();
    });
}

function Register() 
{
    if (UseModalLoginRegister) {
        CloseDialog();
        var URL = "/Reno/Personalization/AjaxCalls/LoginModal.aspx?type=register";
        ShowDialog(URL, 0, 0, function() {
            CreateTermsAndConditionTooltip();
        });
        
    }
    else {
        if (!IsPageRedirectSet()) {
            // user simply pressed the login button
            BuildPageRedirectCookie();
        }
        window.location = Personalization_Root + "Register";
        
    }
}


function SubmitRegister() 
{
    VerifyRegistrationForm();

    if (!$("#registration_form").validate().form()) {
        ClearModalError();
        ResizeDialog();
        CreateTermsAndConditionTooltip();
        return;
    }

    //submit registration form
    var querystring = "action=register";
    querystring += "&username=" + $("#reg_username").val();
    querystring += "&password=" + $("#reg_password").val();
    querystring += "&email=" + $("#reg_email").val();
    querystring += "&hintquestion=" + $("#reg_hintquestion").val();
    querystring += "&hintanswer=" + $("#reg_hintanswer").val();
    querystring += "&phone=" + $("#reg_phone").val();
    querystring += "&address=" + $("#reg_address").val();
    querystring += "&city=" + $("#reg_city").val();
    querystring += "&state=" + $("#reg_state").val();
    querystring += "&zipcode=" + $("#reg_zipcode").val();
    querystring += "&country=" + $("#reg_country").val();
    querystring += "&enableemailalert=" + ($("#reg_emailalert_enable").attr("checked") ? "1" : "0");
    querystring += "&htmlemailformat=" + ($("#reg_emailformat_html").attr("checked") ? "1" : "0");

    var URL = "/Reno/Personalization/AjaxCalls/LoginAction.aspx?" + querystring;

    $.ajax({
        type: "GET",
        url: URL,
        data: "{}",
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            DisplayModalError("Unable to register at this time. Please try again");
            CreateTermsAndConditionTooltip();
            $.log("Json Error Message: error(" + errorThrown + ") \"" + textStatus + "\"");
        },
        success: function(response) {
            if (response.indexOf("pageredirect=") > -1) {
                PerformPageRedirect(response.split("=")[1]);
            }
            else if (response == "success") {
                CloseDialog();
                ShowConfirmationDialog("Account created!");

                // trigger the Register event, for the registered controls to update themselves
                $.event.trigger(RenoEvent.Register);

                if (typeof ReloadSavedListings == 'function') {
                    ReloadSavedListings();
                }

                if (IsLastActionSet()) {
                    ExecuteLastAction();
                }
            }
            else {
                DisplayModalError(response);
                CreateTermsAndConditionTooltip();
            }
        }
    });
}

function VerifyRegistrationForm() 
{
    var validator = $("#registration_form").validate({
        rules: {
            reg_username:       { required: true, minlength: 2 },
            reg_password:       { required: true, minlength: 5 },
            reg_password1:      { required: true, minlength: 5, equalTo: "#reg_password" },
            reg_email:          { required: true, email: true },
            reg_hintquestion:   { required: true },
            reg_hintanswer:     { required: true },
            reg_terms:          { required: true }
        },
        messages: {
            reg_username: {
                required: "Enter a username",
                minlength: jQuery.format("Enter at least {0} characters")
            },
            reg_password: {
                required: "Provide a password",
                rangelength: jQuery.format("Enter at least {0} characters")
            },
            reg_password1: {
                required: "Repeat your password",
                minlength: jQuery.format("Enter at least {0} characters"),
                equalTo: "Enter the same password as above"
            },
            reg_email: {
                required: "Please enter a valid email address",
                minlength: "Please enter a valid email address"
            },
            reg_hintquestion: "You need to select a hint question",
            reg_hintanswer: "Fill in a hint answer",
            reg_terms: "You need to agree with terms and conditions"
        }        
    }); 
}















//========================================================
//  Profile Update related functions
//========================================================
function MyAccount()
{
    if (UseModalLoginRegister) {
        CloseDialog();
        var URL = "/Reno/Personalization/AjaxCalls/LoginModal.aspx?type=UpdateProfile";

        ShowDialog(URL, 0, 0, function() {
            CreateTermsAndConditionTooltip();
        });
    }
    else {
        if (!IsPageRedirectSet()) {
            // user simply pressed the login button
            BuildPageRedirectCookie();
        }    
        window.location = Personalization_Root + "Profile";
    }
    
}

function UpdateProfile() 
{
    VerifyUpdateProfileForm();


    if (!$("#registration_form").validate().form()) {
        ClearModalError();
        ResizeDialog();
        CreateTermsAndConditionTooltip();
        return;
    }

    // submit UpdateProfile form
    var querystring = "action=UpdateProfile";
    querystring += "&username=" + $("#reg_username").val();
    querystring += "&password=" + $("#reg_password").val();
    querystring += "&email=" + $("#reg_email").val();
    querystring += "&hintquestion=" + $("#reg_hintquestion").val();
    querystring += "&hintanswer=" + $("#reg_hintanswer").val();
    querystring += "&phone=" + $("#reg_phone").val();
    querystring += "&address=" + $("#reg_address").val();
    querystring += "&city=" + $("#reg_city").val();
    querystring += "&state=" + $("#reg_state").val();
    querystring += "&zipcode=" + $("#reg_zipcode").val();
    querystring += "&country=" + $("#reg_country").val();
    querystring += "&enableemailalert=" + ($("#reg_emailalert_enable").attr("checked") ? "1" : "0");
    querystring += "&htmlemailformat=" + ($("#reg_emailformat_html").attr("checked") ? "1" : "0");

    var URL = "/Reno/Personalization/AjaxCalls/LoginAction.aspx?" + querystring;

    $.ajax({
        type: "GET",
        url: URL,
        data: "{}",
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            DisplayModalError("Unable to register at this time. Please try again");
            $.log("Json Error Message: error(" + errorThrown + ") \"" + textStatus + "\"");
        },
        success: function(response) {
            if (response.indexOf("pageredirect=") > -1) {
                PerformPageRedirect(response.split("=")[1]);
            } 
            else if (response == "success") {
                // trigger the UpdateProfile event, for the registered controls to update themselves
                $.event.trigger(RenoEvent.UpdateProfile);

                CloseDialog();
                ShowConfirmationDialog("Profile updated!");
            }
            else {
                DisplayModalError(response);
            }
        }
    });
}

function VerifyUpdateProfileForm()
{
    var validator = $("#registration_form").validate({
        rules: {
            reg_username:       { required: true, minlength: 2 },
            reg_password:       { minlength: 5 },
            reg_password1:      { minlength: 5, equalTo: "#reg_password" },
            reg_email:          { required: true, email: true },
            reg_hintquestion:   { required: true },
            reg_terms:          { required: true }
        },
        messages: {
            reg_username: {
                required: "Enter a username",
                minlength: jQuery.format("Enter at least {0} characters")
            },
            reg_password: {
                rangelength: jQuery.format("Enter at least {0} characters")
            },
            reg_password1: {
                minlength: jQuery.format("Enter at least {0} characters"),
                equalTo: "Enter the same password as above"
            },
            reg_email: {
                required: "Please enter a valid email address",
                minlength: "Please enter a valid email address"
            },
            reg_hintquestion: "You need to select a hint question",
            reg_terms: "You need to agree with terms and conditions"
        }
    }); 
}









//========================================================
//  
//
//      PRIVATE PERSONALIZATION UTILITIES
//
//
//========================================================

//========================================================
//  Public function: DisplayModalError
//  This function is only used if the dialog html contains
//  the following HTML structure:
//
//  <div style="display: none;" class="dialog-message">
//      <div class="dialog-error">~~ Error Message ~~</div>
//  </div>
//========================================================
function DisplayModalError(errorMessage) {

    if (errorMessage == null || errorMessage.trim().length == 0) {
        return;
    }
    
    // replace new lines with <br> elements
    errorMessage = errorMessage.replace(/\n/g, "<br />");
    
    
    $('.dialog-message').show();
    $('.dialog-message .dialog-error').html(errorMessage);

    var minWidth  = $('#simplemodal-container').width();
    ResizeDialog(minWidth);
}


//========================================================
//  Public function: ClearModalError
//  This function is only used if the dialog html contains
//  the following HTML structure:
//
//  <div style="display: none;" class="dialog-message">
//      <div class="dialog-error">~~ Error Message ~~</div>
//  </div>
//========================================================
function ClearModalError() {
    $('.dialog-message').hide();
}


//========================================================
//  Private function: Trim
//  Removes leading and ending spaces from a string
//========================================================
String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}


//========================================================================
//  Private function: CanonicalUrl
//  Returns the href value of <link rel="canonical"> element on the page
//  or window.location.href, if no <link rel="canonical"> element is found
//========================================================================
document.CanonicalUrl = function() 
{
  //get all link elements on the page
  var links = document.getElementsByTagName('link');
  //for all link tags ...
  for( var x = 0; links[x]; x++ ) 
  {
     var rel = ''; 
     var href = ''; 
     
    //get rel attribute
    if( links[x].rel ) {
        rel = links[x].rel;
    } 
    else if( links[x].getAttribute ) { 
        rel = links[x].getAttribute('rel');
    } 
    
    //check for the rel attribute to see if it contains 'canonical'
    if( typeof( rel ) == 'string' && rel.toLowerCase().indexOf('canonical') > -1 ) 
    {
        //get href attribute
        if( links[x].href ) {
            href = links[x].href;
        } 
        else if( links[x].getAttribute ) { 
            href = links[x].getAttribute('href');
        } 
        
        //if found, return the value
        if( href != '') {
            return href;
        }
    }
  }  
  
  //no canonical element found in the document, returning window.location.href value
  return window.location.href;
}

//========================================================
//  Show confirmation dialog
//========================================================
function ShowConfirmationDialog(Message, Title) 
{
    Title = (Title == undefined) ? "" : Title;

    var URL = "/Reno/Personalization/AjaxCalls/successmodal.aspx?Message=" + escape(Message) + "&Title=" + escape(Title);
    ShowDialog(URL);
}


//========================================================
//  Show error dialog
//========================================================
function ShowErrorDialog(Message, Title) {
    Title = (Title == undefined) ? "ERROR" : Title;

    var URL = "/Reno/Personalization/AjaxCalls/successmodal.aspx?Message=" + escape(Message) + "&Title=" + escape(Title);
    ShowDialog(URL);
}


//========================================================
//  Refresh My Portfolio
//========================================================
function ReloadMyPortfolio()
{
    var URL = "/Reno/MyPortfolio/AjaxCalls/RenderMPResults.aspx";

    $.ajax({
        url: '/Reno/MyPortfolio/AjaxCalls/RenderMPResults.aspx',
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            $.log("Json Error Message: error(" + errorThrown + ") \"" + textStatus + "\"");
        },
        success: function(html) {
            $('#my_portfolio_placeholder').replaceWith(html);

            AttachMyPortfolioEvents();
        }
    });
}

function AttachMyPortfolioEvents() {
   
    // first, unbind the events
    $('#my_portfolio_placeholder').unbind(RenoEventsNS);

    // bind the events
    $('#my_portfolio_placeholder').bind(RenoEvent.SignIn + RenoEventsNS, function() { ReloadMyPortfolio(); });
    $('#my_portfolio_placeholder').bind(RenoEvent.SignOut + RenoEventsNS, function() { ReloadMyPortfolio(); });
    $('#my_portfolio_placeholder').bind(RenoEvent.ForgotPasswordResetPassword + RenoEventsNS, function() { ReloadMyPortfolio(); });
    $('#my_portfolio_placeholder').bind(RenoEvent.Register + RenoEventsNS, function() { ReloadMyPortfolio(); });
    $('#my_portfolio_placeholder').bind(RenoEvent.UpdateProfile + RenoEventsNS, function() { ReloadMyPortfolio(); });
    $('#my_portfolio_placeholder').bind(RenoEvent.Save + RenoEventsNS, function() { ReloadMyPortfolio(); });
    $('#my_portfolio_placeholder').bind(RenoEvent.Delete + RenoEventsNS, function() { ReloadMyPortfolio(); });
    
    
    BuildIconToolTip("#savesearch", 'searchSave');
    if (typeof $("#savesearch").data('qtip') == 'object') {
        $("#savesearch").qtip("destroy");
    }
    if (typeof BuildIconToolTip == 'function') {
        BuildIconToolTip("#savesearch", 'searchSave');
    }
}

//========================================================
//  LastAction Cookie Builder
//========================================================
function AppendLastActionCookie(LastAction) {
    if (IsLastActionSet()) {
        var PreviousLastAction = $.cookies.get("LastAction");
        LastAction += PreviousLastAction;
    }

    BuildLastActionCookie(LastAction);
}

function BuildLastActionCookie(LastAction)
{
    var Opts = { hoursToLive: 1 };
    $.cookies.set("LastAction", LastAction, Opts);
}

function ClearLastActionCookie() {
    $.cookies.set("LastAction", null, null);
}

function IsLastActionSet()
{
    var LastAction = $.cookies.get("LastAction");
    return (LastAction!=null || LastAction == "")
}

function RemoveAction(Action) {
    var LastAction = $.cookies.get("LastAction");
    if ((LastAction != null || LastAction == "")) {
        LastAction = LastAction.replace(Action, "");
        BuildLastActionCookie(LastAction);
    }
}

function ExecuteLastAction()
{
    var LastAction = $.cookies.get("LastAction");

    // clear last action
    ClearLastActionCookie();
    
    //execute last action
    if (LastAction != null || LastAction == "") {
        try {
            eval(LastAction);
        }
        catch (err) {
        }
    }
}


//========================================================
//  PageRedirect Cookie Builder
//========================================================

function BuildPageRedirectCookie() {
    var Opts = { hoursToLive: 1 };
    $.cookies.set("PageRedirect", window.location.href, Opts);
}

function ClearPageRedirectCookie() {
    $.cookies.set("PageRedirect", null, null);
}

function IsPageRedirectSet() {
    var LastPage = $.cookies.get("PageRedirect");
    return (LastPage != null || LastPage == "");
}


function GetPageRedirect() {
    var LastPage = $.cookies.get("PageRedirect");
    return LastPage;
}


function PerformPageRedirect(redirectPage) {

    if (redirectPage == null || redirectPage == 'undefined') {
        redirectPage = '';
    }

    if (redirectPage == '' && IsPageRedirectSet()) {
        //store the page redirect variable in a variable
        redirectPage = GetPageRedirect();

        //clear the redirect cookie
        ClearPageRedirectCookie();
    }


    if (redirectPage != '') {
        //perform the redirect
        window.location.href = unescape(redirectPage);
    }
}

//========================================================
//  IsSavedListingsPage
//  tests to see if this a portfolio listing result page
//========================================================
function IsSavedListingsResult()
{
    return (window.location.href.toLowerCase().indexOf("account/savedlistings") > -1)
}


//========================================================
//  IsDetailsPage
//  need a better approach
//========================================================
function IsDetailsPage() {
    return (window.location.href.toLowerCase().indexOf("/detail/") > -1)
}
