function $(name) {
	var o = document.getElementById(name);
	return o ? o : {};
}

function onloadCallback() {
	//console.log($('sourceNice'));
	$('wikifiedNice').innerHTML = $('source').value;
	$('startButton').disabled = false;
	var sw = getSkipWords();
	$('skipWords').innerHTML = sw.join(', ');
}

var global_words;
var global_i;
var global_terms = {};
function startWikify() {
	$('startButton').disabled = true;
	$('middle').value = ' '+$('source').value;
	$('wikified').value = $('middle').value;
	$('wikifiedNice').innerHTML = htmlentities_decode($('wikified').value);

	var words = $('middle').value.replace(new RegExp('[ !@#$%^&*()_+:";?><|\\\'\\[\\],./]', 'gi'), ' ');
	//var words = $('middle').value;
	words = words.split(new RegExp(' ', 'gi'));
	//console.log(words);
	words = array_tolower(words);
	//console.log(words);
	words = array_unique(words);
	//console.log(words);
	words = assoc2array(words); // after array_unique
	//console.log(words);
	words = filterWords(words);
	//console.log(words);
	global_words = words;
	global_i = 0;
	continueWikify();
}

function continueWikify() {
	var word = global_words[global_i];
	if (word) {
		var lang = $('language').options[$('language').selectedIndex].value;
		jx.load('index.php?ajax=1&language='+lang+'&word='+word, function(data) {
			//alert(data); // Do what you want with the 'data' variable.
			//console.log(word + ': ' + data);
			if (data) {
				// modify middle buffer
				var re = new RegExp('([ !@#$%^&*()_+:";?><|\\\'\\[\\],./])('+word+')([ !@#$%^&*()_+:";?><|\\\'\\[\\],./])', 'gi');
				$('middle').value = $('middle').value.replace(re, '$1<$2>$3');

				// add term to the list
				global_terms[word] = data;

				// update visible wikified area
				$('wikified').value = linkifyFromMiddle($('middle').value);
				$('wikifiedNice').innerHTML = htmlentities_decode($('wikified').value);
			}
			if ($('progress-bar')) {
				setPBP(Math.round(global_i/global_words.length*100));
			}
			global_i++;
			if (global_i < global_words.length) {
				setTimeout("continueWikify()", 1);
			} else {
				$('startButton').disabled = false;
				setPBP(100);
			}
		});
	} else {	// end of the processing
	}
}

function linkifyFromMiddle(middle) {
	var result = middle;
	//console.log(global_terms);
	for (var word2 in global_terms) {
		//console.log('word2: '+word2);
		var re = new RegExp('<('+word2+')>', 'gi');
		result = result.replace(re, '<a href="'+global_terms[word2]+'">$1</a>');
	}
	return result;
}

function array_unique( array ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com)
    // +      input by: duncan
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Nate
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Michael Grier
  // %          note 1: the second argument, sort_flags is not implemented
    // *     example 1: array_unique(['Kevin','Kevin','van','Zonneveld','Kevin']);
    // *     returns 1: ['Kevin','van','Zonneveld']
    // *     example 2: array_unique({'a': 'green', 0: 'red', 'b': 'green', 1: 'blue', 2: 'red'});
    // *     returns 2: {'a': 'green', 0: 'red', 1: 'blue'}

    var key = '', tmp_arr1 = {}, tmp_arr2 = [];
    var val = '';
    tmp_arr1 = array;

    var __array_search = function (needle, haystack) {
        var fkey = '';
        for (fkey in haystack) {
            if ((haystack[fkey] + '') === (needle + '')) {
                return fkey;
            }
        }
        return false;
    };

    for (key in tmp_arr1) {
        val = tmp_arr1[key];
        if (false === __array_search(val, tmp_arr2)) {
            tmp_arr2[key] = val;
        }

        delete tmp_arr1[key];
    }

    return tmp_arr2;
}

function assoc2array(o) {
	r = [];
	for (var i in o) {
		if (o[i]) { // remove empty
			r.push(o[i]);
		}
	}
	return r;
}

function array_tolower(a) {
	for (var i = 0; i < a.length; i++) {
		a[i] = a[i].toLowerCase();
	}
	return a;
}

function htmlentities_decode(string) {
	string = string.replace(/&amp;/g, '\'');
	string = string.replace(/&lt;/g, '<');
	string = string.replace(/&gt;/g, '>');
	return string;
}

function setPBP(percent, subtitle) {
	$("progress-bar").style.width = percent+"%";
	if (percent == 100) {
		$("transparent-bar").style.display = "none";
	} else {
		$("transparent-bar").style.width = (100-percent)+"%";
	}
	$(percent <  50 ? "transparent-bar" : "progress-bar").innerHTML = percent+"%";
	$(percent >= 50 ? "transparent-bar" : "progress-bar").innerHTML = "";
	if (subtitle) {
		$("subtitle").innerHTML = subtitle;
	}
}

function filterWords(words) {
	var skipList = getSkipWords();
	var words2 = [];
	for (var i = 0; i < words.length; i++) {
		var word = words[i];
		if (word) {
			var found = skipList.indexOf(word);
			if (found == -1) {
				words2.push(word);
			}
			//console.log(i, word, found, words2.length);
		}
	}
	return words2;
}

if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function (obj, fromIndex) {
    if (fromIndex == null) {
        fromIndex = 0;
    } else if (fromIndex < 0) {
        fromIndex = Math.max(0, this.length + fromIndex);
    }
    for (var i = fromIndex, j = this.length; i < j; i++) {
        if (this[i] === obj)
            return i;
    }
    return -1;
  };
}

function getSkipWords() {
	var skipList = [
'the',
'of',
'to',
'and',
'a',
'in',
'is',
'it',
'you',
'that',
'he',
'was',
'for',
'on',
'are',
'with',
'as',
'I',
'his',
'they',
'be',
'at',
'one',
'have',
'this',
'from',
'or',
'had',
'by',
'hot',
'but',
'some',
'what',
'there',
'we',
'can',
'out',
'other',
'were',
'all',
'your',
'when',
'up',
'use',
'word',
'how',
'said',
'an',
'each',
'she',
'which',
'do',
'their',
'time',
'if',
'will',
'way',
'about',
'many',
'then',
'them',
'would',
'write',
'like',
'so',
'these',
'her',
'long',
'make',
'thing',
'see',
'him',
'two',
'has',
'look',
'more',
'day',
'could',
'go',
'come',
'did',
'my',
'sound',
'no',
'most',
'number',
'who',
'over',
'know',
'water',
'than',
'call',
'first',
'people',
'may',
'down',
'side',
'been',
'now',
'find',
'any',
'new',
'work',
'part',
'take',
'get',
'place',
'made',
'live',
'where',
'after',
'back',
'little',
'only',
'round',
'man',
'year',
'came',
'show',
'every',
'good',
'me',
'give',
'our',
'under',
'name',
'very',
'through',
'just',
'form',
'much',
'great',
'think',
'say',
'help',
'low',
'line',
'before',
'turn',
'cause',
'same',
'mean',
'differ',
'move',
'right',
'boy',
'old',
'too',
'does',
'tell',
'sentence',
'set',
'three',
'want',
'air',
'well',
'also',
'play',
'small',
'end',
'put',
'home',
'read',
'hand',
'port',
'large',
'spell',
'add',
'even',
'land',
'here',
'must',
'big',
'high',
'such',
'follow',
'act',
'why',
'ask',
'men',
'change',
'went',
'light',
'kind',
'off',
'need',
'house',
'picture',
'try',
'us',
'again',
'animal',
'point',
'mother',
'world',
'near',
'build',
'self',
'earth',
'father',
'head',
'stand',
'own',
'page',
'should',
'country',
'found',
'answer',
'school',
'grow',
'study',
'still',
'learn',
'plant',
'cover',
'food',
'sun',
'four',
'thought',
'let',
'keep',
'eye',
'never',
'last',
'door',
'between',
'city',
'tree',
'cross',
'since',
'hard',
'start',
'might',
'story',
'saw',
'far',
'sea',
'draw',
'left',
'late',
'run',
'don\'t',
'while',
'press',
'close',
'night',
'real',
'life',
'few',
'stop',
'open',
'seem',
'together',
'next',
'white',
'children',
'begin',
'got',
'walk',
'example',
'ease',
'paper',
'often',
'always',
'music',
'those',
'both',
'mark',
'book',
'letter',
'until',
'mile',
'river',
'car',
'feet',
'care',
'second',
'group',
'carry',
'took',
'rain',
'eat',
'room',
'friend',
'began',
'idea',
'fish',
'mountain',
'north',
'once',
'base',
'hear',
'horse',
'cut',
'sure',
'watch',
'color',
'face',
'wood',
'main',
'enough',
'plain',
'girl',
'usual',
'young',
'ready',
'above',
'ever',
'red',
'list',
'though',
'feel',
'talk',
'bird',
'soon',
'body',
'dog',
'family',
'direct',
'pose',
'leave',
'song',
'measure',
'state',
'product',
'black',
'short',
'numeral',
'class',
'wind',
'question',
'happen',
'complete',
'ship',
'area',
'half',
'rock',
'order',
'fire',
'south',
'problem',
'piece',
'told',
'knew',
'pass',
'farm',
'top',
'whole',
'king',
'size',
'heard',
'best',
'hour',
'better',
'true .',
'during',
'hundred',
'am',
'remember',
'step',
'early',
'hold',
'west',
'ground',
'interest',
'reach',
'fast',
'five',
'sing',
'listen',
'six',
'table',
'travel',
'less',
'morning',
'ten',
'simple',
'several',
'vowel',
'toward',
'war',
'lay',
'against',
'pattern',
'slow',
'center',
'love',
'person',
'money',
'serve',
'appear',
'road',
'map',
'science',
'rule',
'govern',
'pull',
'cold',
'notice',
'voice',
'fall',
'power',
'town',
'fine',
'certain',
'fly',
'unit',
'lead',
'cry',
'dark',
'machine',
'note',
'wait',
'plan',
'figure',
'star',
'box',
'noun',
'field',
'rest',
'correct',
'able',
'pound',
'done',
'beauty',
'drive',
'stood',
'contain',
'front',
'teach',
'week',
'final',
'gave',
'green',
'oh',
'quick',
'develop',
'sleep',
'warm',
'free',
'minute',
'strong',
'special',
'mind',
'behind',
'clear',
'tail',
'produce',
'fact',
'street',
'inch',
'lot',
'nothing',
'course',
'stay',
'wheel',
'full',
'force',
'blue',
'object',
'decide',
'surface',
'deep',
'moon',
'island',
'foot',
'yet',
'busy',
'test',
'record',
'boat',
'common',
'gold',
'possible',
'plane',
'age',
'dry',
'wonder',
'laugh',
'thousand',
'ago',
'ran',
'check',
'game',
'shape',
'yes',
'hot',
'miss',
'brought',
'heat',
'snow',
'bed',
'bring',
'sit',
'perhaps',
'fill',
'east',
'weight',
'language',
'among',
'its',
'not',
];
	return skipList;
}