
load "w2t";

var page = new W2t();


// --------------------------- Calculator ---------------------------

object Calculator
{
	static calculator_counter = 0;

	var myid;
	var mypage;

	var value = 0;
	var op_prefix = undef;

	method init(_page)
	{
		mypage = _page;
		myid = mypage.getid();

		mypage.register_callback("${myid}_action", function(c, op, val)
		{
			switch
			{
			case not defined op_prefix: value = val;
			case op_prefix ~== "add": value .+= val;
			case op_prefix ~== "sub": value .-= val;
			case op_prefix ~== "mul": value .*= val;
			case op_prefix ~== "div": value ./= val;
			case op_prefix ~== "mod": value .%= val;
			case op_prefix ~== "pow": value .**= val;
			}

			op_prefix = op ~== "equal" ? undef : op;
			page.execute("document.getElementById('${myid}_value').value = $value");
		});

		mypage.register_callback("${myid}_close", function() {
			page.dom_remove(myid);
		});

		mypage.dom_appendchild("calcs", <:>
			: <form id="${myid}" xmlns="${page.xmlns.xhtml}" class="calculator">
			:	<h3>Calculator #${calculator_counter++}</h3>
			:	<input id="${myid}_value" value="$value" onclick="${myid}_value.value = ''"/>
			<spl:foreach var="[]op" list="[ add: '+', sub: '-', mul: '*', div: '/', mod: '%', pow: '**', equal: '=' ]">
			:	<button	w2t:callbacks="${myid}_action" onclick="w2t_callback('${myid}_action', [ '$#', ${myid}_value.value ]);">$op</button>
			</spl:foreach>
			:	<button	w2t:callbacks="${myid}_close" onclick="w2t_callback('${myid}_close')">Off</button>
			: </form>
		</>);

		return this;
	}
}

push W2t.styles, <:>
	: .calculator {
	:	background: #aaf;
	:	width: 20%;
	:	height: 20%;
	:	border: groove;
	:	margin: 2%;
	:	padding: 2%;
	:	float: left;
	: }
	: .calculator input {
	:	width: 80%;
	:	margin: 10%;
	: }
	: .calculator button {
	:	width: 20%;
	:	margin: 1%;
	: }
</>;


// --------------------------- Startup Page ---------------------------

page.register_callback("newcalc", function() { new Calculator(page); });

page.startup = <:>
	: <?xml version="1.0" ?>
	: <html xmlns="${page.xmlns.xhtml}" ${page.getxmlnsdecls()}>
	: <head>
	:	<title>Simple w2t demo</title>
	:	<script><![CDATA[
	:		${page.getscripts()}
	:	]]></script>
	:	<style type="text/css"><![CDATA[
	:		${page.getstyles()}
	:	]]></style>
	: </head>
	: <body>
	:	<a href="javascript:w2t_console_open()">Open W2T Console</a><br/>
	:	<a w2t:callbacks="newcalc" href="javascript:w2t_callback('newcalc')">Create new calculator</a>
	:	<div id="calcs"/>
	: </body>
	: </html>
</>;

page.run();

