// Ace Code Editor
var editor = ace.edit('editor');
editor.setOptions({
	mode: "ace/mode/ruby",
	showPrintMargin: false,
	minLines: 36,
	maxLines: 36,
	tabSize: 2,
	fontSize: "2.2vh",
	fontFamily: "Courier New",
	autoScrollEditorIntoView: true
});

function selectedObject() {
	editor.getSession().setValue(document.getElementById('script').value);
	editor.getSession().on("change", function() {
		document.getElementById('script').value = editor.getSession().getValue();
		timer = setTimeout(function() {
			if(document.getElementById('script')) {
				var hST_id = document.getElementById('script').getAttribute('id');
				var hST_name = document.getElementById('script').getAttribute('name');
				window.location = 'skp:setAttributeString@' + hST_name + '=' + hST_id;
			}
		}, 300);
	});
	document.getElementById('childObjectsContainer').style.border = '1px solid #777';
	document.getElementById('editor_panel').style.border = '1px solid #777';
	document.getElementById('editorDiv').style.display = 'block';
	document.getElementById('editor_script_check_box').checked = document.getElementById('inspector_script_check_box').checked;
}

function hideEditor() {
	document.getElementById('editorDiv').style.display="none";
}

function checking_iscb() {
	var iscb = document.getElementById('inspector_script_check_box');
	iscb.checked = document.getElementById('editor_script_check_box').checked;
	window.location = 'skp:setAttributeBool@' + iscb.getAttribute('name') + '=' + iscb.checked;
}

function checking_escb(ch) {
	document.getElementById('editor_script_check_box').checked = ch;
}

// "Purge unused", "Delete guides" and "Clear console panel" buttons
function cleaner_buttons(value) {
	window.location = 'skp:cleaner_buttons@' + value;
}

// Theme changer
// Get theme attribute
function getAceTheme(attribute) {
	editor.setOptions({ theme: "ace/theme/" + attribute });
	document.getElementById('themeChanger').value = attribute;
}
// Set theme attribute
document.getElementById('themeChanger').onchange = function() {
	editor.setOptions({ theme: "ace/theme/" + this.value });
	window.location='skp:setAceTheme@' + this.value;
}

// Joints hiding
// Get attribute
function getHideJoints(attribute) {
	document.getElementById('hide_joints').checked = JSON.parse(attribute); // 'true' => true
}
// Set attribute
function setHideJoints() {
	window.location = 'skp:setHideJoints@' + document.getElementById('hide_joints').checked;
}

// Controller Panel hiding
// Get attribute
function getHideCPanel(attribute) {
	document.getElementById('hide_cpanel').checked = JSON.parse(attribute);
}
// Set attribute
function setHideCPanel() {
	window.location = 'skp:setHideCPanel@' + document.getElementById('hide_cpanel').checked;
}

// Menu changer
// Get attribute from settings_ui.rb and .html
function getMenu(attribute) {
	selected_menu(attribute);
}
// Set attribute from settings_ui.html
function setMenu(attribute) {
	window.location = 'skp:setMenu@' + attribute;
}

function selected_menu(attribute) {
	if (attribute == 'inspector') {
		document.getElementById('menu_1').className = "visible";
		document.getElementById('menu_2').className = "hidden";
		document.getElementById('menu_3').className = "hidden";
		document.getElementById('inspector_panel').className = "visible";
		document.getElementById('editor_panel').className = "hidden";
		document.getElementById('sound_panel').className = "hidden";
		document.getElementsByTagName('body')[0].style.overflowY = "scroll";
	}
	if (attribute == 'editor') {
		document.getElementById('menu_1').className = "hidden";
		document.getElementById('menu_2').className = "visible";
		document.getElementById('menu_3').className = "hidden";
		document.getElementById('inspector_panel').className = "hidden";
		document.getElementById('editor_panel').className = "visible";
		document.getElementById('sound_panel').className = "hidden";
		document.getElementsByTagName('body')[0].style.overflowY = "hidden";
		if(document.getElementById('script')) editor.getSession().setValue(document.getElementById('script').value);
	}
	if (attribute == 'sounds') {
		document.getElementById('menu_1').className = "hidden";
		document.getElementById('menu_2').className = "hidden";
		document.getElementById('menu_3').className = "visible";
		document.getElementById('inspector_panel').className = "hidden";
		document.getElementById('editor_panel').className = "hidden";
		document.getElementById('sound_panel').className = "visible";
		document.getElementsByTagName('body')[0].style.overflowY = "auto";
	}
}

function hideChecks(state) {
	if (state == '_true') document.getElementById('checks').style.display = 'none';
	else document.getElementById('checks').style.display = 'block';
}

function callback(name, data) {
	if (!data) data = '';
	window.location.href = 'skp:' + name + '@' + data;
}

function open_link(ref) {
	window.open(ref, "_blank");
}

function open_ruby_core(ref) {
	callback('open_ruby_core');
	return false;
}

//Tell sketchup window is closing
function windowCloseing() {
	//Call the Sketchup callback
	window.location='skp:windowClosed@';
}

//Functions that feed data back to Sketchup ruby.
function setSkpAttribute(attribute,value) {
	lastEditedElement=null
	window.location='skp:setAttribute@'+attribute+'='+value;
}

function setSkpAttributeString(attribute, value) {
	lastEditedElement=null
	window.location='skp:setAttributeString@'+attribute+'='+value;
}

function setSkpAttributeString2(attribute, value) {
	lastEditedElement=null
	window.location='skp:setAttributeString2@'+attribute+'='+value;
}

function setSkpAttributeBool(attribute, value) {
	lastEditedElement=null
	window.location='skp:setAttributeBool@'+attribute+'='+value;
}

function evalToNumeric(name) {
	window.location = 'skp:evalToNumeric@' + name;
}

//Helper functions for creating a table that changes shape as the area changes.
//Use to for the State section checkboxes.
function clearFlowTable(tblID) {
	tbl=document.getElementById(tblID);
	while(tbl.rows.length>0) {
		tbl.deleteRow(0);
	}
}

function addFlowTableHeader(tblID,text) {
	tbl=document.getElementById(tblID);
	row=tbl.insertRow(tbl.rows.length);
	cell=row.insertCell();
	cell.colSpan=1;
	cell.innerHTML="<p>"+text+"</p>";
	row=tbl.insertRow(tbl.rows.length);
}

function addFlowTableCell(tblID,id,name,html) {
	tbl=document.getElementById(tblID);

	row=null;
	if (tbl.rows.length==0)
	row=tbl.insertRow(tbl.rows.length);
	else
	row=tbl.rows(tbl.rows.length-1);

	if (row.cells.length>3)
	row=tbl.insertRow(tbl.rows.length);
	cell=row.insertCell();
	cell.innerHTML=html;
	cell.id=id;
	cell.name=name;
	cell.onclick=function()  {window.location='skp:onSelectJoint@'+this.id+','+this.name;selectTableCell(tblID,id)}
}

function selectTableCell(tblID,cellID) {
	tbl=document.getElementById(tblID);
}

function setDivVisibility(divid,bVisible) {
	//toggleDiv(divid)
	//return;
	if (bVisible) {
		document.getElementById(divid).style.display = 'block';
	}
	else {
		document.getElementById(divid).style.display = 'none';
	}
}

function toggleDiv(divid) {
	if (document.getElementById(divid).style.display == 'none') {
		document.getElementById(divid).style.display = 'block';
	}
	else {
		document.getElementById(divid).style.display = 'none';
	}
}

//Helper functions for verifying input.
function getCaretPosition(element) {
	// To get cursor position, get empty selection range
	var oSel = document.selection.createRange();

	// Move selection start to 0 position
	oSel.moveStart('character', -element.value.length);

	// The caret position is selection length
	iCaretPos = oSel.text.length;

	return(iCaretPos);
}

function isDigit (evt) {
	var keyCode = evt.which ? evt.which : evt.keyCode;
	digit = !isNaN ( parseInt ( String.fromCharCode ( keyCode ) ) ) ||
	( keyCode == 190 || keyCode == 110 ) ||
	( keyCode >= 8 && keyCode <= 46 &&
	keyCode !=16 && keyCode !=32 );

	ie4up=true;
	digit = ie4up ? digit || ( keyCode >= 96 && keyCode <=105 ) : digit;
	return ( digit );
}

function markDirty(element,name,value) {
	//puts("onChange:"+name+"="+value)
	lastEditedElement=element
	window.location='skp:valueUpdated@'+name+"="+value;
}
function validateNumber() {
	//lastEditedElement=event.srcElement
	if (event.keyCode==45 && getCaretPosition(event.srcElement)==0) {
		//puts("Caret at"+getCaretPosition(event.srcElement))
		lastEditedElement=event.srcElement
		return;
	}

	if (event.keyCode==46 && event.srcElement.value.indexOf(".")==-1) {
		lastEditedElement=event.srcElement
		return;
	}
	if ((event.keyCode < 48) || (event.keyCode > 57))
	event.returnValue = false;
}

//Functions to allow name/value pairs to made into editable html tables.
//These are used to build editable properties and text field sections.
function clearPropertyGrid() {
	while(propertyGridTable.rows.length>0) {
		propertyGridTable.deleteRow(0);
	}
}

function addPropertyGridHeader(text) {
	th = document.createElement("TH");
	th.innerHTML = text;
	th.colSpan=2;
	tr=document.getElementById('propertyGridTable').insertRow();
	tr.appendChild(th);
}

function addPropertyGridRow(id, name,value,type) {
	tbl=document.getElementById('propertyGridTable')

	tr=tbl.insertRow();
	td=tr.insertCell();
	td.innerHTML=name;
	td=tr.insertCell();

	switch(type) {
		case "float":
		case "string":
		case "static":
		td.innerHTML=value;
		break;
		case "int":
		var textInput=document.createElement('input');
		textInput.setAttribute('type','text');
		textInput.setAttribute('value',value);
		textInput.align="right";
		textInput.name=name;
		td.appendChild(textInput);
		break;

		case "bool":
		var boolInput=document.createElement('input');
		boolInput.setAttribute('type','checkbox');
		td.appendChild(boolInput);
		break;

		case "bools":
		boolSelect=document.getElementById('trueFalseSelect').cloneNode(true)
		td.appendChild(boolSelect);
		break;
	}
}
//Clear form called by ruby anytime the form needs a full refresh.
function clearForm() {
	clearFlowTable('parentJointsContainer');
	clearFlowTable('childJointsGrid');
	document.getElementById('childObjectsContainer').innerHTML="";
	document.getElementById('childObjectsContainer').style.border="0";
	document.getElementById('childJointProperties').innerHTML="";
	document.getElementById('stateContainer').innerHTML="";
	document.getElementById('propertiesContainer').innerHTML="";
	document.getElementById('propertiesTitle').innerHTML="";
	document.getElementById('shapesTitle').innerHTML="";
	document.getElementById('jointsTitle').innerHTML="";
	document.getElementById('mainDiv').style.display="none";
	document.getElementById('no_selected2').style.display="block";
	document.getElementById('editorDiv').style.display="none";
	document.getElementById('editor_panel').style.border="0";
}

function visibleForm() {
	document.getElementById('mainDiv').style.display="block";
	document.getElementById('no_selected2').style.display="none";
}

//do a clear on page load.
clearForm();

//This javascript function will print a message in the Ruby console
function puts(str) {
	window.location='skp:puts@'+str;
}

//place to save the last edited element so it can be sent if the window blurs.
var lastEditedElement=null

//onblur handler
function handleWindowBlur() {
	var ua = navigator.userAgent.toLowerCase();
	if ( ua.indexOf( "mac" ) != -1 ) {
		//puts ("Mac onblur")
		if (lastEditedElement!=null) {
			lastEditedElement.onchange()
			lastEditedElement=null
		}
	}
}

//Hook up window onblur event.
window.onblur = function() {
	handleWindowBlur();
}

// ========= Sound ==============================================

function addToSelection(value1, value2, list_type) {
	var select = document.getElementById(list_type);
	select.options[select.options.length] = new Option(value2, value1);
}

function showSoundInfo() {
	var select = document.getElementById("sound_list");
	if (select.selectedIndex>-1) {
		var chosenoption = select.options[select.selectedIndex].value
		document.mainFrame.play.value="@channel_1 = playSound('"+chosenoption+"')"
	}
}

function embedSound() {
	window.location = "skp:embed_sound@";
}

function playSound(list_type) {
	var select = document.getElementById(list_type);
	if (select.selectedIndex>-1) {
		var chosenoption = select.options[select.selectedIndex].value
		window.location = "skp:play_sound@"+list_type+"|"+chosenoption;
	}
}

function stopSound() {
	window.location = "skp:stop_sound@";
}

function removeSound(list_type) {
	var select = document.getElementById(list_type);
	if (select.selectedIndex>-1) {
		var chosenoption = select.options[select.selectedIndex].value
		window.location = "skp:remove_sound@"+list_type+"|"+chosenoption;
	}
}

function removeSelectionItem(variable, list_type) {
	var elSel = document.getElementById(list_type);
	var i;
	for (i = elSel.length-1; i>=0; i--) {
		if (elSel.options[i].value==variable) {
			elSel.remove(i);
		}
	}
}

// HTML is loaded
function loaded() {
	window.location = "skp:html_loaded@";
}