var dialog_effect = 'slide';
var loading_image = "/content/images/admin/loading.gif";

$(function() {
    $("#search_icon").click(function() {
        $("#search_controls").slideToggle();
        return false;
    });
    $("#admin_nav_item").click(function() {
        $("#admin_menu").slideToggle();
    });
    $("#comunicazione_nav_item").click(function() {
        $("#comunicazione_menu").slideToggle();
    });
    set_flash_notice()
    $(".toggle").each(function() {
        toggle_submenu($(this).attr("id"));
    });

});

function animate_saving() {
    disable_all_buttons();
    $("#save_check").attr("src", loading_image);
    $("#save_button_label").html("Salvataggio in corso...");
}
function carica_lista(url, data, callback) {
    $(".datapager").html('<div id="datapager_loader">Aggiornamento... <img src="/content/images/admin/progress-loading.gif" /> </div>');
    $("#posts_list").html('<p style="text-align: center"><img src="/content/images/admin/loading2.gif"/></p>');
    $.ajax({
        type: "GET",
        url: url,
        data: data,
        cache: false,
        success: function(response) {
            $("#posts_list").html(response);
            $(".datapager-link").click(function(e) {
                var pageIndex = $(this).attr("href").split('=')[1];
                if (data.PageIndex == undefined) {
                    data = data.replace(/PageIndex=\d+/, "PageIndex=" + pageIndex)
                } else {
                    data.PageIndex = parseInt(pageIndex);
                }
                carica_lista(url, data, callback);
                return false;
            });
            if (callback != undefined)
                callback();
        }
    });
}
function delete_entity(action) {
    show_confirm(
		"Confermare l'eliminazione? <br/><small>Questa azione è irreversibile</small>",
		"Attenzione",
		400, 200,
		function() {
		    $("#delete_check").attr("src", loading_image);
		    $("#delete_form").attr("action", action);
		    disable_all_buttons();
		    $("#delete_button_label").html("Eliminazione in corso...");
		    $("#delete_form").submit();
		});

}

function disable_all_buttons() {
    $(".button").each(function() { this.disabled = true; });
}

function no_ajax_cache() {
    return Math.floor(Math.random() * 100) * 10;
}

function set_cancel_button(url) {
    $("#cancel_button").click(function() {
        show_confirm(
			"Annullare l'operazione? <br/><small>Tutte le modifiche andranno perse</small>",
			"Attenzione",
			400, 200,
			function() {
			    window.location = url;
			});
    });
}

function set_delete_button(url) {
    $("#delete_button").click(function() {
        delete_entity(url);
    });
}

function show_confirm(message, title, width, height, callback) {
    var innerHTML = ' \
		<table class="dialog-inner"> \
			<tr> \
				<td><img alt="Info" src="/content/images/gnome/dialog-question.png" /></td> \
				<td>' + message + '</td> \
			</tr> \
		</table>';
    $(innerHTML).dialog({
        draggable: false,
        hide: dialog_effect,
        title: title,
        resizable: false,
        bgiframe: true,
        width: width,
        height: height,
        modal: true,
        buttons: {
            "No": function() {
                $(this).dialog("close");
            },
            "Sì": function() {
                $(this).dialog("close");
                callback();
            }
        }
    });
}

function set_flash_notice() {
    var flash_error = $("#flash_error").val();
    if (flash_error != undefined) {
        $("#flash_img").attr("src", "/content/images/gnome/dialog-error.png");
    }
    $("#FlashMessage").dialog({
        draggable: false,
        hide: dialog_effect,
        resizable: false,
        bgiframe: true,
        width: 400,
        modal: true,
        open: function() {
            var d = $(this);
            setTimeout(function(event, ui) {
                d.dialog('close');
            }, 3000);
        }
    });
}

function set_search_kind(kind) {
    var img_tag = ' <img src="/content/images/admin/search_controls_check.png" class="check" id="search_check" />';
    $("#search_check").remove();
    $("#search_" + kind).append(img_tag);
    $("#search_kind").val(kind);
}

function set_tinymce() {
    $('textarea.tinymce').tinymce({
        script_url: kTinyMceUrl,
        theme: "advanced",
        relative_urls: false,
        width: 520,
        height: 400,
        theme_advanced_buttons1: "bold,italic,underline,strikethrough,removeformat,bullist,numlist,|,undo,redo,link,unlink,anchor,image,|,cleanup,code",
        theme_advanced_buttons2: "",
        theme_advanced_buttons3: "",
        theme_advanced_buttons4: ""
    });
}

function slug(str) {
    var slug = str.replace(/\s+/g, '-').replace(/[^a-zA-Z0-9\-]/g, '').toLowerCase();
    return slug;
}

function toggle_submenu(name) {
    $("#" + name + "_toggle").click(function() {
        $("#" + name + "_uncollapsed_arrow").toggle();
        $("#" + name + "_collapsed_arrow").toggle();
        $("#" + name).slideToggle();
    });
}

function inspect(obj, maxLevels, level) {
    var str = '', type, msg;

    // Start Input Validations
    // Don't touch, we start iterating at level zero
    if (level == null) level = 0;

    // At least you want to show the first level
    if (maxLevels == null) maxLevels = 1;
    if (maxLevels < 1)
        return '<font color="red">Error: Levels number must be > 0</font>';

    // We start with a non null object
    if (obj == null)
        return '<font color="red">Error: Object <b>NULL</b></font>';
    // End Input Validations

    // Each Iteration must be indented
    str += '<ul>';

    // Start iterations for all objects in obj
    for (property in obj) {
        try {
            // Show "property" and "type property"
            type = typeof (obj[property]);
            str += '<li>(' + type + ') ' + property +
                 ((obj[property] == null) ? (': <b>null</b>') : ('')) + '</li>';

            // We keep iterating if this property is an Object, non null
            // and we are inside the required number of levels
            if ((type == 'object') && (obj[property] != null) && (level + 1 < maxLevels))
                str += inspect(obj[property], maxLevels, level + 1);
        }
        catch (err) {
            // Is there some properties in obj we can't access? Print it red.
            if (typeof (err) == 'string') msg = err;
            else if (err.message) msg = err.message;
            else if (err.description) msg = err.description;
            else msg = 'Unknown';

            str += '<li><font color="red">(Error) ' + property + ': ' + msg + '</font></li>';
        }
    }

    // Close indent
    str += '</ul>';

    return str;
}

function validation_summary(validator, errorMap) {
    if (validator.numberOfInvalids() > 0) {
        var messaggio = "";
        for (var i in errorMap) { messaggio += "<li>" + i + ": " + errorMap[i] + "</li>"; }
        $("#validation-summary").html("Il form contiene i seguenti errori:"
                        + "<ul class=\"errors\">"
                        + messaggio
                        + "<ul>");
        $("#validation-summary").show();
    } else {
        $("#validation-summary").hide();
    }
    validator.defaultShowErrors();
}