﻿(function($) {  
  $.fn.carousel = function(options) {  
    var options = $.extend({  
       width:		600,
       height:		200,
       margin:		5,
       time:		500,
       start_pos:	1   
    }, options);  
    
    // параметры инициализации
    var carousel_width	= options.width;
    var carousel_height	= options.height;
    var margin		= options.margin;
    var start_position	= options.start_pos;
    var slide_time	= options.time;

    // задаем ширину карусели
    $('#carousel_inner').css('width',carousel_width+'px');

    // задаем высоту карусели
    $('#carousel_ul li').height((carousel_height-margin*2)+'px');
    $('#carousel_ul li img').height((carousel_height-margin*2)+'px');
    //$('#left_scroll,#right_scroll').css('height',carousel_height+margin*2+'px');

    // задаем отступы
    $('#carousel_ul li').css('margin',margin+'px');
    
    // проверяем стартовую позицию
    if (start_position > ($('#carousel_ul li').length - 3))
      start_position = $('#carousel_ul li').length - 3;
    else
      if (start_position < 1) start_position = 1;

    // ставим последнюю в списке картнку слева от первой
    $('#carousel_ul li:first').before($('#carousel_ul li:last')); 
    
    // считаем первоначальное смещение
    var imgprev_width	= $('#carousel_ul li:first').outerWidth();
    var start_left = 0;
    
    // устанавливаем смещение
    start_left = start_left + imgprev_width + margin*3;
    $('#carousel_ul').css('left','-'+start_left+'px');

    options.Left = function()
    {
      if (!$("#carousel_inner").hasClass("animated"))
      {
        $("#carousel_inner").addClass("animated");
        
        var item_width	= $('#carousel_ul li:first').outerWidth() + margin*2;
        var left_indent = parseInt($('#carousel_ul').css('left')) + item_width;
        
        // ставим последнюю картинку в начало и сдвигаем все влево на ширину картинки           
        start_left = $('#carousel_ul li:last').outerWidth() + margin*2;
        
        $('#carousel_ul li:first').before($('#carousel_ul li:last')); 
        $('#carousel_ul').css('left',(parseInt($('#carousel_ul').css('left')) - start_left)+'px' );
        
        $('#carousel_ul:not(:animated)').animate({'left' : (left_indent-start_left)},slide_time,function(){    
          $("#carousel_inner").removeClass("animated");
        });
      }

      return false;
    }

    options.Right = function()
    {
      if (!$("#carousel_inner").hasClass("animated"))
      {
        $("#carousel_inner").addClass("animated");
        
        var item_width = $('#carousel_ul li:eq(1)').outerWidth() + margin*2;
        var left_indent = parseInt($('#carousel_ul').css('left')) - item_width;
                                
        $('#carousel_ul:not(:animated)').animate({'left' : left_indent},slide_time,function(){    
          start_left = $('#carousel_ul li:first').outerWidth() + margin*2;
          $('#carousel_ul li:last').after($('#carousel_ul li:first'));
          $('#carousel_ul').css('left',(parseInt($('#carousel_ul').css('left')) + start_left)+'px' );

          $("#carousel_inner").removeClass("animated");
        });

        return false;
      }
    }

    // идем направо        
    $('#right_scroll').click(function(){
      options.Right();
    });
    
    // идем влево
    $('#left_scroll').click(function(){
      options.Left();
    });

    // обработчик на колесо мыши
    $("#carousel_inner").mousewheel( function(e, d) {
      return d>0 ? options.Left() : options.Right(); 
    });

    return options;
  };
})(jQuery);

// обработчик события загрузки картинки

(function ($) {
  $.fn.bindImageLoad = function (callback) {
    function isImageLoaded(img) {
      if (!img.complete) {
        return false;
      }
      if (typeof img.naturalWidth !== "undefined" && img.naturalWidth === 0) {
        return false;
      }
      
      return true;
    }

    return this.each(function () {
      var ele = $(this);
      
      if (ele.is("img") && $.isFunction(callback)) {
        ele.one("load", callback);
        if (isImageLoaded(this)) {
          ele.trigger("load");
        }
      }
    });
  };
})(jQuery);
