Thành viên:Cumeo89/vector.js

Từ điển mở Wiktionary

Chú ý: Sau khi lưu trang này, phải xóa bộ nhớ đệm (cache) của trình duyệt để những thay đổi hiện ra

  • Firefox / Safari: Nhấn giữ phím Shift trong khi nhấn Tải lại (Reload), hoặc nhấn tổ hợp Ctrl-F5 hay Ctrl-R (⌘R trên Mac)
  • Google Chrome: Nhấn tổ hợp Ctrl-Shift-R (⇧⌘R trên Mac)
  • Internet Explorer / Edge: Nhấn giữ phím Ctrl trong khi nhấn Làm tươi (Refresh), hoặc nhấn tổ hợp Ctrl-F5
  • Opera: Nhấn tổ hợp Ctrl-F5.
function wiktauto_init() {
    var data = {
        values: [
            // languages        
            "Brai", "Cham", "Hani", "Hans",
 
			"Hang", "Hant", "Hira", "Grek", "Cyrl", "Latn", "Jpan", "vie-n",
 
			"Runr", "Xsux", "Teng", "Thai", "epo", "afr", "sqi", "amu", "eng",
 
			"ang", "ara", "pol", "isl", "eus", "fas", "bos", "ina", "por",
 
			"cat", "gan", "hrv", "heb", "dan", "dng", "deu", "est", "fao",
 
			"fry", "glg", "grn", "nld", "haw", "hin", "hun", "czh", "ell",
 
			"ido", "ind", "gle", "hak", "kur", "lat", "jbo", "msa", "mlt",
 
			"mnp", "nan", "czo", "cdo", "mar", "nap", "nor", "nob", "nno",
 
			"nep", "rus", "wuu", "jpn", "oci", "fin", "fra", "cpx", "yue",
 
			"cmn", "qya", "ron", "ces", "sna", "slk", "sux", "swa", "cjy",
 
			"tat", "spa", "tha", "tur", "swe", "tpi", "kor", "zho", "hsn",
 
			"tpn", "vie", "ita", "lit",
			// parts of speech
			"cmavo", "noun", "pr-noun",
 
			"coll-noun", "pronoun", "dem-pronoun", "per-pronoun",
 
			"ref-pronoun", "rel-pronoun", "place", "part-adj", "verb",
 
			"imp-verb", "ref-verb", "coverb", "prep", "suffix", "copula",
 
			"conj", "co-conj", "sub-conj", "article", "indef-article",
 
			"part-article", "def-article", "tr-verb", "intr-verb", "adv",
 
			"circumfix", "num", "interj", "prefix", "adj", "indef-adj",
 
			"dem-adj", "pr-adj", "pos-adj", "part", "aux-verb", "infix", "dem",
 
			"clitic", "enclitic", "mesoclitic", "proclitic", "det", "interrog",
 
			"contr", "abbr", "abr", "adpos", "circumpos", "postpos",
			// others
			"nôm", "homo", "paro", "hanviet", "syn", "redup", "compound", 
                        "drv", "ant", "rel", "trans", "pron"],
        suggestions : [
            // languages
            "Chữ Braille", "Chữ Chăm",
 
			"Chữ Hán", "Chữ Hán giản thể", "Chữ Hangul", "Chữ Hán phồn thể",
 
			"Chữ Hiragana", "Chữ Hy Lạp", "Chữ Kirin", "Chữ Latinh",
 
			"Chữ Nhật hỗn hợp", "Chữ Nôm", "Chữ Rune", "Chữ Sumer",
 
			"Chữ Tengwar", "Chữ Thái", "Quốc tế ngữ", "Tiếng Afrikaans",
 
			"Tiếng Albani", "Tiếng Amuzgo", "Tiếng Anh", "Tiếng Anh cổ",
 
			"Tiếng Ả Rập", "Tiếng Ba Lan", "Tiếng Băng Đảo", "Tiếng Basque",
 
			"Tiếng Ba Tư", "Tiếng Bosnia", "Tiếng Bổ trợ Quốc tế",
 
			"Tiếng Bồ Đào Nha", "Tiếng Catalan", "Tiếng Cống", "Tiếng Croat",
 
			"Tiếng Do Thái", "Tiếng Đan Mạch", "Tiếng Đông Can", "Tiếng Đức",
 
			"Tiếng Estonia", "Tiếng Faroe", "Tiếng Frysk", "Tiếng Galicia",
 
			"Tiếng Guaraní", "Tiếng Hà Lan", "Tiếng Hawaii", "Tiếng Hindi",
 
			"Tiếng Hung", "Tiếng Huy", "Tiếng Hy Lạp", "Tiếng Ido",
 
			"Tiếng Indonesia", "Tiếng Ireland", "Tiếng Khách Gia",
 
			"Tiếng Kurd", "Tiếng Latinh", "Tiếng Lojban", "Tiếng Mã Lai",
 
			"Tiếng Malta", "Tiếng Mân Bắc", "Tiếng Mân Nam", "Tiếng Mân Trung",
 
			"Tiếng Mân Đông", "Tiếng Marathi", "Tiếng Napoli", "Tiếng Na Uy",
 
			"Tiếng Na Uy (Bokmål)", "Tiếng Na Uy (Nynorsk)", "Tiếng Nepal",
 
			"Tiếng Nga", "Tiếng Ngô", "Tiếng Nhật", "Tiếng Oc",
 
			"Tiếng Phần Lan", "Tiếng Pháp", "Tiếng Phổ Hiền",
 
			"Tiếng Quảng Đông", "Tiếng Quan Thoại", "Tiếng Quenya",
 
			"Tiếng Rumani", "Tiếng Séc", "Tiếng Shona", "Tiếng Slovak",
 
			"Tiếng Sumer", "Tiếng Swahili", "Tiếng Tấn", "Tiếng Tatar",
 
			"Tiếng Tây Ban Nha", "Tiếng Thái", "Tiếng Thổ Nhĩ Kỳ",
 
			"Tiếng Thụy Điển", "Tiếng Tok Pisin", "Tiếng Triều Tiên",
 
			"Tiếng Trung Quốc", "Tiếng Tương", "Tiếng Tupi", "Tiếng Việt",
 
			"Tiếng Ý", "Tiếng Litva",
			// parts of speech
			"cmavo", "Danh từ", "Danh từ riêng",
 
			"Danh từ tập họp", "Đại từ", "Đại từ chỉ định", "Đại từ nhân xưng",
 
			"Đại từ phản thân", "Đại từ quan hệ", "Địa danh", "Động tính từ",
 
			"Động từ", "Động từ không ngôi", "Động từ phản thân",
 
			"Đồng động từ", "Giới từ", "Hậu tố", "Hệ từ", "Liên từ",
 
			"Liên từ kết hợp", "Liên từ phụ thuộc", "Mạo từ",
 
			"Mạo từ bất định", "Mạo từ bộ phận", "Mạo từ hạn định",
 
			"Ngoại động từ", "Nội động từ", "Phó từ", "Phụ tố chu vi", "Số từ",
 
			"Thán từ", "Tiền tố", "Tính từ", "Tính từ bất định",
 
			"Tính từ chỉ định", "Tính từ riêng", "Tính từ sở hữu", "Trợ từ",
 
			"Trợ động từ", "Trung tố", "Từ chỉ định", "Từ ghép", "Từ ghép sau",
 
			"Từ ghép trung", "Từ ghép trước", "Từ hạn định", "Từ nghi vấn",
 
			"Từ rút gọn", "Từ viết tắt", "Từ viết tắt", "Yếu tố",
 
			"Yếu tố quanh", "Yếu tố sau",
			// others
			"Chữ Nôm", "Từ đồng âm", "Từ viết tương tự", "Phiên thiết Hán-Việt", 
                        "Đồng nghĩa", "Từ láy", "Từ ghép", "Từ dẫn xuất", "Trái nghĩa", 
                        "Từ liên hệ", "Dịch", "Phát âm"]
    };
    for (i in data.values) {
        data.suggestions[i] = data.values[i] + ' - ' + data.suggestions[i];
        data.values[i] = '{{-' + data.values[i] + '-}}';
    }
 
    var textbox = document.getElementById('wpTextbox1');
    var inputBox = document.createElement('input');
    inputBox.type = 'text';
    var pos = wiktauto_findPos(textbox);
    inputBox.style.position = "absolute";
    inputBox.style.left = pos.left + "px";
    inputBox.style.top = pos.top + "px";
    inputBox.style.zIndex = 2;
    inputBox.style.display = 'none';
    document.body.appendChild(inputBox);
 
    var autoSuggestDiv = document.createElement('div');
    autoSuggestDiv.id = 'wiktauto-autosuggest';
    autoSuggestDiv.appendChild(document.createElement('ul'));
    document.body.appendChild(autoSuggestDiv);
    autoSuggest = new AutoSuggest(inputBox, data);
 
    autoSuggest.suggestionUsed = function() {
    	if ( document.selection  && document.selection.createRange ) { // IE/Opera
		    // save window scroll position
		    if ( document.documentElement && document.documentElement.scrollTop ) {
			    var winScroll = document.documentElement.scrollTop
		    } else if ( document.body ) {
			    var winScroll = document.body.scrollTop;
		    }
		    // insert suggestion
		    var range = document.selection.createRange();
		    range.text = inputBox.value;
		    // restore window scroll position
		    if ( document.documentElement && document.documentElement.scrollTop ) {
			    document.documentElement.scrollTop = winScroll;
		    } else if ( document.body ) {
			    document.body.scrollTop = winScroll;
		    }
            range.select();
	    } else if ( textbox.selectionStart || textbox.selectionStart == '0' ) { // Mozilla
		    // save textarea scroll position
		    var textScroll = textbox.scrollTop;
		    // insert suggestion
		    var startPos = textbox.selectionStart;
		    var endPos = textbox.selectionEnd;
		    textbox.value = textbox.value.substring(0, startPos)
			    + inputBox.value
			    + textbox.value.substring(endPos, textbox.value.length);
		    // restore textarea scroll position
		    textbox.scrollTop = textScroll;
		    textbox.selectionStart = startPos + inputBox.value.length;
            textbox.selectionEnd = textbox.selectionStart; 
	    }
        inputBox.style.display = 'none';
        autoSuggest.hideDiv();
        textbox.focus();
    };
    wiktauto_addKeydownHandler(inputBox, function(ev) {
        var key = wiktauto_getKeyCode(ev), ESC = 27;
        if (key == ESC) {
            inputBox.style.display = 'none';
            autoSuggest.hideDiv();
            textbox.focus();
        }
    });
    textbox.onkeydown = function(ev) {
        var key = wiktauto_getKeyCode(ev), SPACE = 32;
        if (key == SPACE && ev.ctrlKey) {
            selText = '';
            if ( document.selection  && document.selection.createRange ) { // IE/Opera
		        // get current selection
		        var range = document.selection.createRange();
		        selText = range.text;
	        } else if ( textbox.selectionStart || textbox.selectionStart == '0' ) { // Mozilla
		        // get current selection
		        var startPos = textbox.selectionStart;
		        var endPos = textbox.selectionEnd;
		        selText = textbox.value.substring( startPos, endPos );
	        }
	        selText = selText.replace(/^[ {-]*((?:\w+\s*)+)[ -}]*$/, '$1');
            inputBox.value = selText;
 
            inputBox.style.display = 'block';
            inputBox.select();
            inputBox.focus();
        }
    }
    textbox.onfocus = function(ev) {
        inputBox.style.display = 'none';
        autoSuggest.hideDiv();
    }
}
 
function wiktauto_findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
    	do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
    }
	return { "left": curleft, "top": curtop };
}
 
 
function AutoSuggest(elem, data)
{
 
	//The 'me' variable allow you to access the AutoSuggest object
	//from the elem's event handlers defined below.
	var me = this;
 
	//A reference to the element we're binding the list to.
	this.elem = elem;
 
    this.values = data.values;
	this.suggestions = data.suggestions;
 
	//Arrow to store a subset of eligible suggestions that match the user's input
	this.eligible = new Array();
 
	//The text input by the user.
	this.inputText = null;
 
	//A pointer to the index of the highlighted eligible item. -1 means nothing highlighted.
	this.highlighted = -1;
 
	//A div to use to create the dropdown.
	this.div = document.getElementById("wiktauto-autosuggest");
 
 
	//Do you want to remember what keycode means what? Me neither.
	var TAB = 9;
	var ENTER = 13;
	var ESC = 27;
	var KEYUP = 38;
	var KEYDN = 40;
 
 
	//The browsers' own autocomplete feature can be problematic, since it will 
	//be making suggestions from the users' past input.
	//Setting this attribute should turn it off.
	elem.setAttribute("autocomplete","off");
 
	//We need to be able to reference the elem by id. If it doesn't have an id, set one.
	if(!elem.id)
	{
		var id = "wiktauto-autosuggest" + idCounter;
		idCounter++;
 
		elem.id = id;
	}
 
 
	/********************************************************
	onkeydown event handler for the input elem.
	Tab key = use the highlighted suggestion, if there is one.
	Esc key = get rid of the autosuggest dropdown
	Up/down arrows = Move the highlight up and down in the suggestions.
	********************************************************/
	wiktauto_addKeydownHandler(elem, function(ev)
	{
		var key = wiktauto_getKeyCode(ev);
 
		switch(key)
		{
			case TAB:
			case ENTER:
			me.useSuggestion();
			break;
 
			case ESC:
			me.hideDiv();
			break;
 
			case KEYUP:
			if (me.highlighted > 0)
			{
				me.highlighted--;
			}
			me.changeHighlight(key);
			break;
 
			case KEYDN:
			if (me.highlighted < (me.eligible.length - 1))
			{
				me.highlighted++;
			}
			me.changeHighlight(key);
			break;
		}
	});
 
	/********************************************************
	onkeyup handler for the elem
	If the text is of sufficient length, and has been changed, 
	then display a list of eligible suggestions.
	********************************************************/
	elem.onkeyup = function(ev) 
	{
		var key = wiktauto_getKeyCode(ev);
		switch(key)
		{
		//The control keys were already handled by onkeydown, so do nothing.
		case TAB:
		case ENTER:
		case ESC:
		case KEYUP:
		case KEYDN:
			return;
		default:
 
			if (this.value != me.inputText && this.value.length > 0)
			{
				me.inputText = this.value;
				me.getEligible();
				me.createDiv();
				me.positionDiv();
			}
			me.showDiv();
			//else
			//{
			//	me.hideDiv();
			//}
		}
	};
 
 
	/********************************************************
	Insert the highlighted suggestion into the input box, and 
	remove the suggestion dropdown.
	********************************************************/
	this.useSuggestion = function()
	{
		if (this.highlighted > -1)
		{
			this.elem.value = this.eligible[this.highlighted].value;
			this.hideDiv();
			//It's impossible to cancel the Tab key's default behavior. 
			//So this undoes it by moving the focus back to our field right after
			//the event completes.
			setTimeout("document.getElementById('" + this.elem.id + "').focus()",0);
			if (this.suggestionUsed) {
			    this.suggestionUsed();
			}
		}
	};
 
	/********************************************************
	Display the dropdown. Pretty straightforward.
	********************************************************/
	this.showDiv = function()
	{
	    if (this.div.style.display != 'block') {
		    this.div.style.display = 'block';
		    // auto select the first one
		    me.highlighted = 0;
		    me.changeHighlight();
		}
	};
 
	/********************************************************
	Hide the dropdown and clear any highlight.
	********************************************************/
	this.hideDiv = function()
	{
		this.div.style.display = 'none';
		this.highlighted = -1;
	};
 
	/********************************************************
	Modify the HTML in the dropdown to move the highlight.
	********************************************************/
	this.changeHighlight = function()
	{
		var lis = this.div.getElementsByTagName('LI');
		for (i in lis)
		{
			var li = lis[i];
 
			if (this.highlighted == i)
			{
				li.className = "selected";
			}
			else
			{
				li.className = "";
			}
		}
	};
 
	/********************************************************
	Position the dropdown div below the input text field.
	********************************************************/
	this.positionDiv = function()
	{
		var el = this.elem;
		var x = 0;
		var y = el.offsetHeight;
 
		//Walk up the DOM and add up all of the offset positions.
		while (el.offsetParent && el.tagName.toUpperCase() != 'BODY')
		{
			x += el.offsetLeft;
			y += el.offsetTop;
			el = el.offsetParent;
		}
 
		x += el.offsetLeft;
		y += el.offsetTop;
 
		this.div.style.left = x + 'px';
		this.div.style.top = y + 'px';
	};
 
	/********************************************************
	Build the HTML for the dropdown div
	********************************************************/
	this.createDiv = function()
	{
		var ul = document.createElement('ul');
 
		//Create an array of LI's for the words.
		for (i in this.eligible)
		{
			var word = this.eligible[i];
 
			var li = document.createElement('li');
			var a = document.createElement('a');
			a.href="javascript:false";
			a.innerHTML = word.suggestion;
			li.appendChild(a);
 
			if (me.highlighted == i)
			{
				li.className = "selected";
			}
 
			ul.appendChild(li);
		}
 
		this.div.replaceChild(ul,this.div.childNodes[0]);
 
 
		/********************************************************
		mouseover handler for the dropdown ul
		move the highlighted suggestion with the mouse
		********************************************************/
		ul.onmouseover = function(ev)
		{
			//Walk up from target until you find the LI.
			var target = me.getEventSource(ev);
			while (target.parentNode && target.tagName.toUpperCase() != 'LI')
			{
				target = target.parentNode;
			}
 
			var lis = me.div.getElementsByTagName('LI');
 
 
			for (i in lis)
			{
				var li = lis[i];
				if(li == target)
				{
					me.highlighted = i;
					break;
				}
			}
			me.changeHighlight();
		};
 
		/********************************************************
		click handler for the dropdown ul
		insert the clicked suggestion into the input
		********************************************************/
		ul.onclick = function(ev)
		{
			me.useSuggestion();
			me.hideDiv();
			me.cancelEvent(ev);
			return false;
		};
 
		this.div.className="wiktauto-suggestion_list";
		this.div.style.position = 'absolute';
 
	};
 
	/********************************************************
	determine which of the suggestions matches the input
	********************************************************/
	this.getEligible = function()
	{
	    var parts = this.inputText.split(' ');
	    for (i in parts) {
	        parts[i] = parts[i].trim().toLowerCase();
	    }
 
		this.eligible = new Array();
		for (i in this.suggestions) 
		{
			var suggestion = this.suggestions[i];
			var temp = suggestion.toLowerCase();
			// diem cho suggestion, cang nho cang duoc uu tien
			// - tu tim thay cang dan dau suggestion thi cang duoc uu tien
			// - cac tu cang gan nhau cang duoc uu tien
			// - khop ca? tu thi duoc uu tien hon khop 1 phan
			var score = 0;
		    indices = new Array();
		    lengths = new Array();
 
			var found = true;
			for (j in parts) {
			    if ((index = temp.indexOf(parts[j])) >= 0) {
	    		    // tinh diem
	    		    score += index;
                    for (k in indices) {
                        score += (indices[k] - index);
                    }
                    for (k = index-1; k >= 0 && temp.charAt(k) != ' '; k--) {
                        score += 5;
                    }
                    for (k = index+parts[j].length; k < temp.length 
                            && temp.charAt(k) != ' '; k++) {
                        score += 5;
                    }
                    // thay bang ki tu dac biet de tranh danh dau 2 lan
                    indices[indices.length] = index;
                    lengths[lengths.length] = parts[j].length;
			        temp = temp.substr(0, index) 
			                + wiktauto_times('\u0001', parts[j].length)
	    		            + temp.substr(index + parts[j].length);
			    } else {
			        found = false;
			        break;
			    }
			}
 
			if (found) {
			    // thay placeholders bang noi dung
			    for (i2 = 0; i2 < indices.length-1; i2++) {
			        for (j2 = indices.length-1; j2 > i2; j2--) {
			            if (indices[j2-1] < indices[j2]) {
			                var t = indices[j2];
			                indices[j2] = indices[j2-1];
			                indices[j2-1] = t;
			            }
			        }
			    }
			    for (j in indices) { + "px"
			        suggestion = suggestion.substr(0, indices[j]) 
			                + '<strong>' + suggestion.substr(indices[j], lengths[j])  + '</strong>'
	    		            + suggestion.substr(indices[j] + lengths[j]);
			    }
			    // ghi nhan ket qua
			    this.eligible[this.eligible.length]= {
			        "suggestion": suggestion,
			        "value": this.values[i],
			        "score": score
			    };
			}
		}
 
		// sap xep: diem nho dung truoc
		for (i = 0; i < this.eligible.length-1; i++) {
		    for (j = this.eligible.length-1; j > i; j--) {
		        if (this.eligible[j-1].score > this.eligible[j].score) {
		            var t = this.eligible[j];
		            this.eligible[j] = this.eligible[j-1];
		            this.eligible[j-1] = t;
		        }
		    }
		}
                this.eligible = this.eligible.slice(0, 14);
	};
 
	/********************************************************
	Helper function to determine the event source element in a 
	browser-independent manner.
	********************************************************/
	this.getEventSource = function(ev)
	{
		if(ev)			//Moz
		{
			return ev.target;
		}
 
		if(window.event)	//IE
		{
			return window.event.srcElement;
		}
	};
 
	/********************************************************
	Helper function to cancel an event in a 
	browser-independent manner.
	(Returning false helps too).
	********************************************************/
	this.cancelEvent = function(ev)
	{
		if(ev)			//Moz
		{
			ev.preventDefault();
			ev.stopPropagation();
		}
		if(window.event)	//IE
		{
			window.event.returnValue = false;
		}
	}
}
 
 
/********************************************************
Helper function to determine the keycode pressed in a 
browser-independent manner.
********************************************************/
function wiktauto_getKeyCode(ev)
{
	if(ev)			//Moz
	{
		return ev.keyCode;
	}
	if(window.event)	//IE
	{
		return window.event.keyCode;
	}
};
 
function wiktauto_times(p, n) {
    var s = '';
    for ( ; n > 0; n--) {
        s += p;
    }
    return s;
}
 
function wiktauto_addKeydownHandler(elem, keydownHandler) {
    if (elem.onkeydown) {
	    var originHandler = elem.onkeydown;
	    elem.onkeydown = function(ev) {
	        originHandler(ev);
	        keydownHandler(ev);
	    }
	} else {
    	elem.onkeydown = keydownHandler;
	}
}
 
 
//counter to help create unique ID's
var idCounter = 0;
addLoadEvent(wiktauto_init);