var tempo;

$(function(){
    $('#dialog').dialog({
        autoOpen: false,
        modal: true,
        width: 550,
        buttons: { }
    });

    $('#dialog2').dialog({
        autoOpen: false,
        modal: true,
        width: 650,
        buttons: {
            "Conferma": function() {
                do_variazione($(this));
            },
            "Annulla": function() {
                $(this).dialog("close");
            }
        }
    });

    $('#div_add_sez').dialog({
        autoOpen: false,
        modal: true,
        width: 900,
        closeOnEscape: true,
        title: 'Scheda sezione',
        buttons: { }
    });

    $('#dialog_link').click(function(){
        $('#dialog').dialog('open');

        $("#flexami").flexigrid({
            url: '/index.php?p=gestione_variazioni',
            dataType: 'json',
            colModel : [
                {display: 'Tipo', name : 'tipo', width : 150, sortable : true, align: 'left'},
                {display: 'Variazione', name : 'variazione', width : 300, sortable : true, align: 'left'},
                ],
            buttons : [
                {name: 'Aggiungi variazione', bclass: 'add', onpress : esegui_comando},
                {name: 'Modifica variazione', bclass: 'mod', onpress : esegui_comando},
                {name: 'Elimina variazione', bclass: 'del', onpress : esegui_comando},
                {separator: true}
                ],
            searchitems : [
                {display: 'Tipo', name : 'tipo', isdefault: false},
                {display: 'Variazione', name : 'variazione', isdefault: true},
                ],
            sortname: "tipo",
            sortorder: "asc",
            usepager: true,
            useRp: true,
            rp: 15,
            showTableToggleBtn: false,
            width: 530,
            height: 350,
            singleSelect: true
        });

        return false;
    });

    $('#call').click(function() {
        $('#dialog6').center();
        $('#dialog6').show('slow');
        $('#dialog6').draggable();
        return false;
    });


    $('#callback_close').click(function(){
        $('#dialog6').hide('slow');
    });

    $('#popupwelcome_close').click(function(){
        clearTimeout(tempo);
        $('#popupwelcome').hide('slow');
    });

    $('#popupinfo_close').click(function(){
        $('#popupinfo').hide();
    });

    $(document).ready(function() {
        if ($.cookie('popupwelcome')) {
        } else {
            $.cookie('popupwelcome', true);
            $('#popupwelcome').center();
            tempo=setTimeout("$('#popupwelcome').show('slow');", 500);
            tempo=setTimeout("$('#popupwelcome').hide('slow');", 10500);
        }

        $("#filtrofigli input:checkbox").each(function() {
            $(this).attr('checked', true);
            $(this).change(function() {
                if ($(this).attr('checked')) {
                    $('#listaprodotti div[sezione="'+$(this).attr('figlio')+'"]').each(function() {
                        $(this).attr('showsezione', '1');
                        if ($(this).attr('showtag') == 1) $(this).show('slow');
                    });
                } else {
                    $('#listaprodotti div[sezione="'+$(this).attr('figlio')+'"]').each(function() {
                        $(this).attr('showsezione', '0');
                        $(this).hide('slow');
                    });
                }

            });
        });

        $("#filtrotag input:checkbox").each(function() {
            $(this).attr('checked', true);
            $(this).change(function() {
                if ($(this).attr('checked')) {
                    stringa = '#prod_box[tag~="'+$(this).attr('tag')+'"]';
                    $('#listaprodotti div[tag~="'+$(this).attr('tag')+'"]').each(function() {
                        $(this).attr('showtag', '1');
                        if ($(this).attr('showsezione') == 1) $(this).show('slow');
                    });
                } else {
                    $('#listaprodotti div[tag~="'+$(this).attr('tag')+'"]').each(function() {
                        $(this).attr('showtag', '0');
                        $(this).hide('slow');
                    });
                }

            });
        });

        $("#slides").coinslider({
            width: 970, /* width of slider panel */
            height: 270, /* height of slider panel */
            spw: 10, /* squares per width */
            sph: 5, // squares per height
            delay: 3000, // delay between images in ms
            sDelay: 30, // delay beetwen squares in ms
            opacity: 0.7, // opacity of title and navigation
            titleSpeed: 500, // speed of title appereance in ms
            effect: 'straight', // random, swirl, rain, straight
            navigation: false, // prev next and buttons
            links : true, // show images as links
            hoverPause: true // pause on hover
        });

        if (typeof js_info == 'string') {
            alert(js_info);
        }

        if (typeof js_go_link == 'string') {
            document.location.href = js_go_link;
        }

        if (typeof no_breadcrumbs == 'undefined') {
            do_breadcrumbs = 1;
        } else {
            do_breadcrumbs = 0;
        }

        sendtitle = $(this).attr('title');
        sendtitle = sendtitle.replace(/ - Playtennis/gi, "");
        /*
        alert(sendtitle);
        */

        $.post(
            "/index.php",
            { p: "get_breadcrumbs", url: $(location).attr('href'), title: sendtitle, set: do_breadcrumbs },
            function (data) {
                if (typeof data == 'object' && data != null) {
                    var mybcr = '<ul><li><a href="/index.php" title="PlayTennis Home">PlayTennis Home</a></li>';
                    for (var i=0; i<data.length; i++) {
                        riga = data[i];
                        mybcr = mybcr + '<li><a href="'+riga["href"]+'" title="'+riga["title"]+'">'+riga["title"]+'</a></li>\n';
                    }
                    mybcr = mybcr + '</ul>';
                    $("#sk_titolo").html(mybcr);
                    lasttxt = $("#sk_titolo > ul > li:last > a").text();
                    $("#sk_titolo > ul > li:last").html(lasttxt);
                    $("#sk_titolo").jBreadCrumb();
                    $("#sk_contitolo").css('visibility', 'visible');
                }
            }, "json");



    });

    $( "#accordion" ).accordion({ autoHeight: true, active: 0 });;
    $( "#accordion2" ).accordion({ autoHeight: false, active: 1 });;
    $( "#sk_img" ).imageZoom();
});

function esegui_comando(com, grid) {
    if (com == 'Aggiungi variazione') {
        $('#dialog2 #codice').val('');
        $('#dialog2 #action').val('add');
        $('#dialog2 #tipo').val(0);
        $('#dialog2 #variazione').val('');
        $('#dialog2').dialog('open');
    } else if (com == 'Modifica variazione') {
        if ($('.trSelected', grid).length < 1) {
            alert('Selezionare prima una variazione.');
            return;
        }
        id = $('.trSelected', grid).attr('id');
        id = id.substring(id.lastIndexOf('row')+3);

        $.post(
            "/index.php",
            { p: "get_variazione", value: id },
            function (data) {
                $('#dialog2 #action').val('mod');
                $('#dialog2 #variazione').val(data["variazione"]);
                $('#dialog2 #tipo').val(data["tipo"]);
                $('#dialog2 #codice').val(data["codice"]);
                $('#dialog2').dialog('open');
            }, "json");
     } else if (com == 'Elimina variazione') {
        if ($('.trSelected', grid).length < 1) {
            alert('Selezionare prima una variazione.');
            return;
        }
        id = $('.trSelected', grid).attr('id');
        id = id.substring(id.lastIndexOf('row')+3);
        if (confirm('Confermi la cancellazione della riga selezionata (' + id + ')?')) {
            $.ajaxSetup({async:false});
            $.post(
                "/index.php",
                { p: "del_variazione", value: id },
                function (data) {
                    if (data["result"] == '200 OK') {
                        // alert('Operazione eseguita con successo.');
                        $("#flexami").flexReload();
                    } else {
                        alert('Errore nell\'esecuzione dell\'operazione: ' + data["result"]);
                    }
                }, "json");
        }
    }
}

function do_variazione(dialog) {
    codice = $('#dialog2 #codice').val();
    variazione = $('#dialog2 #variazione').val();
    tipo = $('#dialog2 #tipo').val();
    action = $('#dialog2 #action').val();

    if (variazione && tipo && action ) {
        $.ajaxSetup({async:false});
        $.post(
            "/index.php",
            { "p": "do_variazione", "action": action, "variazione": variazione, "tipo": tipo, "codice": codice },
            function (data) {
                if (data["result"] == '200 OK') {
                    dialog.dialog("close");
                    // alert('Operazione eseguita con successo.');
                    $("#flexami").flexReload();
                } else {
                    alert('Errore nell\'esecuzione dell\'operazione: ' + data["result"]);
                }
            }, "json");
    }
    return false;
}


jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px");
    this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");
    return this;
}


function addtag(sel) {
    sel = document.getElementById(sel);
    if (sel.value == '' || sel.value == '0ZZ0') return;
    tmpval = document.getElementById('tag').value + "\n" + sel.value;

    tmpval = tmpval.replace(/\r/gi, "\n");
    tmpval = tmpval.replace(/\n+/gi, "\n");

    var listvalues = new Array();
    var newlist = new Array();

    listvalues = tmpval.split("\n");

    var hash = new Object();

    for (var i=0; i<listvalues.length; i++)
    {
        if (hash[listvalues[i].toLowerCase()] != 1 && listvalues[i] != '')
        {
            newlist = newlist.concat(listvalues[i]);
            hash[listvalues[i].toLowerCase()] = 1
        }
    }
    document.getElementById('tag').value = newlist.join("\n");

}

function show_addtag(sel, div) {
    sel = document.getElementById(sel);
    div = document.getElementById(div);

    if (sel.options[sel.selectedIndex].value == 0) {
        div.style.visibility = 'hidden';
    } else {
        div.style.visibility = 'visible';
    }
}


function build_seltag(sel) {
    if (isNaN(sel.value)) return;

    $.post(
    "/index.php",
    { p: "get_sel_tag", value: sel.value },
    function (data) {
        _emptyMenuItems('listatag');
        var opt;
        var i = 0;
        menu = document.getElementById('listatag');
        for (var key in data) {
            opt = new Option(data[key], key);
            menu.options[i++] = opt;
        }
        if (i > 1) {
            if ($('#listatag').css('display') == 'none') $('#listatag').css('display', 'block');
        } else {
            if ($('#listatag').css('display') == 'block') $('#listatag').css('display', 'none');
        }
    }, "json");
}
