/* 
 * 
 * Copyright (c) 2007 e-nova technologies pvt. ltd. (kevin.muller@enova-tech.net || http://www.enova-tech.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *            __             ___      ___    __  __     __     
 *          /'__`\    __   /' _ `\   / __`\ /\ \/\ \  /'__`\   
 *         /\  __/  /\__\  /\ \/\ \ /\ \_\ \\ \ \_/ |/\ \_\.\_ 
 *  (o_    \ \____\ \/__/  \ \_\ \_\\ \____/ \ \___/ \ \__/.\_\    _o)
 *  (/)_    \/____/         \/_/\/_/ \/___/   \/__/   \/__/\/_/   _(\)
 *       
 *           Prevents Headaches !  
 * 
 * JMyCarousel is inspired and based on JCarouselLite, an original concept by Ganeshji Marwaha
 *  
 *
 * $LastChangedDate: 2007-06-22 20:08:34 -0500 (Thu, 22 Nov 2007) $
 * $Rev: 15 $
 *
 * Version: 0.1
 */

(function ( $ ) {                  // Compliant with jquery.noConflict()
$.fn.jMyCarousel = function(o) {   
    o = $.extend({
        btnPrev: null,            // previous button customization
        btnNext: null,            // next button customization
        
        auto: false,            // shall the carousel start automatically

        speed: 1500,                // speed in ms of the animation.
        easing: 'swing',        // linear animation.'linear'

        vertical: false,        // set the carousel in a vertical mode
        circular: true,            // run in circular mode. Means : images never reach the end.
        visible: '4',            // size of the carousel on the screen. Can be in percent '100%', in pixels '100px', or in images '3' (for 3 images)
        start: 0,                // position in pixels that the carousel shall start at
        scroll: 1,
               
        evtStart : 'click',    // start event that we want for the animation (click, mouseover, mousedown, etc..)        
        beforeStart: null,        // Not used yet
        afterEnd: null            // Not used yet
    }, o || {});

    return this.each(function() 
        { 
            // Returns the element collection. Chainable.   
           var running = false, animCss="left", sizeCss="width";
           var div = $(this), ul = $("ul", div), tLi = $("li", ul), tl = tLi.size(), v = o.visible;        
           //var defaultBtn = (o.btnNext === null && o.btnPrev === null) ? true : false;
           var cssU = (v.toString().indexOf("%") != -1 ? '%' : (v.toString().indexOf("px") != -1) ? 'px' : 'el');
           var direction = null; // used to keep in memory in which direction the animation is moving
        
        // circular mode management
        // we add at the end and at the beginning some fake images to make the circular effect more linear, so it never breaks
        // It is still possible to improve the memory management by adding exactly the number of images requested.
        
        var imgSet = tLi.clone();
        ul.prepend(imgSet).append(imgSet.clone());
        
        // list              
        var li = $("li", ul);                                    
        div.css("visibility", "visible");
            
        // If the list item size is bigger than required
        // Horizontal list
        // If the item within li overflows its size, hide'em            
        li.css("overflow", "hidden").css("float", o.vertical ? "none" : "left").children().css("overflow", "hidden");  
            
        // IE double margin bug - rooo..    
        li.css("display", "inline");        
        if(li.children().get(0).tagName.toLowerCase() == 'a' && !o.vertical)
            {
                li.children().css('float','left');
            }
        

        ul.css("margin", "0")                               // Browsers apply default margin 
            .css("padding", "0")                            // and padding. It is reset here.
            .css("position", "relative")                    // IE BUG - width as min-width
            .css("list-style-type", "none")                 // We dont need any icons representing each list item.
            .css("z-index", "1")                          // IE doesnt respect width. So z-index smaller than div
			.css("zoom","1");

        div.css("overflow", "hidden")                       // Overflows - works in FF
            .css("position", "relative")                    // position relative and z-index for IE
            .css("z-index", "2")                            // more than ul so that div displays on top of ul
            .css("left", "0px")                            // after creating carousel show it on screen
			.css("zoom","1");
        
        var liSize    = width(li);                            // Full li size(incl margin)-Used for animation
        var liSizeV   = height(li);                            // size of the main layer, in its side          
        var curr      = o.start;                               // Current position in pixels  
        var nbAllElts = li.size();                            // Total number of items  
        var ulSize = liSize * nbAllElts;                       // size of full ul(total length, not just for the visible items)
        var nbElts = tl;                                    // number of elements (only visible items)
        var eltsSize = nbElts * liSize;                        // size of the visible elements only
        var allEltsSize = nbAllElts * liSize;                // Total size of the elements
        var textholderHeight =.31;
        var step = liSize;                                    // step size

        var omega   = ($('body').width()-liSize)/2;
       
          
        /******* Buttons **********/
        
        
        var imgStart =    o.start;
        if(o.start % liSize !== 0)
            {  
                // If a start position was given and was not exactly positionned between 2 images
                var imgStart = parseInt(o.start / liSize);    // we adjust it
                curr = o.start = (imgStart * liSize);        // we set the starting position at a fixed point, between 2 images.
        
            }
        // The start position is one carousel length ahead due to the optical effect
        o.start += (liSize * tl-omega);        
        curr += (liSize * tl-omega);        
        
        
        // Calculates the size of the main div according to the given size (can be in percent, in value or in pixels)
        var divSize, cssSize, cssUnity;
        if(cssU == '%')
            {                                    // in percent 
                divSize = 0;                                    // We don't have the value in pixels unless we set the percent value first. So 0, and will catch it later
                cssSize = parseInt(v);  
                cssUnity = "%";
            }
        else if(cssU == 'px')
            {                                    // in pixels
                divSize = parseInt(v);
                cssSize = parseInt(v);
                cssUnity = "px";
            }
        else
            {                                                    // in elements (number of elements to display)
                divSize = liSize * parseInt(v); 
                cssSize = liSize * parseInt(v);
                cssUnity = "px";
            }                                                        

            
        // Width of the UL is the full length for all the images
        // Set the starting item            
        ul.css(sizeCss, ulSize + "px").css(animCss, -(o.start)); 
        
        // Width of the DIV. length of visible images            
        div.css(sizeCss, cssSize + cssUnity);                    
        
        // We didn't have the size in pixels in case of % size. Catch up !
        // The size is simply the calculated size in pixels            
        if(divSize === 0) divSize = div.width();                                
            
        
        // horizontal mode
        div.css('height', liSizeV + 'px');
        ul.css('height', liSizeV + 'px');    
      
                                
        // Calculate the number of visible elements inside (in case of size in percent)                            
        if(cssU == '%')
        {
            v = divSize / li.width();                        
            if(v % 1 !== 0){ v +=1; }
            v = parseInt(v);
        }
        
        var divVSize = div.height(); 
     
        //DIV с меню
        $('#wrapper').css({'left':omega+500,'position':'absolute'});
        
        //Выплывающее окно.Добавляем к документу
        var obj = $(this);
        $('li>div', obj).hide();        
        $(obj).append
            (
                '<div id="textholder" class="textholder" style="z-index:200; position:absolute; bottom:0px; margin-bottom:0; left:'+omega+'px"></div>'
            );
           
        //Размеры окошка    
        $('div#textholder').width(liSize).height(liSizeV*textholderHeight);    
                
        //Начальное состояние окошка.
                            
        $('div#textholder').html($('li:eq('+imgStart+')>div', obj).html()).animate({marginBottom:'0px'},1000); 

       

        //Кнопки-ссылки.
        //На момент показа отключаем все обработчики чтоб не мешали            
        var Click_next = function()
                {
                    $('div#textholder>div.link_right').unbind(o.evtStart);
                    $('div#textholder>div.link_left').unbind(o.evtStart);
                    //o.btnNext.css('opacity',1);
                    running = true;
                    direction = 'forward';                
                    return forward();                        
                }
        
        //На момент показа отключаем все обработчики чтоб не мешали            
        var Click_prev = function()
                {
                    $('div#textholder>div.link_left').unbind(o.evtStart); 
                    $('div#textholder>div.link_right').unbind(o.evtStart);
                    //o.btnNext.css('opacity',1);
                    running = true;                
                    direction = 'backward';
                    return backward();                 
                }    
            
        //Подключаем обработчики.
        $('div#textholder>div.link_right').bind(o.evtStart,Click_next);        
        $('div#textholder>div.link_left').bind(o.evtStart,Click_prev);    
        
        function forward()
            {                        
                var s = step;
                if(running === true && direction === "backward"){ return; }    
                //Поехали.Сначала сворачиваем текст потом едем и только потом открываем текст.            
                $('div#textholder').
                animate({marginBottom:-liSizeV*textholderHeight+'px'},1000,
                        function()
                            {
                                ul.animate( {left: -(curr + s)} , o.speed, o.easing,
                                  function() 
                                    {                                                                                                                                             
                                        curr += s; 
                                        if(curr + divSize + liSize >= allEltsSize)
                                           {
                                                ul.css('left', -curr + eltsSize);
                                                curr -= eltsSize;
                                            } 
                                            
                                        stop();                                                        
                                        if(running) forward();
                                            
                                        imgStart++;
                                        if(imgStart>=tl) imgStart=0;
                                        $('div#textholder').html($('li:eq('+imgStart+')>div', obj).html()).animate({marginBottom:'0px'},1000,
                                                    function()
                                                                {                                                                    
                                                                     //Закончили слайд шоу. Включаем обработчики.
                                                                     $('div#textholder>div.link_right').bind(o.evtStart,Click_next);        
                                                                     $('div#textholder>div.link_left').bind(o.evtStart,Click_prev);
                                                                });
                                                      
                                    })    
                            });
                            
                
                return true;    
            }
                
        function backward()
            {
                var s = step;            
                if(running === true && direction === "forward"){ return; } 
                 
                $('div#textholder').
                animate({marginBottom:-liSizeV*textholderHeight+'px'},1000,
                        function()
                            {
                                ul.animate({ left: -(curr - s) }, o.speed, o.easing,
                                        function() 
                                             {                    
                                                curr -= s;                                       
                                                if(curr <= liSize)
                                                     {
                                                         ul.css('left', -(curr + eltsSize));
                                                         curr += eltsSize;
                                                     }
                                                     
                                                stop();                    
                                                if(running) backward();
                                                     
                                                imgStart--;
                                                if(imgStart<0) imgStart=tl-1;                                                 
                                                $('div#textholder').html($('li:eq('+imgStart+')>div', obj).html()).animate({marginBottom:'0px'},1000,
                                                    function()
                                                                {
                                                                    //Закончили слайд шоу. Включаем обработчики.
                                                                    $('div#textholder>div.link_left').bind(o.evtStart,Click_prev); 
                                                                    $('div#textholder>div.link_right').bind(o.evtStart,Click_next);        
                                                                });
                                                             
                                            });
                        });
                return true;    
            }
        
        function stop()
            {   
                running = false;     
                direction = null;
                return true;            
            }      
        
    });
};
        function css(el, prop) 
            {
                return parseInt($.css(el[0], prop)) || 0;
            }

        function width(el) 
            {
                    return el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
            }

        function height(el) 
            {   //alert( el[0].offsetHeight);             
                return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
            }

})(jQuery);



