var idx = 0;
var imgs = new Array();
var txts = new Array();
var lnks = new Array();
var intervalHandler;
var $overlay;

function init_slideshow(div, timeout, path, eID) {
	$.ajax({
		url: 'index.php?eID='+eID,
		data: 'imgDir=' + encodeURIComponent(path),
		datatype: 'application/json',
		success: function(data) {
			__init_slideshow(div, timeout, data.imgs, data.txts, data.lnks);
		},
		error: function(jqXHR, textStatus, errorThrown) {
			alert('ERROR: ' + textStatus);
		}
	});
}

function click_slideshow(event) {
	clearInterval(intervalHandler);
	target = event.target ? event.target : event.srcElement;
	pos = event.clientX - $(target).offset().left;
	pos = parseInt(pos / 22);
	__slider_move(pos);
}

function __init_slideshow(div, timeout, imgNames, txtStrings, links) {
	$overlay = $('div.banderolle > div.overlay');
	$.each(imgNames, function(i, name) {
		img = new Image();
		img.src = name;
		img.alt = name;
		img.title = name;
		if (i != 0) {
			$(img).css('display', 'none');
		} else {
			$overlay.click(function(event) { 
				__open_link(links[i]);
			});
		}
		imgs.push(img);
		if (links != undefined) {
			lnks[i] = links[i];
		}
		$('#'+div).append(img);
	})
	$.each(txtStrings, function(i, txt) {
		txts.push(txt);
		if (i == 0) {
			$('#overlayText').html(txt);
		}
	})
	if (links != undefined) {
		$overlay.css('cursor', 'pointer');
	}
	$('#slider').css('width', 22 * imgNames.length + 'px');
	$('#slider').css('cursor', 'pointer');
	$('#slider').click(function(event) { 
		click_slideshow(event.target ? event : window.event);
	});
	intervalHandler = setInterval('__slide()', timeout);
}

function __slide() {
	pos = (idx + 1) % imgs.length;
	__slider_move(pos);
}

function __slider_move(pos) {
	$('#slider').unbind('click');
	$(imgs[idx]).fadeOut('normal', function() {
		idx = pos;
		imgName = imgs[idx].src;
		textName = imgName.substr(0, imgName.length - 3).concat('txt');
		$('#overlayText').html(txts[idx]);
		if (lnks.length > 0) {
			$overlay.unbind('click');
			$overlay.click(function(event) { 
				__open_link(lnks[idx]);
			});
		}
		$('#sliderfg').css('margin-left', idx * 22 + 'px');
		$(imgs[idx]).fadeIn('normal', function() {
			$('#slider').click(function(event) {
				click_slideshow(event.target ? event : window.event);
			});
		});
	})
}

function __open_link(href) {
	if (href) {
		if (href.indexOf('http') == 0) {
			if (document.domain == 'www.redbullmobile.pl') {
				var nWin = window.open(href, '_blank', 'width=1090,height=750,left=0,top=0,location=yes,scrollbars=yes,status=yes');
			} else {
				var nWin = window.open(href, '_blank', 'width=820,height=600,left=100,top=200,location=yes,scrollbars=yes,status=yes');
			}
			if(nWin) {
				nWin.focus();
			}
		} else if (href.indexOf('/') == 0) {
			window.location.href = href;
		} else {
			window.location.href = window.location.protocol + '//' + href;
		}
	}
}


