/*
 * unbit.js - unbit sas - copyright 2010
 */

/*
 * Usare:
 * $(document).ready(function() {
 *   menuSetActive('ul#menu li');
 * });
 * Prende come parametro opzionale un dizionario con i seguenti attributi:
 * - li_elem = stringa del selettore degli elementi li del menu
 * - active_class = la classe da dare agli elementi attivi, default 'active'
 * - follow_parent = booleano per segnare come attivo anche eventuali li padri, default true
 * - match_id = booleano per segnare di beccare anche eventuali cifre oltre al path, default false
 *   es. /progetti/1/ che segni attivo pure /progetti/
 * - broad_match = booleano per segnare di beccare tutti gli href che cominciano con il path, default false
 *   es. /progetti/progettone/ che segni attivo pure /progetti/
 * - href_ignore_parms = booleano per ignorare i parametri GET presenti nell'href del link
 * - cb = callback opzionale che prende come parametri l'href del link, il path chiamato e l'elementi li
 */
function menuSetActive(li_elem, opts) {
    var options = typeof(opts) == 'undefined' ? {} : opts;
    var active_class = typeof(options.active_class) != 'undefined' ? options.active_class : 'active';
    var follow_parent = typeof(options.follow_parent) != 'undefined' ? options.follow_parent : true;
    var match_id = typeof(options.match_id) != 'undefined' ? options.match_id : false;
    var broad_match = typeof(options.broad_match) != 'undefined' ? options.broad_match : false;
    var href_ignore_params = typeof(options.href_ignore_params) != 'undefined' ? options.href_ignore_params : false;

    var path = window.location.pathname;

    $(li_elem).each(function() {
        var href = $(this).children('a').attr('href');
        if (href_ignore_params) {
            href = href.replace(/\?.*$/, '');
        }

        var match_re = '^(/it|/en|/fr)?'+href;
        if (broad_match && href != '/') {
            var match_href_re = new RegExp(match_re+'.*$');
        } else if (match_id) {
            var match_href_re = new RegExp(match_re+'\\d+/$');
        } else {
            var match_href_re = new RegExp(match_re+'$');
        }

        if (path.match(match_href_re)) {
            $(this).attr('class', active_class);
            if (follow_parent) {
                $(this).parent().parent('li').attr('class', active_class);
            }
        } else {
            $(this).attr('class', '');
        }

        if (typeof(cb) != 'undefined') {
            cb(href, path, $(this));
        }
    });
}

/*
 * Usare:
 * redirect("http://unbit.it", 5000);
 * I parametri:
 * - url = url su cui redirigere
 * - timeout = millisecondi dopo i quali redirigere, default 0
 */
function redirect(url, timeout) {
    timeout = typeof(timeout) != 'undefined' ? timeout : 0;

    setTimeout("window.location.replace('"+url+"')", timeout);
}

/*
 * Crea dei tooltip all'hover pigliando il contenuto del tooltip da un 
 * dizionario.
 *
 * Esempio:
 * js:
 * var glossary = {miao: 'Miao miao'};
 * $(document).ready(function() {
 *   uglossary(glossary);
 * });
 * html:
 * <span class="ugl ugl_miao">gatto</span>
 *
 * All'hover su ugl_miao viene aggiunto un nodo in questo formato:
 * <div class="ugl-tip"><h6></h6><span></span></div>
 * dove all'interno dell'h6 trovate il contenuto dello span originale,
 * in questo caso 'gatto', mentre all'interno dello span troverete il contenuto 
 * che avete specificato nel dizionario, in questo caso 'Miao miao'.
 * Il nodo viene visualizzato all'onmouseover tramite fadeIn e nascosto all'onmouseout 
 * con fadeOut.
 */
function uglossary(glossary) {
    $('.ugl').each(function() {
         var classes = $(this).attr('class');
         var key = false;
         var ugl_class_re = /ugl_(.*)/;
         for (var c in classes) {
             var match = ugl_class_re.exec(c);
             if (match) {
                 key = match[1];
                 break;
             }
         }

        /* come il continue in un for */ 
        if (!key)
            return true;

        var title = $(this).text();
        var e = $('<div class="ugl-tip"><h6>'+title+'</h6><span>'+glossary[key]+'</span></div>').hide();
        $(this).append(e);
        $(this).hover(function() {
            $('.ugl-tip', $(this)).stop(true, true).fadeIn('normal');
        }, function() {
            $('.ugl-tip', $(this)).stop(true, true).fadeOut('normal');
        });
    });
}

/*
 * uScroll e uScrollResize sono due plugin per creare un menu che fa lo scrolling verticale al mousemove.
 * uScroll deve essere chiamata sul contenitore del menu al document ready mentre uScrollResize deve
 * essere chiamata al window resize.
 *
 * Vengono applicate agli ultimi tre elementi delle lista partendo dal fondo le seguenti classi:
 * last, last_1, last_2.
 *
 * Ispirato da: http://www.queness.com/resources/html/scrollmenu/index.html
 */
(function($) {
    $.fn.uScroll = function() {
        // gli ultimi tre visibili devono essere identificabili
        function mark_last_three(sidebar, list, list_length, last_index) {
            list.removeClass('last last_1 last_2');
            // non metto le classi quando non ci sono elementi nascosti
            // mettere last a tutti dopo l'ultimo
            if (last_index+1 < list_length) {
                for (var i = last_index; i < list_length; i++) {
                    $('li:eq('+i+')', sidebar).addClass('last');
                }
                $('li:eq('+(last_index-1)+')', sidebar).addClass('last_1');
                $('li:eq('+(last_index-2)+')', sidebar).addClass('last_2');
            }
        }

        var skip = 0;
        $(this).mousemove(function(e) {
            if (skip++ % 2) {
               skip = 0;
               return;
            }

            var list = $('li', $(this));
            var elems = {height: list.height(), length: list.length};

            //Sidebar Offset, Top value
            var s_top = parseInt($(this).offset().top);
            var mheight = parseInt(elems.height * elems.length);
            // Calcoliamo l'inizio del viewport
            var top_value = Math.round(((s_top - e.pageY) /100) * mheight / 2) + (3 * elems.height);
            // almeno un elemento deve essere visibile
            top_value = top_value < -mheight + elems.height ? -mheight + elems.height : top_value;
            // gli ultimi tre visibili devono essere identificabili
            var last_index = Math.min(Math.abs(Math.floor((top_value - $(this).height()) / elems.height))-1, elems.length-1);
            list.removeClass('last last_1 last_2');

            jQuery.data($(this), 'menu_top_value', top_value);

            $('ul', $(this)).stop().animate({top: top_value}, { queue:false, duration:10000, complete: function () {
                mark_last_three($(this), list, elems.length, last_index);
            }});
        });

        // centrare active 
        $(this).each(function() {
            var list = $('li', $(this));
            var active_index = list.index($('li.active', $(this)));
            var elems = {height: list.height(), length: list.length};

            //Sidebar Offset, Top value
            var s_top = parseInt($(this).offset().top);

            // Calcoliamo l'inizio del viewport
            var top_value = 0;
            if (!(-active_index * elems.height <= top_value && -active_index * elems.height >= top_value - $(this).height()))
                top_value = -active_index * elems.height;

            var last_index = Math.min(Math.abs(Math.floor((top_value - $(this).height()) / elems.height))-1, elems.length-1);
            mark_last_three($(this), list, elems.length, last_index);

            jQuery.data($(this), 'menu_top_value', top_value);
            $('ul', $(this)).animate({top: top_value}, { queue:false, duration:3000});
        });
    }
})(jQuery);

(function($) {
    $.fn.uScrollResize = function() {
        // quando allargo i nuovo elementi hanno classe last e non ci piace
        $(this).each(function() {
            var list = $('li', $(this));
            var elems = {height: list.height(), length: list.length};

            var mheight = parseInt(elems.height * elems.length);
            var top_value = jQuery.data($(this), 'menu_top_value');
            // almeno un elemento deve essere visibile
            top_value = top_value < -mheight + elems.height ? -mheight + elems.height : top_value;

            // gli ultimi tre visibili devono essere identificabili
            var last_index = Math.min(Math.abs(Math.floor((top_value - $(this).height()) / elems.height))-1, elems.length-1);
            mark_last_three($(this), list, elems.length, last_index);
        });
    }
})(jQuery);

/*
 * uFloat sposta l'oggetto animandolo a seconda di quanto si è scrollato. Da chiamare al $(window).scroll().
 * Prende come parametro opzionale il margine superiore da aggiungere alla nuvoa posizione.
 */
(function($) {
    $.fn.uFloat = function(margin) {
        margin = margin || 0;
        var scrollAmount=$(document).scrollTop()+margin;
        if ($(window).height() < $(this).height()) {
            $(this).css("top", margin);
        } else {
            $(this).stop().animate({top: scrollAmount}, 1500, 'easeOutQuint');
        }
    }
})(jQuery);

