﻿//========================================================
//  Save Search Related functions
//========================================================
function SaveSearch(CallString)
{
    var LastAction = String.format("SaveSearch(\"{0}\");", CallString);
    BuildLastActionCookie(LastAction);

    var EntryType = "search";
    var Channel = $("#Channel").val(); //from the listing result page
        
    var querystring  = "type=SaveItem";
        querystring += "&entrytype=" + escape(EntryType);
        querystring += "&channel=" + escape(Channel);
        querystring += "&callstring=" + escape(CallString);

    var URL = "/Reno/MyPortfolio/AjaxCalls/SavedItemDialog.aspx?" + querystring;

    ShowDialog(URL, 0, 0, VerifySaveEntryForm);
}

function SubmitSaveSearch() 
{
    VerifySaveEntryForm();


    if (!$("#saveitem_form").validate().form()) {
        ClearModalError();
        ResizeDialog();
        return;
    }

    // submit save search
    var querystring = "";
    querystring += "&entrytype=" + escape($("#se_EntryType").val());
    querystring += "&channel=" + escape($("#se_Channel").val());
    querystring += "&callstring=" + escape($("#se_CallString").val());
    querystring += "&title=" + escape($("#se_title").val());
    querystring += "&newlistingalert=" + $('input[name=se_newlistingalert]').is(':checked');
    querystring += "&pricereductionalert=" + $('input[name=se_pricereductionalert]').is(':checked');
    querystring += "&openhousealert=" + $('input[name=se_openhousealert]').is(':checked');
    querystring += "&action=save";


    var URL = "/Reno/MyPortfolio/AjaxCalls/SavedItemAction.aspx?" + querystring;

    $.ajax({
        type: "GET",
        url: URL,
        data: "{}",
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            DisplayModalError("Unable to save the search. 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();
                ClearLastActionCookie();
                // trigger the SaveSearch event, for the registered controls to update themselves
                $.event.trigger(RenoEvent.Save);

                ShowToolTip('#savesearch', 'searchSaved', CreateToolTipContent('searchSaved', 'Search Saved'));
                window.setTimeout(function() {
                }, 2000);
            }
            else {
                //ShowToolTip("#savesearch", 'error', response);
                DisplayModalError(response);
            }
        }
    });
}

function VerifySaveEntryForm() {

    var validator = $("#saveitem_form").validate({
        rules: {
            se_title: { required: true, minlength: 1 }
        },
        messages: {
            se_title: {
                required: "Title cannot be empty",
                minlength: jQuery.format("Enter at least {0} characters")
            }
        }
    });       
}




//========================================================
//  Edit Search Related functions
//========================================================
function EditSearch(CallString) {
    var LastAction = String.format("EditSearch(\"{0}\");", CallString);
    BuildLastActionCookie(LastAction);

    var EntryType = "search";

    var querystring = "type=ModifyItem";
    querystring += "&entrytype=" + escape(EntryType);
    querystring += "&callstring=" + escape(CallString);

    var URL = "/Reno/MyPortfolio/AjaxCalls/SavedItemDialog.aspx?" + querystring;

    // Close any existing dialog before proceeding and destroy qtips in SavedSearches_Form
    $("#savedsearches_form .icon-img").qtip("destroy");
    CloseDialog();
    
    
    ShowDialog(URL, 0, 0, VerifySaveEntryForm);
}

function SubmitEditSearch() {
    VerifySaveEntryForm();


    if (!$("#saveitem_form").validate().form()) {
        ClearModalError();
        ResizeDialog();
        return;
    }

    // submit save search
    var querystring = "";
    querystring += "&entrytype=" + escape($("#se_EntryType").val());
    querystring += "&title=" + escape($("#se_title").val());
    querystring += "&callstring=" + escape($("#se_CallString").val());
    querystring += "&newlistingalert=" + $('input[name=se_newlistingalert]').is(':checked');
    querystring += "&pricereductionalert=" + $('input[name=se_pricereductionalert]').is(':checked');
    querystring += "&openhousealert=" + $('input[name=se_openhousealert]').is(':checked');
    querystring += "&action=edit";


    var URL = "/Reno/MyPortfolio/AjaxCalls/SavedItemAction.aspx?" + querystring;

    $.ajax({
        type: "GET",
        url: URL,
        data: "{}",
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            DisplayModalError("Unable to update the search. 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();
                ShowSavedSearches();

                // trigger the EditSearch event, for the registered controls to update themselves
                $.event.trigger(RenoEvent.Edit);
            }
            else {
                //ShowToolTip("#savesearch", 'error', response);
                DisplayModalError(response);
            }
        }
    });
}


//========================================================
//  Delete Search Related functions
//========================================================
function DeleteSearch(CallString)
{
    var LastAction = String.format("DeleteSearch(\"{0}\");", CallString);
    BuildLastActionCookie(LastAction);

    var EntryType = "search";
    var querystring  = "action=delete";
        querystring += "&EntryType=" + escape(EntryType);
        querystring += "&CallString=" + escape(CallString);

    var URL = "/Reno/MyPortfolio/AjaxCalls/SavedItemAction.aspx?" + querystring;

    var response = $.ajax({
        type: "GET",
        url: URL,
        data: "{}",
        async: false
    }).responseText;

    if(response == "success") 
    {
        // trigger the DeleteSearch event, for the registered controls to update themselves
        $.event.trigger(RenoEvent.Delete);

        Url = WebRoot + "/account/savedsearches";

        //add a timestamp to the call, to prevent caching
        var currentTime = new Date();
        var timestamp = { ts: currentTime.getTime() };

        $.get(Url, timestamp, function(data) {

            $("#savedsearches_form .icon-img").qtip("destroy");
            
            $('#simplemodal-data').html(data);
            ResizeDialog();
            BuildIconToolTip("#savedsearches_form .icon-img[title!='']");

        });
    }
    else if(response == "login") 
    {
        Login();
    }
    else {
        DisplayModalError(response);
    }  
}


//========================================================
//  Show Saved Searches
//========================================================
function ShowSavedSearches()
{
    var URL = "/account/savedsearches";

    ShowDialog(URL, 0, 0, function() {
        BuildIconToolTip("#savedsearches_form .icon-img[title!='']");
    });
}





//========================================================
//  LISTING TOOLS
//========================================================


//========================================================
//  Select All
//========================================================
function SelectAllListings() {

    $("input[name=LSCheckBox]").each(function() {
        this.checked = true;
    });

}

//========================================================
//  Clear All
//========================================================
function ClearAllListings() {

    $("input[name=LSCheckBox]").each(function() {
        this.checked = false;
    });
}



//========================================================
//  View Selected Listings
//========================================================
function ViewSelectedListings() {
    alert("not implemented");
}




//========================================================
//  Print Selected Listings
//========================================================
function PrintSelectedListings() {

    // ~~ Create an array with all checked listings ~~
    var checkedListings = new Array();
    $('input[name=LSCheckBox]:checked').each(function() {
        checkedListings.push($(this).val().toLowerCase());
    });


    // ~~ Check that at least one listing is selected ~~
    if (checkedListings.length == 0) {
        ShowErrorDialog("No listings selected!");
        return;
    }


    // ~~ Create URL ~~
    var URL = "/listing/print-brochure/" + checkedListings.join("|");

    window.open(URL);
}




//========================================================
//  Compare Selected Listings
//========================================================
function CompareSelectedListings() {

    // ~~ Create an array with all checked listings ~~
    var checkedListings = new Array();
    $('input[name=LSCheckBox]:checked').each(function() {
        checkedListings.push($(this).val().toLowerCase());
    });


    // ~~ Check that at least one listing is selected ~~
    if (checkedListings.length == 0) {
        ShowErrorDialog("No listings selected!");
        return;
    }


    // ~~ Create URL ~~
    var URL = "/listing/compare/" + checkedListings.join("|");

    window.open(URL);
}




//========================================================
//  Delete Selected Listings
//========================================================
function DeleteSelectedListings() {

    // ~~ Save last action ~~
    var LastAction = "DeleteSelectedListing();";
    BuildLastActionCookie(LastAction);

    // ~~ Create an array with all checked listings ~~
    var checkedListings = new Array();
    $('input[name=LSCheckBox]:checked').each(function() {
        checkedListings.push($(this).val().toLowerCase());
    });

    // ~~ Check that at least one listing is selected ~~
    if (checkedListings.length == 0) {
        ShowErrorDialog("No listings selected!");
        return;
    }
    
    // ~~ Create query string ~~
    var querystring = "action=delete";
    querystring += "&EntryType=listing";
    querystring += "&ListingIds=" + escape(checkedListings.join(","));

    var URL = "/Reno/MyPortfolio/AjaxCalls/SavedItemAction.aspx?" + querystring;



    $.ajax({
        type: "GET",
        url: URL,
        data: "{}",
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            DisplayModalError("Unable to delete listings. Please try again");
            $.log("Json Error Message: error(" + errorThrown + ") \"" + textStatus + "\"");
        },
        success: function(response) {
        
            if (response == "success") {

                // trigger the DeleteListing event, for the registered controls to update themselves
                $.event.trigger(RenoEvent.Delete);

                var SEOQuery = NormalizeSEOQuery(CacheObject.SEOQuery).toLowerCase();

                // ~~ reload result list ~~
                ReloadList(SEOQuery);
            }
            else if (response == "login") {
                Login();
            }
            else {
                ShowErrorDialog("Error deleting listings. Error was: " + response);
            }
        }
    });
}








//========================================================
//  Stores the current MyPortfolio collapsed state
//========================================================
function SaveMyPortfolioCollapsedState() {

    if ($("#tab-portfolio").hasClass("expand")) {
        $.cookies.set("MyPorfolioIsCollapsed", 1, null);
    }
    else {
        $.cookies.set("MyPorfolioIsCollapsed", 0, null);
    }

}




