/*
 * Set-up Scroll class and internal static values
 */
var Scroller = new Class({

	// Initialise the class and internal values
	initialize: function(containerID) {
		if(containerID == ""  ) {
			// Not enough arguments were supplied
			alert('Scroller class not initialised correctly!');
			return false;
		}
		// Store the values supplied
		this.container_id = containerID;

		// Fetch the config data from the XML, which in turn (if sucessful) kicks-off everything else
		this.fetch_config_data();
	},

	// Fetch configuration data
	fetch_config_data: function() {
		var req = new Request({
			method: 'get',
			data: {
				'do' : '1'
			},
			onRequest: function() {
				// Display loading message
				$(this.container_id).innerHTML = '<div style="padding:4px;">Loading...</div>';
			}.bind(this),
			onFailure: function() {
				// Clear loading message
				$(this.container_id).innerHTML = '';
			}.bind(this),
			onSuccess: function(responseText, responseXML) {
				this.setup_html();
			}.bind(this)
		}).send();
	},

	// Set-up image mouseover listeners
	setup_listeners: function() {
		$$('#' + this.container_id + ' img').addEvent('mouseover', function() {
			Scroller.allow_movement = false;
		});
		$$('#' + this.container_id + ' img').addEvent('mouseout', function() {
			clearTimeout(Scroller.start_timer);
			Scroller.allow_movement = true;
			Scroller.start_timer = setTimeout("Scroller.prototype.start_left();", 500);
		});
	},

	// Code contained in a function because it is used in more than one place
	return_htmltable: function(i) {
		return new HtmlTable({
			properties: {
				id: 'walker' + i,
				border: 0,
				cellspacing: 0,
				cellpadding: 0,
				style: 'position: absolute'
			}
		});
	},

	// Set-up the html to display
	setup_html: function() {
		// Make sure we have a valid number when scrolling
		//Scroller.speed = this.fetch_xml_item('imageSpeed');
		Scroller.speed = '25';
		if(Scroller.speed === false  ||  Scroller.speed <= 0) {
			alert('Scroll speed supplied is invalid: "' + Scroller.speed.toString() + '"');
			return false;
		}

		// Make sure we have some images to display
		//var total_number_of_images = this.fetch_xml_item('advert', true);

		if(total_number_of_images === false  ||  total_number_of_images == 0) {
			// There are no images!?
			return false;
		}

		// Loop through each image and store the html
		var scrollable = true;
		var cell_content = [];
		var total_widths_per_element = [];
		var total_width_of_imagery = 0;
		for(var i=0; i<activeAds.length; i++) {
			// Fetch the values we need for each image and link
			var image_src = activeAds[i][0];
			var image_height = activeAds[i][1];
			var image_width = activeAds[i][2];
			var image_alt = activeAds[i][3];
			var link_href = activeAds[i][4];
			var link_target = activeAds[i][5];
			var link_title = activeAds[i][6];
			
			if(image_src === false  ||  image_src == '') {
				alert('Image location supplied is invalid: "' + image_src.toString() + '"');
				return false;
			}
			if(image_height === false  ||  image_height == 0  ||  isNaN(parseInt(image_height))) {
				alert('Image height supplied is invalid: "' + image_height.toString() + '"');
				return false;
			}
			if(image_width === false  ||  image_width == 0  ||  isNaN(parseInt(image_width))) {
				alert('Image width supplied is invalid: "' + image_width.toString() + '"');
				return false;
			}

			// Cache the total width of all the images
			total_widths_per_element[i] = parseInt(image_width) + parseInt(image_spacing);

			// Start to build the image html
			var html = '<img src="' + image_src + '" alt="';
			if(image_alt !== false  &&  image_alt != "") {
				html += image_alt;
			}
			html += '" width="' + image_width + '" height="' + image_height + '" style="margin: ' + (Math.ceil((container_height - image_height)/2)) + 'px 0 0 ' + image_spacing + 'px" />';

			// Check to see if we have a link for this image
			if(link_href !== false  ||  link_href != '') {
				var link_html = '<a href="' + link_href + '"';
				if(link_target !== false  &&  link_target != "") {
					link_html += ' target="' + link_target + '"';
				}
				if(link_title !== false  &&  link_title != "") {
					link_html += ' title="' + link_title + '"';
				}
				html = link_html + '>' + html + '</a>';
			}

			// Store the html ready to be added to the table later
			cell_content.extend([html]);
		}
		total_width_of_imagery = total_widths_per_element.sum();

		// How many containers are required?
  		// - For this to work, we need more than 1.5 when calculating the following: 'total image width' / 'container width'
		var overlap_calc = (total_width_of_imagery / container_width);
		if(overlap_calc < 1) {
			// We are unable to scroll the imagery
			overlap_calc = 1;
			scrollable = false;
		} else if(overlap_calc < 1.5) {
			// We need to duplicate the imagery
			overlap_calc = 1;
		} else if(overlap_calc >= 1.5  &&  overlap_calc < 2) {
			overlap_calc = 3;
		} else {
			overlap_calc = 2;
		}

		// Setup the containing tables
		var htmlTables = [];
		for(var i=0; i<overlap_calc; i++) {
			// Build the tables used to contain the imagery
			htmlTables[i] = this.return_htmltable(i);
		}

		// Add the rows to the tables (this works best when all the images are the same width)
		var min_container_width = (total_width_of_imagery / overlap_calc);
		var cells_per_table = [], cells_per_table_backup = [];
  		var table_index = 0;
		var total_widths = [];
		total_widths[table_index] = 0;
		for(i=0; i<cell_content.length; i++) {
			if(total_widths[table_index] >= min_container_width) {
				// Add the html to the table
				htmlTables[table_index].push([cells_per_table]);
				// Update the table index
				table_index++;
				// Reset the container counter and html collected
				cells_per_table.empty();
				total_widths[table_index] = 0;
			}
			cells_per_table.extend([cell_content[i]]);
			total_widths[table_index] += total_widths_per_element[i];
		}
		// Mop-up any left-overs
		if(cells_per_table.length > 0) {
			htmlTables[table_index].push([cells_per_table]);
		}

		// If there is only one table and we're allowed to scroll lets double-up
		if(overlap_calc == 1  &&  scrollable) {
			// Duplicate the one table created so we have two
			var i = htmlTables.length;
			htmlTables[i] = this.return_htmltable(i);
			htmlTables[i].push([cells_per_table]);
			total_widths[i] = total_widths[(i-1)];
			total_width_of_imagery += total_width_of_imagery;
		}

		// Add the necessary style elements to the container
		$(this.container_id).setStyle('position', 'relative');
		$(this.container_id).setStyle('overflow', 'hidden');
		if(container_width !== false  &&  container_width != 0) {
			$(this.container_id).setStyle('width', container_width + 'px');
		}
		if(container_height !== false  &&  container_height != 0) {
			$(this.container_id).setStyle('height', container_height + 'px');
		}
		if(class_name !== false  &&  class_name != "") {
			$(this.container_id).addClass(class_name);
		}
		if(container_border_width !== false  &&  container_border_width != ''  &&  container_border_style !== false  &&  container_border_style != ''  &&  container_border_colour !== false  &&  container_border_colour != '') {
			$(this.container_id).setStyle('border', container_border_width + ' ' + container_border_style + ' ' + container_border_colour);
		}

		// Remove loading message
		$(this.container_id).innerHTML = '';

		// Add the html to the page
		for(var i=0; i<htmlTables.length; i++) {
			// Add the html to the page
			htmlTables[i].inject($(this.container_id));
			// Position the html correctly
			var left_position = 0;
			if(i > 0) {
				var ii = i;
				while(ii > 0) {
					left_position += total_widths[i-1];
					ii--;
				}
			}
			$('walker' + i).setStyle('width', total_widths[i]);

			// Are there enough images to scroll?
			if(!scrollable) {
				// If not, we need to make sure the images are centred within the container
				// - assumes in this scenario there is only one set of images, var: ''overlap_calc''
				var centred = container_width - total_width_of_imagery;
				centred = Math.ceil(centred / 2);
				$('walker' + i).setStyle('left', centred);
				// As per the assumption, there is only one container so we can leave this loop and exit the function
				return false;
			}
			// Kick-off the movement of each of the two containers, making sure the html is in place before we start
			$('walker' + i).setStyle('left', left_position);
			Scroller.element_cache[Scroller.element_cache.length] = ['walker' + i, total_widths[i], total_width_of_imagery];
		}
		setTimeout("Scroller.prototype.start_left();", 1000);
		this.setup_listeners();
	}

});


// Control movement
Scroller.speed = 0;
Scroller.element_cache = [];
Scroller.allow_movement = true;
Scroller.start_timer = null;

Scroller.prototype.start_left = function() {
	Scroller.element_cache.each(function(val, key){
		Scroller.prototype.go_left(val[0], val[1], val[2]);
	});
}
Scroller.prototype.go_left = function(elID1, w1, w2) {
	// Should we be moving the scroller?
	if(!Scroller.allow_movement) {
		return false;
	}
	// Fetch the container as an object
	el = $(elID1);
	// Move the container left by 1 pixel
	el.setStyle('left', parseInt(el.style.left)-1);
	// Is the container out of sight?
	if(parseInt(w1) + parseInt(el.style.left) < 0) {
		// As soon as a container is out of sight, move it to the end
		el.setStyle('left', parseInt(w2-w1));
	}
	// Run the movement code again in 'x' milliseconds
	setTimeout("Scroller.prototype.go_left('" + elID1 + "', '" + w1 + "', '" + w2 + "');", Scroller.speed);
}