var action, orgTableWidth, orgTableHeight;

function insertTable() {
	tinyMCEPopup.restoreSelection();

	var formObj = document.forms[0];
	var inst = tinyMCE.selectedInstance;
	var cols = 2, rows = 2, border = 0, cellpadding = -1, cellspacing = -1, align, width, height, className;
	var html = '';
	var elm = tinyMCE.tableElm;

	// Get form data
	cols = formObj.elements['cols'].value;
	rows = formObj.elements['rows'].value;
    heading = formObj.elements['heading'].checked;

	// Update table
	if (action == "update") {
		inst.execCommand('mceBeginUndoLevel');

		tinyMCE.setAttrib(elm, 'cellPadding', cellpadding, true);
		tinyMCE.setAttrib(elm, 'cellSpacing', cellspacing, true);
		tinyMCE.setAttrib(elm, 'border', border, true);
		tinyMCE.setAttrib(elm, 'align', align);
		tinyMCE.setAttrib(elm, 'class', className);
		tinyMCE.setAttrib(elm, 'style', style);
		tinyMCE.setAttrib(elm, 'id', id);
		tinyMCE.setAttrib(elm, 'summary', summary);
		tinyMCE.setAttrib(elm, 'dir', dir);
		tinyMCE.setAttrib(elm, 'lang', lang);

		// Not inline styles
		if (!tinyMCE.getParam("inline_styles"))
			tinyMCE.setAttrib(elm, 'width', width, true);

		// Remove these since they are not valid XHTML
		tinyMCE.setAttrib(elm, 'borderColor', '');
		tinyMCE.setAttrib(elm, 'bgColor', '');
		tinyMCE.setAttrib(elm, 'background', '');
		tinyMCE.setAttrib(elm, 'height', '');

		if (background != '')
			elm.style.backgroundImage = "url('" + background + "')";
		else
			elm.style.backgroundImage = '';

		if (tinyMCE.getParam("inline_styles"))
			elm.style.borderWidth = border + "px";

		if (tinyMCE.getParam("inline_styles")) {
			if (width != '')
				elm.style.width = getCSSSize(width);
		}

		if (bordercolor != "") {
			elm.style.borderColor = bordercolor;
			elm.style.borderStyle = elm.style.borderStyle == "" ? "solid" : elm.style.borderStyle;
			elm.style.borderWidth = border == "" ? "1px" : border;
		} else
			elm.style.borderColor = '';

		elm.style.backgroundColor = bgcolor;
		elm.style.height = getCSSSize(height);

		tinyMCE.handleVisualAid(tinyMCE.tableElm, false, inst.visualAid, inst);

		// Fix for stange MSIE align bug
		tinyMCE.tableElm.outerHTML = tinyMCE.tableElm.outerHTML;

		tinyMCE.handleVisualAid(inst.getBody(), true, inst.visualAid, inst);
		tinyMCE.triggerNodeChange();
		inst.execCommand('mceEndUndoLevel');

		// Repaint if dimensions changed
		if (formObj.width.value != orgTableWidth || formObj.height.value != orgTableHeight)
			inst.repaint();

		tinyMCEPopup.close();
		return true;
	}

	// Create new table
	html += '<table';
    html += makeAttrib('class', 'confluenceTable');
	html += '>';

    var inner = "";
    if (!tinyMCE.isMSIE)
    {
        inner = "&nbsp;";
    }

    for (var y=0; y<rows; y++) {
		html += "<tr>";

		for (var x=0; x<cols; x++)
        {
            if (heading && y == 0)
            {
                html += "<th class='confluenceTh'>" + inner + "</th>"
            }
            else
            {
                html += "<td class='confluenceTd'>" + inner + "</td>";
            }
        }

		html += "</tr>";
	}

	html += "</table>";

	inst.execCommand('mceBeginUndoLevel');
	inst.execCommand('mceInsertContent', false, html);
	tinyMCE.handleVisualAid(inst.getBody(), true, tinyMCE.settings['visual']);
	inst.execCommand('mceEndUndoLevel');

	tinyMCEPopup.close();
}

function makeAttrib(attrib, value) {
	var formObj = document.forms[0];
	var valueElm = formObj.elements[attrib];

	if (typeof(value) == "undefined" || value == null) {
		value = "";

		if (valueElm)
			value = valueElm.value;
	}

	if (value == "")
		return "";

	// XML encode it
	value = value.replace(/&/g, '&amp;');
	value = value.replace(/\"/g, '&quot;');
	value = value.replace(/</g, '&lt;');
	value = value.replace(/>/g, '&gr;');

	return ' ' + attrib + '="' + value + '"';
}

function init() {
	tinyMCEPopup.resizeToInnerSize();
    if (document.getElementById('backgroundimagebrowsercontainer'))
    {
        document.getElementById('backgroundimagebrowsercontainer').innerHTML = getBrowserHTML('backgroundimagebrowser','backgroundimage','image','table');
    }
    if (document.getElementById('bordercolor_pickcontainer'))
    {
        document.getElementById('bordercolor_pickcontainer').innerHTML = getColorPickerHTML('bordercolor_pick','bordercolor');
    }
    if (document.getElementById('bgcolor_pickcontainer'))
    {
        document.getElementById('bgcolor_pickcontainer').innerHTML = getColorPickerHTML('bgcolor_pick','bgcolor');
    }

    var cols = 2, rows = 2;
    var heading = true;
	var inst = tinyMCE.selectedInstance;
	var formObj = document.forms[0];
	var elm = tinyMCE.getParentElement(inst.getFocusElement(), "table");

	tinyMCE.tableElm = elm;
	action = tinyMCE.getWindowArg('action');
	if (action == null)
		action = tinyMCE.tableElm ? "update" : "insert";

	if (tinyMCE.tableElm && action != "insert") {
		var rowsAr = tinyMCE.tableElm.rows;
		var cols = 0;
		for (var i=0; i<rowsAr.length; i++)
			if (rowsAr[i].cells.length > cols)
				cols = rowsAr[i].cells.length;

		cols = cols;
		rows = rowsAr.length;

		st = tinyMCE.parseStyle(tinyMCE.getAttrib(tinyMCE.tableElm, "style"));
		orgTableWidth = width;
		orgTableHeight = height;

		action = "update";
	}

	// Update form
	formObj.cols.value = cols;
	formObj.rows.value = rows;
    formObj.heading.checked = heading;
	formObj.insert.value = tinyMCE.getLang('lang_' + action, 'Insert', true); 


	// Resize some elements
	if (isVisible('backgroundimagebrowser'))
		document.getElementById('backgroundimage').style.width = '180px';

	// Disable some fields in update mode
	if (action == "update") {
		formObj.cols.disabled = true;
		formObj.rows.disabled = true;
        formObj.heading.disabled = true;
	}
}