<div id="addTableDialog" class="modal fade">
	<input id="editMode" type="hidden" value=""></input>
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
        <h4 class="modal-title">Table Name: <span id="tableName"></span></h4>
      </div>
      <div class="modal-body form-inline">
        <input autofocus="true" id="fieldName" style="width:110px;" class="form-control" type="text" placeholder="Field name"></input>
        <select id="fieldType" class="form-control" type="text" onchange="if ($('#fieldType').val()!='String' && $('#fieldType').val()!='Text') $('#fieldSize').attr('disabled',''); else $('#fieldSize').removeAttr('disabled');">
			<option value="Text">Text</option>
			<option value="LONGTEXT">mysql.LONGTEXT</option>
			<option value="String">String</option>
			<option value="Date">Date</option>
			<option value="Integer">Integer</option>
			<option value="BIGINT">mysql.BIGINT</option>
			<option value="BIGINT(unsigned=True)">mysql.BIGINT(unsigned)</option>
			<option value="Float">Float</option>
		</select>
        <input id="fieldSize" style="width:70px;" class="form-control" type="number" min="0" placeholder="size" value=""></input>
        <input id="fieldDefault" style="width:100px;" class="form-control" type="text" placeholder="Default" value=""></input>
        <input id="fieldPrimary" class="form-control" type="checkbox" value="primary">Primary</input>
        <input id="fieldUnique" class="form-control" type="checkbox" value="unique">Unique</input>
		
		<p></p>
        <button style="text-align:right;" type="button" class="btn btn-success" onclick="addField();">Add Field</button>
		<p></p>
		<table id="fields" class="table table-striped">
			<tr>
				<th>Name</th>
				<th>Type</th>
				<th>Size</th>
				<th>Details</th>
				<th>Action</th>
			</tr>
		</table>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary" onclick="saveData();">Save changes</button>
	</div>
		<div class="alert alert-info" role="alert">
		<small>Note: Use <kbd>tab</kbd> key to navigate through the widgets.</small>
		</div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

<script>
//$("#fieldName").focus();
document.getElementById("fieldName").focus();
//console.log("Focussed");

$("#addTableDialog").on('hidden.bs.modal', function(e){
	console.log(this.data);
});

function saveData() {
	if ($('.fieldRow').length==0) {
		alert('There must be at least one field.');
		return;
	}
	//alert($('#editMode').val());
	var table;
	if ($('#editMode').val() == "add") {
		if (tables[$('#tableName').text()] != undefined){
			alert('This table already exists.');
			return;
		}
		table = new Table();
	}
	else if ($('#editMode').val() == "edit") {
		table = tables[$('#tableName').text()];
	}
	else {
		alert("Unexpected value!");
		return;
	}
	
	table.name = $('#tableName').text();
	
	//remove old endpoints
	window.oldrefs = {};
	if ($('#editMode').val() == 'edit') {
		jsPlumb.detachAllConnections($('#tbl' + table.name + " .table"));
		window.oldrefs = {};
		$.each(tables[table.name].fields, function(k,v) {
			//preserve existing relations
			window.oldrefs[v.name] = {};
			window.oldrefs[v.name]['foreign'] = v.foreign;
			window.oldrefs[v.name]['ref'] = v.ref;
			console.log('oldref backing up',v.name,v.foreign,v.ref);
			
			//console.log(v.ep);
			//elist1 = jsPlumb.selectEndpoints({target:$("#tbl" + tsa[0] +  " div[ffname='" + tsa[0] + "." + tsa[1] +  "']")});
			
			//jsPlumb.deleteEndpoint(v.ep);
			//console.log('deleted ep for',v.name);
		});
		jsPlumb.empty($('#tbl' + table.name + " .table"));
	}
	
	table.fields={};
	//First update the data model!
	$('.fieldRow').each(function(index) {
		var isPrimary = Boolean($(this).find(".hfieldPrimary").text());
		var isUnique = 	Boolean($(this).find(".hfieldUnique").text());
		var defaultValue = $(this).find(".hfieldDefaultValue").text();
		console.log($(this).find(".fieldName").text(), 'primary: ' + $(this).find(".hfieldPrimary").text());
		console.log($(this).find(".fieldName").text(), 'unique: ' + $(this).find(".hfieldUnique").text());
		console.log("DATA_TYPE",$(this).find(".fieldType").val());
		
		table.fields[$(this).find(".fieldName").text()] = new Field({ 
			name: $(this).find(".fieldName").text(),
			type: $(this).find(".fieldType").text(),
			size: $(this).find(".hfieldSize").text(),
			primaryKey: isPrimary,
			unique: isUnique,
			defaultValue:  (defaultValue=="" ? null : defaultValue)
			});
	});
	
	
	tables[table.name] = table;
	$("#addTableDialog").modal('hide');
	
	
	//Now Build the new panel!
	createThePanel(table, $('#editMode').val(), null);
}


/**
* Creates a new field from the input boxes and adds to the display.
*/
function addField()
{
	if ($("#fieldSize").val() =="" || $("#fieldSize").attr('disabled')) $("#fieldSize").val(0);
	var sizeValid = parseInt($("#fieldSize").val()) >= 0;
	if ($("#fieldName").val().trim() == "") {
		alert("Field name cannot be blank.");
		return;
	}
	else if ($('#fieldName').val().indexOf(" ")>=0) {
		alert("Field cannot contain a special character or space.");
		return;
	}
	else if (!sizeValid) {
		alert("Not a valid size.");
		return;
	}
	else if ($("#" + $("#fieldName").val()).length >0) {
		alert("This element already exists.");
		return;
	}
	var html = "<tr class='fieldRow' id='" + $("#fieldName").val() + "'>";
	html += "<td class='fieldName'>" + $("#fieldName").val() + "</td>";
	html += "<td class='fieldType'>" + $("#fieldType").val() + "</td>";
	var size = $("#fieldSize").val();
	html += "<td class='fieldSize'>" + (size==0 ? "-" : size)  + "</td>";
	var details;
	//details  =($("#fieldPrimary:checked").length==0 ? "" : "primary ");
	//details  += ($("#fieldUnique:checked").length==0 ? "" : "unique");
	var isPrimary = $("#fieldPrimary").is(':checked');
	var isUnique = $("#fieldUnique").is(':checked');
	details  =(isPrimary ? "primary," : "");
	details  += (isUnique ? "unique," : "");
	
	details  += ($("#fieldDefault").val() == "" ? "" : "," + $("#fieldDefault").val());
	html += "<td class='fieldDetails'>" + details  + "</td>";
	html += "<td class='hidden hfieldSize'>" + size  + "</td>";
	html += "<td class='hidden hfieldDefaultValue'>" + $("#fieldDefault").val()  + "</td>";
	html += "<td class='hidden hfieldPrimary'>" + (isPrimary ? 'true' : '')  + "</td>";
	html += "<td class='hidden hfieldUnique'>" + (isUnique ? 'true' : '')  + "</td>";
	html += "<td class='delete'><button onclick='tryToDelete(\"" + $("#fieldName").val() + "\")' title='Delete Field' class='btn btn-xs btn-danger'><span class='glyphicon glyphicon-remove'></span></button></td>";
	html += "</tr>";
	
	$("#fields").append(html);
	$("#fieldName").val("");
	$("#fieldSize").val("");
	$('#fieldSize').removeAttr('disabled');
	$('#fieldType').val("Text");
	$('#fieldDefault').val('');
	$('#fieldPrimary').removeAttr("checked");
	$('#fieldUnique').removeAttr("checked");	

	$("#fieldName").focus();
}

function tryToDelete(fieldName) {
	//TODO: Check this is not working
	for (conn in jsPlumb.getAllConnections()) {
		var tname = $('#tableName').text();
		var existing = tables[tname].fields[fieldName];
		//if ($(conn.source).attr('ffname') == $("#tableName").text() + '.' + fieldName) {
		if (existing!=undefined && existing.foreign != null) {
			alert("This key is acting as a primary key in a relation. Please delete that relation first.");
			return;
		}
		//else if ($(conn.target).attr('ffname') == $("#tableName").text() + '.' + fieldName) {
		else if (existing!=undefined && existing.ref != null) {
			alert("This key is acting as a foreign key in a relation. Please delete that relation first.");
			return;
		}
	}
	//jsPlumb.remove($('#' + fieldName));
	//jsPlumb.remove('#' + fieldName);
	$('#' + fieldName).remove();
}
</script>

<style>
#fields td,
#fields th
 {
	padding-top: 4px;
	padding-bottom: 4px;
}
</style>