jQuery.fn.preload = function () {//preloading images
    jQuery('img', this).each(function() {
        var img = new Image();
        img.src = this.src; 
    });
}

//define the script globals
var s_size = 5,
	curr = 0,
	interval_id = 0;
	
var browser = navigator.userAgent.toLowerCase();

$(document).ready(function() {
	
	CenterBg();
	
	$('UL#thumbs LI').eq(0).addClass('now');
	
    $('#slides, #thumbs').preload();//preload slider images
	
    $('UL#thumbs LI').click(function(){
        StopAutoRotate();//stop slideshow
        go($(this).index());//go to the slide
    });

    $('.nav-btn').click(function(){
        StopAutoRotate();//stop slideshow
        var now = curr,
            to = $(this).hasClass('next') ? ++now : --now;//define next slide
        go(to);//go to the next slide
    });
	
    interval_id = setInterval(function(){//start slideshow
       go(curr + 1);
    }, 6000);
	
	$(window).resize(CenterBg);
});

function CenterBg() {
	
	if (browser.indexOf('ipad') < 0) {
		var minWidth = 940;
		var screenWidth = $(window).width();
		if (screenWidth < minWidth)
			screenWidth = minWidth;
			
		$('#slider').css({ 'margin-left': Math.round(-1 * (1400 - screenWidth) / 2) + 'px', 'width': '1400px'});
	}
}

function go(to) {
	if (to < 0 || to >= s_size) {//if slide not exists
		to = curr == 0 ? s_size - 1 : 0;//redefine the slide
	}
	
	if (to != curr) {//if the next slide isn't current
		curr = to;
		if (browser.indexOf('ipad') >= 0)
			$('#slides').animate({ 'margin-left' : (-1 * to * 1400 - 188) + 'px' }, 400, 'linear')
		else
			$('#slides').animate({ 'margin-left' : (-1 * to * 1400) + 'px' }, 400, 'linear')
		$('UL#thumbs LI').removeClass('now');
		$('UL#thumbs LI').eq(to).addClass('now');//activate the thumbnail
	}
}

function StopAutoRotate() {
	if (interval_id)
		clearInterval(interval_id);
}
