/*
 * box-scroll
 * v. 1.3
 * @todo fix ff flash movie reload
 *
 * se jquery non è incluso copiare la riga successiva nell'HTML
 *
 * <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
 *
 * Per evitare conflitti con altri js:
 *
 * $j = jQuery.noConflict();
 *
 * $j(document).ready(function($)
 *
 */

$(function() {
       
    var boxParentId , boxParentClass, secondLastId, secondLastClass, secondLastName, mySecondLastElement, endBoxAdboxScrollName
            
      /******** CONFIGURAZIONE **************/
    
    var boxScrollName = '#adv-scroll-side'; //nome  id/class  del  box  da far scorrere, specificare se id (#) o  classe  (.)  ATTENZIONE!!  VANNO CAMBIATI ANCHE I NOMI NEL CSS CHE SI  RIFERISCONO  AL  BOX   
    var haveParent = 0; //se il box da far scrollare è contenuto a sua volta in un altro box mettere 1 altrimenti 0
    var boxBodyName = '.corpo-sx'; //nome id/class del corpo pagina, specificare se id (#) o classe (.)
    var secondLastName = 'pre-advscroll'; //nome penultimo elemento prima del box scorrevole, NON specificare se id (#) o classe (.)
    var tagSecondLastAllow = ['h1', 'h2', 'h3', 'div', 'span', 'table', 'p', 'b', 'i', 'br']; //tag che lo script cercherà in automatico di trovare prima del box scorrevole per calcolare posizione e altezza
    var sidebarAttrName = ['sidebar']; //nome contenitore elementi sidebar, NON specificare se id (#) o classe (.)
    var marginSecondAndLastEl = 0; //margine superiore tra box scorrevole e penultimo elemento
    var checkSecondLastExists = 1; //tenta di trovare in automatico penultimo elemento prima del box scorrevole

    /************** FINE CONFIGURAZIONE **************/

    var totMarginSecondAndLastEl = 0;
    var boxParentId = (haveParent == 1) ? $(boxScrollName).parent().parent().attr('id') : $(boxScrollName).parents().attr('id');
    var boxParentClass = (haveParent == 1) ? $(boxScrollName).parent().parent().attr('class') : $(boxScrollName).parents().attr('class');
         
    var secondLastId = $(boxScrollName).prev().attr('id'), secondLastClass = $(boxScrollName).prev().attr('class');
       
    boxScrollName = (haveParent == 1) ? $(boxScrollName).parent().attr('id', '#box-scroll-parent') : boxScrollName;
        
    var checkTypeLastElement = (haveParent == 1) ? $(boxScrollName).get(0).tagName.toLowerCase() : $(boxScrollName).prev().get(0).tagName.toLowerCase();
    
    if ( (jQuery.inArray(boxParentId, sidebarAttrName) >= 0) || (jQuery.inArray(boxParentClass, sidebarAttrName) >= 0) )
        if ( (boxParentId != secondLastId) || (boxParentClass != secondLastClass) )
        {
            if (jQuery.inArray(checkTypeLastElement, tagSecondLastAllow) >= 0)
            {
                secondLastHeight = (haveParent == 1) ? $(boxScrollName).height() : $(boxScrollName).prev().height();
            
                secondLastTop = (haveParent == 1) ? $(boxScrollName).offset().top : $(boxScrollName).prev().offset().top;
            
                totMarginSecondAndLastEl = Math.round(secondLastHeight+secondLastTop+marginSecondAndLastEl);
            
            } else {
                
               alert('Attenzione! Tag ultimo elemento non riconosciuto ('+$(boxScrollName).prev().get(0).tagName.toLowerCase()+'), verrà cercato un lemento con id: '+secondLastName);
                
                if ($('#'+secondLastName).length == 1)
                    mySecondLastElement = $('#'+secondLastName);
                else if ($('.'+secondLastName).length == 1)
                    mySecondLastElement = $('.'+secondLastName);
                else
                    checkSecondLastExists = 0;
                
                if (checkSecondLastExists == 0)
                    alert('Attenzione! Non posso posizionare il box-adv-scroll');
                else {
                    
                    secondLastHeight = mySecondLastElement.height();
            
                    secondLastTop = mySecondLastElement.offset().top;
                                                                
                    totMarginSecondAndLastEl = Math.round(secondLastHeight+secondLastTop+marginSecondAndLastEl);                                
                }
            }
        } else
             totMarginSecondAndLastEl = $(boxScrollName).marginTop;
    else
        alert('Attenzione! Parent "'+sidebarAttrName+'" not found!');    
    
    $(boxScrollName).css({ top: totMarginSecondAndLastEl+'px' });
    
    var msie6 = $.browser == 'msie' && $.browser.version < 7;
    
    if (!msie6)
    {      
        var top = (haveParent == 1) ? Math.round($(boxScrollName).offset().top + $(boxScrollName).height()) : $(boxScrollName).offset().top;
         
        $(window).scroll(function(event)
        {
            //Per il debug creare un div con id #debug nel sorgente HTML e scommentare la riga sottostante
            //$('#debug').html('scroll: '+$(this).scrollTop()+' - altezza corpo: '+$(boxBodyName).height());
                        
            if ( Math.round($(boxScrollName).height() + $(this).scrollTop()) <= $(boxBodyName).height())
            {
                var y = $(this).scrollTop();
                                
                if (y >= top)                       
                    $(boxScrollName).removeAttr("style").css({
                        'top' : '0px',
                        'position' : 'fixed'
                    });
                else
                    $(boxScrollName).removeAttr("style").css({
                        'top' : totMarginSecondAndLastEl+'px'
                    })
            } else {
                                
               endBoxAdvScroll = Math.round($(boxBodyName).height()-$(boxScrollName).height());
                   
                   //Per il debug creare un div con id #debug nel sorgente HTML e scommentare la riga sottostante
                  //$('#debug').append("  -  boxADVH: "+$(boxScrollName).height()+" -  boxADVTOP:  "+$(boxScrollName).offset().top+' - endBoxAdvScroll:  '+endBoxAdvScroll);

               if ( ($(this).scrollTop()+19-30) > $(boxBodyName).height())
                   $(boxScrollName).css({
                        'position' : 'absolute',
                        'top' : endBoxAdvScroll+'px'                    
                   });
               else
                  $(boxScrollName).removeAttr("style").css({
                          'top' : '0px',
                          'position' : 'fixed'
                  });
            }
        });
    }
});
