function dibaris(tex, pos) {
	tex = tex.slice(0, pos);
	var ret = tex.match(/\n/g);
	if (!ret) return 1;
	return ret.length + 1;
}

function hitungbaris(evt, kolbekpos) {
    var t = evt.target;

	if (kolbekpos) {
		var bdari = dibaris(t.value, t.selectionStart);
		var bke = dibaris(t.value, t.selectionEnd);
		
		kolbekpos(bdari, bke);
	}
}

function bisangetab(evt) {
	var tab = "\t";
    var t = evt.target;
    var ss = t.selectionStart;
    var se = t.selectionEnd;
 
    // Tab key - insert tab expansion
    if (evt.keyCode == 9) {
        evt.preventDefault();
               
        // Special case of multi line selection
        if (ss != se && t.value.slice(ss,se).indexOf("\n") != -1) {
            // In case selection was not of entire lines (e.g. selection begins in the middle of a line)
            // we ought to tab at the beginning as well as at the start of every following line.
            var pre = t.value.slice(0,ss);
			
			var selasli = t.value.slice(ss,se);
			if (evt.shiftKey) {
	            var sel = t.value.slice(ss,se).replace(/^(\t|    )/gm, "");
			} else {
	            var sel = t.value.slice(ss,se).replace(/^.{0}/gm, "\t");
			}
			
            var post = t.value.slice(se,t.value.length);
            t.value = pre.concat(sel).concat(post);
                   
            t.selectionStart = ss;
            t.selectionEnd = se + sel.length - selasli.length;
        }
               
        // "Normal" case (no selection or selection on one line only)
        else {
            t.value = t.value.slice(0,ss).concat(tab).concat(t.value.slice(ss,t.value.length));
            if (ss == se) {
                t.selectionStart = t.selectionEnd = ss + tab.length;
            }
            else {
                t.selectionStart = ss + tab.length;
                t.selectionEnd = se + tab.length;
            }
        }
    }
    else if (evt.keyCode == 13) {
		if (ss == se) {
			evt.preventDefault();
			
			var di = ss-1;
			var baris = '';
			while (di >= 0) {
				var bt = t.value.slice(di, di+1);
				if (bt != '\n') {
					baris = bt + baris;
				} else {
					break;
				}
				di--;
			}
			
			// cari kosongd ari depan
			var kosong = '';
			
			for (var i = 0; i < baris.length; i++) {
				var c = baris.charAt(i);
				if (c != '\t' && c != ' ') {
					break;
				} else {
					kosong += c;
				}
			}
			
			var pre = t.value.slice(0,ss);
			
			var sel = "\n" + kosong;
			
			var post = t.value.slice(se,t.value.length);
            t.value = pre.concat(sel).concat(post);
                   
            t.selectionStart = se + sel.length;
            t.selectionEnd = se + sel.length;
		}
	}
}
