
var lastSaveId;

function toggleSaved(ref, userId, propertyId, purchaseType) 
{        
    var obj;
    var jsonUrl = searchSettings.jsonGateway;

    if (userId <= 0)
        return;

    if (ref.type == "checkbox" ) {
        obj = $(ref);
        obj.attr('checked', !obj.attr('checked'));        
    } else {
        obj = $("#cbSavedProperty_" + propertyId);
    }
    
    if (obj.attr('checked')) {
        obj.attr('checked', false);
        jsonUrl += "removeProperty/";

        var isSaved = jQuery.inArray(propertyId, jsSavedProperties);
        if (isSaved >= 0)
        {
            jsSavedProperties.splice(isSaved,1);
        }
        
    } else {
        obj.attr('checked', true);
        jsonUrl += "saveProperty/";
        jsSavedProperties.push(propertyId);        
    }
    
    obj.attr('disabled', true);

    jsonUrl += userId + '/{"purchaseType":"' + purchaseType + '","id":"' + propertyId + '"}';
    jsonUrl += "&rand=" + Math.random() * 1000000000000000000;
    //alert(jsonUrl);

    var resultCount = -1;

    xhr = $.ajax({
        type: "GET",
        url: jsonUrl,
        async: true,
        dataType: "json",
        beforeSend: function() {
            //stop any save attempt in progress
            undoSaveAttempt();
            lastSaveId = propertyId;
        },
        success: function(content) {
            resultCount = content.length;
        },
        complete: function(xhr, status) {
            //alert(xhr.responseText);
            obj.attr('disabled', false);
            localResultCount = updateCounter(obj.attr('checked'));
            if (resultCount === localResultCount) {
                //success
            } else if(localResultCount !== false) {
                //alert(resultCount + "!=" + localResultCount);
                updateCounter(!obj.attr('checked'));
                errorSaveProp(jsonUrl + " " + status);
            }
            xhr = null;
            lastSaveId = null;
        },
        error: function(xhr, desc, exceptionobj) {
            errorSaveProp(jsonUrl + " " + desc);
        }
    });

    return;
}


function updateCounter(isAdded) {
    var noSavedProps = 0;
    if ($(".noSavedProps").length) {
        noSavedProps = parseInt($(".noSavedProps").text());

        if (isAdded) {
            noSavedProps++;
        } else {
            noSavedProps--;
        }
        noSavedProps = Math.max(0, noSavedProps);
        $(".noSavedProps").text(noSavedProps);

        return noSavedProps;
    }
    return false;
}


function undoSaveAttempt() {
    if (xhr) {
        xhr.abort();
        if (lastSaveId) {
            var obj = $("#cbSavedProperty_" + lastSaveId);
            if (obj.length) {
                obj.attr('checked', !obj.attr('checked'));
                obj.attr('disabled', false);
                return true;
            }
        }
    }
    return false;
}


function errorSaveProp(msg) {
    alert("Error, please refresh the page and try again. " + msg);
    undoSaveAttempt()
}