var sourceObj = null;
var typeWindow = null;
var message = '';
var typedPortion = '';
var cursorChar = '';
var cursorHTML = '<span class="cursorChar">@</span>';
var workHTML = '';

function initTypewriter(sourceId, newSpeed, typeWriterDelay){
	sourceObj = document.getElementById(sourceId);
	typeWindow = document.getElementById('typeWindow');
	typeWindow.innerHTML = '';
	message = sourceObj.innerHTML;
	msgLength = message.length;
	HTMLstr = '';
	workChar = '';
	count = 0;
	speed = newSpeed;
	typing = setInterval('typeText('+typeWriterDelay+','+speed+');', speed);
}

function typeText(typeWriterDelay,typeWriterSpeed){
	if (count == msgLength+1){//Siste tegn manglet så jeg la til +1
		clearInterval(typing);
		// Sjekker om functionen typeWriterNext() er satt, kjører den hvis den er satt.
		if(typeof window.typeWriterNext=='function'){
			typeWriterNext(typeWriterDelay,typeWriterSpeed);
		}
		return;
	}else if (count == 0){
		typedPortion = '';
	}else{
		typedPortion = message.substring(0, count)
		cursorChar = message.charAt(count);
	}
	if (/</.test(cursorChar)){
		var tag = message.substring(count).match(/<\/?[^>]+>/);
		if (tag){
			typedPortion += tag[0];
			count += tag[0].length;
		}
	}else{
		workHTML = '';
		workHTML += typedPortion;
		if (count != msgLength - 1)
		workHTML += cursorHTML.replace(/@/, cursorChar);
		typeWindow.innerHTML = workHTML;
		count++;
	}
}

