﻿// implement indexOf into IE6, IE7, IE8

if (!Array.indexOf) {
    Array.prototype.indexOf = function (obj) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == obj) {
                return i;
            }
        }
        return -1;
    }
}

$(document).ready(function () {

    $(".column").sortable({
        connectWith: ".column",
        handle: ".widget-head"
    });

    $(".widget").addClass("ui-widget ui-widget-content ui-helper-clearfix ui-corner-all")
		.find(".widget-head")
		.addClass("ui-widget-header ui-corner-all")
		.prepend("<span class='ui-icon ui-icon-minusthick'></span>")
		.end()
		.find(".widget-content");

    $(".column").bind("sortstop", function (event, ui) {
        saveState(serializeWidgets());
    });

    //    // varibile globale per stato click freccia strumenti widgets
    //    var arrowClicked = false;

    //    // chiusura strumenti widgets a click sul body
    //    $(document).click(function (e) {
    //        if (!$(e.target).hasClass("activearrow")) {
    //            $('.arrow').removeClass('activearrow');
    //            arrowClicked = false;
    //        }
    //    });

    //    // gestione click freccia strumenti widgets
    //    $(".widget-head .arrow").live('click', function () {
    //        if (!arrowClicked) {
    //            $(this).addClass('activearrow');
    //            arrowClicked = true;
    //        }
    //        else {
    //            $(this).removeClass('activearrow');
    //            arrowClicked = false;
    //        }
    //    });

    // gestione click cancellazione widgets
    $(".widget-head .wg-delete a").live('click', function (event) {
        event.preventDefault();
        if (confirm('Sei sicuro di voler eliminare la widget?')) {
            var par = $(this).parent().parent().parent().parent();
            var id = $(par).attr('id').replace("w", "");
            $("#widgetslist #widget" + id).removeClass("used");
            par.remove();
            saveState(serializeWidgets());
            // aggiorno dimensione carousel dopo rimozione
            updateCarouselSettings();
        }
    });

    // funzione che serializza la lista delle widgets caricate
    function serializeWidgets() {
        var state = new Array();
        $(".column").each(function (i) {
            var widgets = new Array();
            $(this).children('.widget').each(function (j) {
                widgets[j] = $(this).attr('id');
            });
            state[i] = widgets;
        });
        //alert(JSON.stringify(state));
        return JSON.stringify(state);
    }

    // funzione per il salvataggio dello stato delle widgets per l'utente loggato
    function saveState(state) {
        // salvo lo stato delle widget (dashboard.ascx)
        $.post('/IT/Dashboard.htm', 'state=' + encodeURIComponent(state));
    }

    // funzione per il recupero dello stato da cookie in caso di utente nn loggato
    function resumeState() {
        // not implemented yet
    }

    /*$(".portlet-header .ui-icon").click(function () {
    $(this).toggleClass("ui-icon-minusthick").toggleClass("ui-icon-plusthick");
    $(this).parents(".portlet:first").find(".portlet-content").toggle();
    });*/

    // disabilita la selezione del testo per poter trascinare le widgets facilmente
    $(".column .widget-head").disableSelection();
    $("#widgetslist li").disableSelection();

    // gestione click sulla widget per aggiunta
    $('#widgetslist li').live('click', function () {

        // se widget non utilizzata la aggiungo
        if (!$(this).hasClass('used')) {
            var id = $(this).attr("id").replace("widget", "");
            var wid;
            for (var i = 0; i < widgetsList.length; i++) {
                if (widgetsList[i].id == id) {
                    wid = widgetsList[i];
                    $("#widgetslist #widget" + id).addClass("used");
                }
            }
            $(".column").last().prepend(createWidget(wid));
            saveState(serializeWidgets());
            // aggiorno dimensione carousel dopo aggiunta
            updateCarouselSettings();
        }

    });

    // funzione che concatena le classi
    function getClassName(c1, c2) {
        var clist = c1.split(" ");
        c2 = c2.toLowerCase().replace(/ /gi, "-");
        if (clist.indexOf(c2) < 0) {
            clist.push(c2);
        }
        return clist.join(" ");
    }

    // genera url nocache per widget
    function getWidgetRandomUrl(oUrl) {
        oUrl += (oUrl.indexOf("?") > 0 ? "&" : "?") + "nocache=" + Math.floor(Math.random() * 32768);
        return oUrl;
    }

    // funzione che crea l'html per le widgets (traccia dell'html in dashboard.ascx)
    function createWidget(widgetData) {
        var wdgt = "<div class=\"widget " + getClassName(widgetData["class"], widgetData["categoryName"]) + "\" id=\"w" + (widgetData.id) + "\">";
        wdgt += "<div class=\"widget-head\">" + (widgetData.name);

        wdgt += '<div class="widget-icons">';

        // restituisce l'html della freccia, vedi anche dashboard.ascx
        if (widgetData["deletable"] == 1) {
            wdgt += '<span class="wg-delete" title="Elimina widget"><a>Cancella</a></span>';
        }

        // restituisce l'html del punto di domanda, vedi anche dashboard.ascx
        if (widgetData["id"] > 0) {
            wdgt += '<span class="wg-faq" title="Come funziona?"><a href="/IT/Widgets.htm#w' + widgetData["id"] + '">Come funziona?</a></span>';
        }

        wdgt += "</div>";

        wdgt += "</div>";
        wdgt += "<div class=\"widget-content\" style=\"height: " + (widgetData.height) + "px;\">";
        wdgt += "<iframe src=\"" + getWidgetRandomUrl(widgetData.url) + "\" scrolling=\"no\" frameborder=\"0\"></iframe></div>";
        wdgt += "<div class=\"widget-footer\"></div></div>";
        return wdgt;
    }

    // funzioen che marchia le widgets già aggiunte dall'utente
    function hideUsedFromList() {
        $(".column").each(function (i) {
            $(this).children('.widget').each(function (j) {
                var id = $(this).attr('id').replace("w", "");
                $("#widgetslist #widget" + id).addClass("used");
            });
        });
    }

    // esecuzione al primo avvio del marchio widgets attive
    hideUsedFromList();

    // impostazioni carousel
    var currentPos = 0;           // posizione corrente
    var itemWidth = 220;         // dimensione singolo item
    var visibleItems = 4;           // utenti visibili nel carousel
    var countUsed = false;       // indica se contare le widgets nascoste
    var itemsCount = 0;

    // scroll carousel
    function updateCarouselPosition() {

        // aggiorno posizione
        var pos = itemWidth * currentPos;

        // animazione scroll
        $("#widgetslist ul").animate({ marginLeft: "-" + pos + "px" }, 1000, function () { });

    }

    // funzione che raggruppa l'aggiornamento del carousel
    function updateCarouselSettings() {

        // aggiorno numero elementi
        updateCarouselLength();

        // aggiorno stato pulsanti
        updateCarouselButtons();

    }

    // controllo lunghezza carousel
    function updateCarouselLength() {

        // conto gli oggetti
        itemsCount = countUsed ? $('#widgetslist li').length : $('#widgetslist li').not('.used').length;   // numero di widgets

    }

    // controllo per nascondimento pulsante next
    function updateCarouselButtons() {

        // se non ci sono sufficienti elementi nascondo il pulsante avanti ed indietro e azzero la posizione
        if (itemsCount <= visibleItems) {
            $('.next').hide();
            currentPos = 0;
            updateCarouselPosition();
        }
        // altrimenti lo mostro
        else {
            $('.next').show();
        }

        // nascondo il pulsante prev se sono in posizione zero
        if (currentPos <= 0) {
            $('.previous').hide();
        }

    }

    // controllo subito il numero di oggetti
    // e se nascondere il pulsante next
    updateCarouselSettings();

    // gestioen click pulsante indietro
    $('.previous').click(function () {
        if (currentPos > 0) {
            $('.next').show();
            currentPos--;
            updateCarouselPosition();
        }
        if (currentPos == 0) {
            $('.previous').hide();
        }
    });

    // gestione click pulsante avanti
    $('.next').click(function () {
        if (currentPos < (itemsCount - visibleItems)) {
            $('.previous').show();
            currentPos++;
            updateCarouselPosition();
        }
        if (currentPos == (itemsCount - visibleItems)) {
            $('.next').hide();
        }
    });

    // aggiorno il carousel alla prima esecuzione
    updateCarouselPosition();

});
