﻿//DESRCRIPTION: Merge tables
//Peter Kahrel

(function () {


	function merge_tables () {
		var i;
		var tables = app.selection[0].parentStory.tables.everyItem().getElements();

		function merge (target, source) {
			var i, j;
			var targetCells;
			var texts;
			var sourceRows = source.rows.everyItem().getElements();
			for (i = source.headerRowCount; i < sourceRows.length; i++) {
				targetCells = target.rows.add().cells.everyItem().getElements();
				texts = sourceRows[i].cells.everyItem().texts.everyItem().getElements()
				for (j = 0; j < texts.length; j++) {
					texts[j].move (LocationOptions.AFTER, targetCells[j].insertionPoints[0]);
				}
			}
		}

		
		for (i = 1; i < tables.length; i++) {
			merge (tables[0], tables[i]);
		}

		for (i = tables.length-1; i > 0; i--) {
			tables[i].remove();
		}
	}


	if (app.documents.length === 0 || app.selection.length === 0 || app.selection[0].tables.length === 0) {
		alert ("Select a story or some text containing more than one table.");
		exit();
	}

	merge_tables();

}());