var
histList = [""],
histPos = 0,
_scope = {},
_win, // a top-level context
//_arguments,
_in,
_out;

function init() {
	_in = document.getElementById("input");
	_out = document.getElementById("output");
	//_win = window;
	
	initTarget();
	
	resetInputHeight();
	refocus();
}

function refocus() {
	_in.blur();
	_in.focus();
}

function initTarget() {
	_win = window;
	_win.print = commandList.print;
}

function resetInputHeight() {
	var rows = _in.value.split(/\n/).length + 1;
	if(_in.rows != rows ) {
		_in.rows = rows;
	}
}

function focusOnInput() {
	_in.focus();
}


function printError(er) {
    var lineNumberString;
    lastError = er;
    if (er.name) {
        lineNumberString = er.lineNumber != undefined ? " on line " + er.lineNumber + ": " : ": ";
        println(er.name + lineNumberString + er.message, "error");
    } else {
        println(er, "error");
    }
}


function println(s, type) {
    if (s = String(s)) {
        var newdiv = document.createElement("div");
        newdiv.appendChild(document.createTextNode(s));
        newdiv.className = type;
        _out.appendChild(newdiv);
        //return newdiv;
    }
}


function keydownEvent(e) {
		
    if (e.shiftKey && e.keyCode == 13) {
    } else if (e.keyCode == 13) {
        try {
            go();
        } catch (er) {
            alert(er);
        }
        setTimeout(function () {_in.value = "";}, 0);

    } else if (e.keyCode == 38) {
        if (e.ctrlKey || caretInFirstLine(_in)) {
            hist(true);
        }
    } else if (e.keyCode == 40) {
        if (e.ctrlKey || caretInLastLine(_in)) {
            hist(false);
        }

    } else if (e.keyCode == 9) { // tab
			// tabcomplete();
			setTimeout(function() { refocus(); }, 0); // refocus because tab was hit
		} else { }
    setTimeout(resetInputHeight, 0);
}

function go() {

	try{
		println( _in.value, "input");
		
		runCommandline(_in.value);
		
		histList[histList.length-1] = _in.value;
		histList[histList.length] = "";
		histPos = histList.length - 1;
		
		_in.value = "";
		resetInputHeight();
		initTarget();
		
	} catch(er) { 
		//printError(er);
		printError("Error: " + er); 
	};
	
}
	
function printAnswer(ans) {
	if( ans !== undefined ) {
		println(ans, "normal output" );
		commandList.ans = ans;
	}
}

function keepFocusInTextbox(e) {
    var g = e.srcElement ? e.srcElement : e.target;
    while (!g.tagName) {
        g = g.parentNode;
    }
    var t = g.tagName.toUpperCase();
    if (t == "A" || t == "INPUT") {
        return;
    }
    if (window.getSelection) {
        if (String(window.getSelection())) {
            return;
        }
    } else if (document.getSelection) {
        if (document.getSelection()) {
            return;
        }
    } else {
        if (document.selection.createRange().text) {
            return;
        }
    }
    refocus();
}


// ------------------- history ------------------
//　キャレットが1行目にあるかどうかをチェックする
function caretInFirstLine(textbox) {
	 // IE doesn't support selectionStart/selectionEnd
	if (textbox.selectionStart == undefined)
	return true;
	
	// 改行の位置を取得する
	var firstLineBreak = textbox.value.indexOf("\n");

	// 改行がないか、または、(キャレット開始位置) < (最初の改行位置) ならば"true"
	return ((firstLineBreak == -1) || (textbox.selectionStart <= firstLineBreak));
}

// キャレットが最終行にあるかどうかをチェックする
function caretInLastLine(textbox) {
	// IE doesn't support selectionStart/selectionEnd
	if (textbox.selectionEnd == undefined)
	return true;

	var lastLineBreak = textbox.value.lastIndexOf("\n");
	
	return (textbox.selectionEnd > lastLineBreak);
}


function hist(flag) {
	
	var L = histList.length;
	
	if (L == 1) {return;}

	if (flag) {
 		if (histPos == L-1) {
 			// Save this entry in case the user hits the down key.
 			histList[histPos] = _in.value;
 		}

 		if (histPos > 0) {
 			histPos--;
 			// Use a timeout to prevent up from moving cursor within new text
 			// Set to nothing first for the same reason
 			setTimeout(
 				function() {
 					_in.value = '';
 					_in.value = histList[histPos];
 					var caretPos = _in.value.length;
 					
 					//開始位置と終了位置を同じにすることにより、テキストが選択されずにカーソル位置を指定する
 					if (_in.setSelectionRange) { _in.setSelectionRange(caretPos, caretPos); }
 				},
 				0 );
 		}
	} else {
 		if (histPos < L-1) {
 			histPos++;
 			_in.value = histList[histPos];
 		} else if (histPos == L-1) {
 			// Already on the current entry: clear but save
 			if (_in.value) {
 				histList[histPos] = _in.value;
 				++histPos;
 				_in.value = "";
 			}
 		}
	}

}
// ------------------- history ------------------
