$( function() {
	var wtids = Array();

	$( "*[wtid]" ).each( function( index ) {
		var wtid = $( this ).attr( "wtid" );
		if ( $.inArray( wtid, wtids ) == -1 ) {
			wtids.push( wtid );
		}
	} );
	
	var wtDialogDivs = "";
	$.each( wtids, function( index, value ) {
		wtDialogDivs += "<div wtfor=\"" + value + "\"></div>";
	} );

	$( "body" ).append( wtDialogDivs );
	
	$( "*[wtfor]" ).dialog( {
		autoOpen: false,
		title: "Wat is dat?",
		resizable: false,
		show: "fade",
		buttons: [ {
			text: "Sluiten",
			click: function() { $( this ).dialog( "close" ); }
		} ],
		open: function() {
			var word = $( this ).attr( "word" ); 
			if ( !word || word == 'true' ) {
				var wtfor = $( this ).attr( "wtfor" );
				retreiveWhatsThatContent( wtfor, wtfor );				
			}
		}
	} );
	
	$( "*[wtid]" ).click( function( event ) {
		$( "*[wtfor='" + $( this ).attr( "wtid" ) + "']" ).dialog( "open" );
		event.stopPropagation();
	} );
} );

function retreiveWhatsThatContent( wtfor, wordId ) {
	$.getJSON( "/json/word.php?wtfor=" + wtfor + "&wordID=" + wordId, setWhatsThatContent );
}

function setWhatsThatContent( data ) {
	var html = "<h3>" + data.word + "</h3>";
	html += "<div>" + data.description + "</div>";
	
	if ( data.alternatives ) {
		html += "<div class=\"alternatives\">Ook wel: " + data.alternatives.join( ", " ) + "</div>";
	}
	
	if ( data.links ) {
		html += "<div class=\"wordlinks\">Zie ook: ";
		
		$.each( data.links, function( index, value ) {
			html += "<span class=\"whatsthat\" wtlink=\"" + value.ID + "\">" + value.word + "</span>";
			
			if ( index < data.links.length - 1 ) {
				html += ", ";
			}
		});
		
		html += "</div>";
	}
	
	var dialogSelector = "*[wtfor='" + data.wtfor + "']";
	$( dialogSelector ).html( html );
	$( dialogSelector + " *[wtlink]" ).click( function() {		
		retreiveWhatsThatContent( data.wtfor, $( this ).attr( "wtlink" ) );
	});
}
