$(function(){
    $('.bg_slide:first').show().addClass('active');
    
    resize();
    
    $(window).resize(function(){  
        resize();
    });
  
    $('.bg_slide').each(function(i){
        $(this).attr('id', 'bgslide_'+i);
        abs = i;
    });
    
    $('#wrapper').css('background', '');
    
    slideInterval();
    
    $('#bgslide_left').click(function(){
       window.clearInterval(bgSlideInterval);
       doSlide('left');
       slideInterval();
    });
    
    $('#bgslide_right').click(function(){
       window.clearInterval(bgSlideInterval);
       doSlide('right');
       slideInterval();
    });
   
});

function slideInterval(){
    bgSlideInterval = window.setInterval(function(){
        doSlide('right');
    }, bgFadeSpeed);
}

var bgFadeSpeed = 7000;
var abs;
var id;
var speed = 1500;
var next;
var direction = '';
var bgSlideInterval;
function doSlide(direction){
    id = $('#bgslides .active').attr('id');
    id = id.replace(/bgslide_/, '');
    
    if(direction == 'right'){
        if( (parseInt(id)+1) > abs ){
            next = 0;
        } else {
            next = parseInt(id) + 1;
        }
    }
    
    if(direction == 'left'){
        if( (parseInt(id)-1) < 0 ){
            next = abs;
        } else {
            next = parseInt(id) - 1;
        }
    }    
    
    $('#bgslides .active').fadeOut(speed).removeClass('active');
    $('#bgslide_' + next).fadeIn(speed).addClass('active');
}

function resize(){
    $('#bgslides').css({
        'height': ($('#wrapper').height() - 40) + 'px'
    });
    if($('#wrapper').width() > 1320){
      $('#bgslides').css({
          'left': (document.body.offsetWidth / 2) - (660) + 'px',
          'width': '1320px'
      });
    } else {
        $('#bgslides').css({
            'left': (document.body.offsetWidth / 2) - ($('#wrapper').width() / 2) + 'px',
            'width': $('#wrapper').width() + 'px'
        });
        
    }
}
