// puhuri.js
var puhuri = (function($) {
	var cfg = {
		mode: 'auto',
		pageid: '1',
		pageversion: '',
		parentelement: 'div',
		autocontainer: '.puhuri-auto:eq(0)',
		autoseparator: 'h1,h2,h3',
		autoskip: '',
		soundbase: '/',
		title: 'Kuuntele',
		swf: 'puhuri.swf',
		highlight: false,
		highlightclass: 'puhuri-highlight',
		highlighttype: 'block' // block, sentence, word
	};

	var highlightdata = Array();
	var highlightTo;
	var highlightTime = 0;
	var speak = "";
	var snds = Array();
	var dataSent = false;

	function initialize() {
		if (!arguments.length) {
			if ($(cfg.autocontainer).length || cfg.mode == 'auto') {
				automaticMode();
			}
		}
		
		//$(window).bind('puhuri.loaded', playerEmbedded);
		
		var $$ = $('a.puhuri').hide();
		if ($$.length) {
			if(!soundManager) {
				$.ajax({ type: "GET", url: "/js/soundmanager2-nodebug-jsmin.js", success: puhuri.init, dataType: "script", cache: true }); 
			} else {
				soundManager.waitForWindowLoad = true; 
				soundManager.url = 'http://papunet.net/js/swf/soundmanager2.swf';
				soundManager.flashVersion = 9;
				soundManager.wmode=null;
				$$.each(addPlayer);
				$(window).trigger('puhuri.ready');
			}
		}

		if (cfg.highlight && window.__word == undefined) {
			//console.log(window.__word);
			window.__word = follow;
		}
	}

	function updateSettings(o) {
		$.extend(cfg, o);
		if (cfg.soundbase.charAt(0) != '/') cfg.soundbase = '/'+cfg.soundbase;
	}

	function automaticMode() {
		if (cfg.pageid != '') {
			cfg.mode = 'auto';
			if (cfg.autoseparator != '') {
				$(cfg.autocontainer).find(cfg.autoseparator).each(function(i) {
    					var $s = $(this),
    						$a = $('<a class="puhuri auto created">'+cfg.title+'</a>');
    					$a.attr('rel', cfg.pageversion);
    					// asetetaan äänilinkin titleksi erottimen teksti (= oletuksena otsikko)
    					$a.attr('title', $s.text());
    					$a.attr('href', 'http://puhuri.papunet.net/kuuntele'+cfg.soundbase+'/'+cfg.pageid+'-'+i+'.mp3');
    					$s.before($a);
				});
			} else {
				$(cfg.autocontainer).each(function(i) {
					var $a = $('<a class="puhuri auto created">'+cfg.title+'</a>');
					$a.attr('rel', cfg.pageversion);
					$a.attr('href', 'http://puhuri.papunet.net/kuuntele'+cfg.soundbase+'/'+cfg.pageid+'-'+i+'.mp3');
					$(this).prepend($a);
				});
			}
		}
	}

	function addPlayer(i) {
		if (!this.id) this.id = 'puhuri'+i;
		/*var tempId = this.id;
		var tempSound = soundManager.createSound({
		  id: tempId,
		  url:$(this).attr('href'),
		  autoLoad: true,
		  autoPlay: false,
		  volume:100,
		  onid3: getHighlightPos,
		  onload: soundLoad
		});
		snds.push(tempSound);*/
		$(this).addClass('puhuri-button').css('display','block').css('background-image','url(/mod/puhuri/grafi/kuuntele_ei_kehys.png)');
		$(this).click(function(e) {
			e.preventDefault();
			playSound(this.id);
		});
	}

	function soundLoad(success) {
		if((!success || bytesTotal < 300) && dataSent != this.sID) {
			$.post(this.url,{ speak: getContent(this.sID)});
			soundManager.destroySound(this.sID);
			setTimeout(playSound,2000,this.sID,true);
			dataSent = this.sID;
		}
		else if(dataSent == this.sID && bytesTotal < 300) {
			setTimeout(playSound,2000,this.sID,true);
		}
	}

	function getHighlightPos(elem) {
		highlightdata = Array();
		highlightTo = null;
		highlightTime = 0;
		if(elem == undefined) elem = this;
		var data = "";
		for (prop in elem.id3) {
			if(prop == 'COMM') {
				data += ""+elem.id3[prop];
			}
		}
		if(data.length > 1) {
			var wordSep = data.charAt(0);
			var lengthSep = data.charAt(1);
			data = data.substr(2);
			var words = data.split(wordSep);
			var alertdata = "times: ";
			for(var i=0;i<words.length;i++) {
				var tempTime = parseInt(words[i].substr(0, words[i].indexOf(lengthSep)));
				var tempWords = words[i].substr(words[i].indexOf(lengthSep)+1);
				highlightdata.push({time:tempTime,words:tempWords});
				alertdata += highlightdata[highlightdata.length-1].time+", ";
				setTimeout(follow,tempTime,clean(tempWords),elem.sID);
			}
			setTimeout(follow,tempTime+1000,'');
		}
	}

	function playSound(id,force) {
		var sound = soundManager.getSoundById(id);
		if(!force && sound && sound.playState == 1 && !sound.isBuffering) {
			getHighlightPos(sound);
			soundManager.stopAll();
			highlightTo = clearTimeout(highlightTo);
		}
		else {
			$("#"+id).css('background-image', 'url(/mod/puhuri/grafi/throbber-32.gif)');
			if(sound) {
				if(sound.playState != 1) {
					getHighlightPos(sound);
					soundManager.stopAll();
					sound.setPosition(0);			
					soundManager.play(id);//,{volume:100,onplay: changePlayIcon, onfinish: changeStopIcon,onstop: changeStopIcon});
				}
			}
			else {
				soundManager.stopAll();
				soundManager.play(id,{url:$("#"+id).attr('href'), whileplaying: changePlayIcon, onload: soundLoad,onfinish: changeStopIcon,onstop: changeStopIcon,volume:100,onid3: getHighlightPos});
			}
		}
	}

	function changePlayIcon() {
		$("#"+this.sID).css('background-image', 'url(/mod/puhuri/grafi/kuuntele_ei_kehys2.gif)');
	}

	function changeStopIcon() {
		$("#"+this.sID).css('background-image', 'url(/mod/puhuri/grafi/kuuntele_ei_kehys.png)');
		endFollow();
	}
	
	var cleanupRE	= /[^a-zA-Z0-9äöåÄÖÅ+=()\-\.\,\:\?\!\s]/g;
	var dashRE = /[\u2013\u2014\u2212]/g;
	function clean(t) {
		return (t ? t.replace(dashRE, '-').replace(cleanupRE, '') : '');
	}

	function getContent() {
		var $a = (arguments.length ? (arguments[0].jquery == undefined ? $('#'+arguments[0]) : arguments[0]) : $('a.puhuri')),
				next = null,
				content = '';
		if (cfg.mode == 'auto' && $a.hasClass('created')) {
			next = $a.next(cfg.autoseparator);
		} else {
			next = (arguments.length ? $a.parents(cfg.parentelement) : $('#main')).children(':not(.puhuri)').eq(0);
		}
		
		while (next.length && !next.is('.puhuri')) {
			if (next.is('ul'))
				next.children().each(function() { content += $(this).text() + '\n\n'; });
			else if (next.is('ol'))
				next.children().each(function(i) { content += (i + 1) + '. ' + $(this).text() + '\n\n'; });
			else			
				content += next.text() + "\n\n";
			next = next.next();
			if (cfg.autoskip != '')
				if (next.is(cfg.autoskip))
					next = next.next();
		}
		return clean(content);
	}
	
	var follow_el = null,
			follow_lastidx = 0,
			follow_re = null,
			follow_hlSource = '';
	
	
	function follow(word) {
		var re = null,
				hlSource = null;

		word = clean(word);
		//console.log(word);
		
		// "tyhjä" sana, lopetetaan seuraaminen
		if (word == '') {
			follow_el = null;
			follow_lastidx = 0;
			setTimeout(endFollow, 1000);
			return;
		}
		
		// tunnistamaton merkki
		if (word == '?')
			return;
		
		if (follow_el == null && arguments.length > 1) {
			follow_el = $('#'+arguments[1]).next();
			follow_hlSource = (cfg.highlighttype == 'word' ? '$1<span class="'+cfg.highlightclass+'">$2</span>$3' : '<span class="'+cfg.highlightclass+'">$1</span>');
			follow_re = (cfg.highlighttype == 'sentence' ? /^([^\.\!\?]+[\.\!\?]? ?)/i : /^([\s]?)([^\s]+)([\s]?)/i);
		}
		
		var txt = clean(follow_el.text());
		if (txt.indexOf(word, follow_lastidx) >= follow_lastidx) {
			follow_lastidx = txt.indexOf(word, follow_lastidx) + word.length;
			if (cfg.highlighttype == 'block') {
				// maalataan koko blokki
				follow_el.addClass(cfg.highlightclass); 
			} else {
				// etsitään blokista maalattu lause / sana
				var $s = follow_el.find('span.'+cfg.highlightclass),
						el = null,
						trynext = null, pel = null,
						eltxt = '';
						
				if ($s.length) {
					// edellinen lause/sana löytyi
					if (clean($s.text()).indexOf(word) < 0) {
						// maalataan seuraava lause
						if ($s[0].nextSibling && $s[0].nextSibling.nodeType == 3 && !$s[0].nextSibling.nodeValue.match(/^[\s]*$/)) {
							var restOfText = $s[0].nextSibling.nodeValue;
							$s[0].parentNode.removeChild($s[0].nextSibling);
							$s.after(restOfText.replace(follow_re, follow_hlSource)).each(function() { $(this.childNodes).insertBefore(this);	}).remove();
						} else {
							// ei ollutkaan enää lauseita
							/*
							pel = $s.parent();
							while (pel != follow_el && !pel.next().length)
								pel = pel.parent();
							if (pel != follow_el) trynext = pel.next();
							console.log(trynext);
							*/
							$s.each(function() { $(this.childNodes).insertBefore(this);	}).remove();
							$s = null;
						}
					}
				}
				if ($s == null || !$s.length) {
					// maalattua lausetta ei ole, etsitään ensimmäinen tekstielementti, joka sisältää haetun sanan
					el = (trynext != null ? trynext[0] : follow_el[0].childNodes[0]);
					eltxt = clean(el.nodeValue);
					while (el != null && (el.nodeType != 3 || eltxt.match(/^[\s]*$/) || eltxt.indexOf(word) < 0)) {
						if (clean($(el).text()).indexOf(word) >= 0) {
							// jos löydettiin elementti, joka sisältää sanan, etsitään sen lapsista
							el = el.childNodes[0];
						} else {
							// muuten siirrytään seuraavaan elementtiin
							el = el.nextSibling;
						}
						if(el) eltxt = clean(el.nodeValue);
					}
					if(el) {
						var hld = el.nodeValue.replace(follow_re, follow_hlSource);
						$(el.parentNode).html($(el.parentNode).html().replace(el.nodeValue, hld));
					}
				}
			}
		} else {
			endFollow();
			follow_el = follow_el.next();
			follow_lastidx = 0;
			if (follow_el.length) follow(word);
		}
			
	}
	
	function endFollow() {
		//$('span.'+cfg.highlightclass).replaceWith($('span.'+cfg.highlightclass).text());
		$('span.'+cfg.highlightclass).each(function() {
				$(this.childNodes).insertBefore(this);
			}).remove();
		
		$('.'+cfg.highlightclass).removeClass(cfg.highlightclass);
	}
	
	
	this.init = initialize;
	this.settings = updateSettings;
	this.content = getContent;
	//this.stopSounds = stopAllOtherSounds;
	return this;
})(jQuery);

jQuery(function($) {
	puhuri.init();
});

