// insert the baseurl of the images here, with and ending slash (eg. 'http://example.com/images/')
var baseurl = '/software/ambigram/ambigen/ambipic/';

function makeAmbi() {
	
	var theView = document.getElementById('theView');
	
	while(theView.hasChildNodes()) {
		theView.removeChild(theView.firstChild);
	}
	
	var word = document.getElementById("theWord").value;
	var word1, word2;
	alert('Making ambi of the word ' + word);
	
	
	if(word.indexOf(' ') < 0) {
		
		drawWords(word, inverse(word));

	} else if(word.indexOf(' ') * 2 + 1 == word.length) {
		
		word1 = word.substring(0, word.indexOf(' '));
		word2 = word.substring(word.indexOf(' ') + 1, word.length);

		drawWords(word1, inverse(word2));
		
		document.getElementById('theView').appendChild(document.createElement('br'));
	
		drawWords(word2, inverse(word1));
	
	} else {
		return;
	}
	
}

function inverse(word) {
	ret = '';
	
	for(i = 0; i < word.length; i++) {
		ret = word.charAt(i) + ret;
	}
	
	return ret;
}

function drawWords (word1, word2) {
	for(i = 0; i < word1.length; i++) {
		
		var img = document.createElement('img');
		if(isLetter(word1.charAt(i)) && isLetter(word2.charAt(i))) {
			img.setAttribute('style', 'float: left;');
			var url = baseurl + word1.charAt(i).toLowerCase() + '' + word2.charAt(i).toLowerCase() + '.png';
			img.setAttribute('src', url);
		} else {
			alert("Please use normal letters only");
			var theView = document.getElementById('theView');

			while(theView.hasChildNodes()) {
				theView.removeChild(theView.firstChild);
			}
			break
		}
		document.getElementById('theView').appendChild(img);
	}
}

function isLetter(character) {
  return ((character >= "a" && character <= "z") || (character >= "A" && character <= "Z"))
}