var pos = 0;
var max = 0;
var ids_str = '';
var ids = new Array();

var delay = 4000;
var pause = 10000;
var trans = 200;
var paused = false;

var btnLeft;
var btnRight;

var dir = true;

var t = false;

function init(i_delay, i_pause, i_trans) {
	
	if (max == 0) {
		
		delay = i_delay;
		pause = i_pause;
		trans = i_trans;
	
		max = $('#max').val();
		ids_str = $('#id').val();
		
		ids = ids_str.split('|');
		
		btnLeft = $('#btnLeft');
		btnRight = $('#btnRight');
		
		$('#ajax_load').hide();
	}
}

function getInfo() {
	var theID = ids[pos];
	
	$('#ajax_load').fadeIn();
	
	$.post (
		"/_template/market/getInfo.php"
		
		,	{
				'id' : theID
			}
		
		, 	function(data){
				$(data).find('product').each(function () {
					var name = $(this).children('name').text();
					var application = $(this).children('application').text();
					var chemistry = $(this).children('chemistry').text();
					var voltage = $(this).children('voltage').text();
					var weight = $(this).children('weight').text();
					var features = $(this).children('features').text();
					
					var img = new Image();
					
					$(img).load(function () {
						
						if (t != false) {
							clearTimeout(t);
						}
						
						if (paused) {
							t = setTimeout(moveAuto, pause);
							paused = false;
						} else {
							t = setTimeout(moveAuto, delay);
						}
						
						$('#fldImage').fadeTo(trans, 0, function () {
							
							$('#fldImage').empty();
							$('#fldImage').append(img);
							
							$('#fldImage').fadeTo(trans, 1, function () {
								$('#ajax_load').fadeOut();
							});
							
							$('#fldName').html(name);
							$('#fldApplication').html(application);
							$('#fldChemistry').html(chemistry);
							$('#fldVoltage').html(voltage);
							$('#fldWeight').html(weight);
							$('#fldFeatures').html(features);
							
						});
						
						
					}).attr('src', '/_images/_markets/' + theID + '.jpg').attr('class', 'market_image');
				});
			}
		,	"xml"
	);
}

function moveAuto() {
	if (dir) {
		if ((pos+1) < max) {
			pos++;
			
			getInfo();
			
			toggleButtons();
			
		} else {
			dir = false;
			moveAuto();
		}
	} else {
		if (pos > 0) {
			pos--;
			
			getInfo();
			
			toggleButtons();
			
		} else {
			dir = true;
			moveAuto();
		}
	}
}


function moveRight() {
	if ((pos + 1) < max) {
		pos++;
		
		getInfo();
		
		toggleButtons();
		
		paused = true;
	}
}

function moveLeft() {
	if (pos > 0) {
		pos--;
		
		getInfo();
		
		toggleButtons();
		
		paused = true;
	}
}

function toggleButtons() {
	$(btnRight).show();
	$(btnLeft).show();

	if ((pos + 1) == max) {
		$(btnRight).hide();
	} else if (pos == 0) {
		$(btnLeft).hide();
	}
}