var httpObjectMain;
// this is what I am mining for
var equivExpression;
var foundIt;
// The Language I'm Wondering About
var dstLan;
var word;
var srcLan;
// Found a term, retrieving a description 
var description;
// There are other languages for the input word
var langlinksExists = false;

	// on Translate! click, Ajax request to POC.php
	function translate() {
		
		// Reset and restart
		langlinksExists = false;
		foundIt = false;
		description = "";
		equivExpression = "";
		$("#answer").removeClass("error");
		$("#answer").html("");
		$("#description").hide("slow");
		$("#description").html("");
		
		// jQuery fetch of selected src language
		srcLan = $("#srcLan").val();
		dstLan = $("#dstLan").val();
		word = $("#word").val();
		word = word.toLowerCase();
		var apiString = ".wikipedia.org/w/api.php?action=query&format=json&callback=processAnswer&prop=langlinks&lllimit=500&redirects&titles=";
		
		// call to wikipedia api to retrieve language links
		var url = "http://" + srcLan + apiString + word;
	    
		// JSON :: Add script to head of document. Callback function processAnswer
    	var elem = document.createElement ('script');
    	elem.setAttribute ('src', url);
    	elem.setAttribute ('type','text/javascript');
    	document.getElementsByTagName ('head') [0].appendChild (elem);

	}
	
	// process first reply from wikipedia, and go from there.
	function processAnswer(data) {
		
		// retrieve and display the equivalent expression 
		fetchReply(data);
		// no equiv languages
		if (!langlinksExists)
		{	
			$("#answer").addClass("error");
			$("#answer").html("Wikipedia does not have an equivalent expression in " + dstLan + " for the " + srcLan + " expression " + word + ".");
		}
		
		apiString = ".wikipedia.org/w/api.php?action=query&format=json&callback=processDesc&prop=revisions&rvprop=content&rvsection=0&redirects&titles=";
		// api string to retrieve description
		url = "http://" + dstLan + apiString + equivExpression;
		
		// JSON, PT II
    	var elem = document.createElement ('script');
    	elem.setAttribute ('src', url);
    	elem.setAttribute ('type','text/javascript');
    	document.getElementsByTagName ('head') [0].appendChild (elem);
		// Callback processDesc()
    	
	}
	
	// this method allow for sync between JSON and XHR, ie, workflow is respected
	function processDesc(data) {
		
		// parse and fetch description
		getDescription(data);
		
    	// Call php
	    // this is my XMLHttpRequest object
		httpObjectMain = initXMLHttpClient();
	    httpObjectMain.onreadystatechange = stateChangedAfterAsk;

	    //alert(description.valueOf());

	    if (description.length > 4000) {
		    // Truncate description. Otherwise ugly and prone to trigger server 'URI Too Long' error
		    description = description.substring(0, 4000);
		    description = description + " ( . . . )";
	    }
	    
		httpObjectMain.open("GET", "mining.php?src_lan="+ srcLan +"&dst_lan="+ dstLan +"&word="+ word +"&equiv="+ equivExpression +"&desc=" + description, true); // open asynchronous request
		//description = "";	
	    //document.write(description.toUpperCase());
		httpObjectMain.send(null);
		
	}

	
	function stateChangedAfterAsk() {

		if (httpObjectMain.readyState == 4) {
			
			var htmlDescription = httpObjectMain.responseText;
			
			//var documentRoot = xmlDoc.getElementsByTagName('langlinks');
			$("#description").html(htmlDescription);
			$("#description").show("slow");
		}
	}


	function fetchReply(data) {
		
		if ( typeof data == "object" ) {
		
			$.each(data, function(k,v) {
					
					//alert(k + " : " + v);
					if ( k == "langlinks" ) { 
						langlinksExists = true;
						var theTranslations = v;
						recursiveFetch(theTranslations);
						// error management
							if (!foundIt) {
								$("#answer").addClass("error");
								$("#answer").html("Wikipedia does not have an equivalent expression in " + dstLan + " for the " + srcLan + " expression " + word + ".");
							}
						
					} else if (k == "missing") {
						$("#answer").addClass("error");
						$("#answer").html("Wikipedia does not have an entry for the expression \"" + word + "\" in " + srcLan + ".");

					}
					
						fetchReply(v);
			});
			
		} else {  
			// alert ("not an object, but : " + data);
		}
		
		
	}


	function recursiveFetch(mainObject) {
	
	if ( typeof mainObject == "object" ) {
		
		$.each(mainObject, function(k,v) {

			if (mainObject["lang"] == dstLan) {
					
					equivExpression = mainObject["*"];
					//alert(equivExpression);
					$("#answer").html("<a href=\"http://" + dstLan + ".wikipedia.org/wiki/" + escape(equivExpression) + "\" target=\"_blank\">" + equivExpression + "</a>");
					foundIt = true;
				}
				//alert(k + " : " + v);
				recursiveFetch(v);
		});
		
	} else {  
		
	}
	
}
	
	function getDescription(content) {
		
		if ( typeof content == "object" ) {
			
			$.each(content, function(k,v) {
				
				
				if ( content["*"] ) {
					description = content["*"];
					//alert(typeof description + "  with length : " + description.length);
					
				}
				
				getDescription(v);
			});
			
		} else {  
			
		}
	}
	
	
	
//
// create an XMLHttpClient in a cross-browser manner
//
function initXMLHttpClient() {
	var xmlhttp;

	try {
		// Mozilla/Safari/IE7 (normal browsers)
		xmlhttp = new XMLHttpRequest();
		
	} catch (e) {
		// IE (?!)
		var success = false;
		var XMLHTTP_IDS = new Array('MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0',
				'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP');

		for ( var i = 0; i < XMLHTTP_IDS.length && !success; i++) {
			try {
				success = true;
				xmlhttp = new ActiveXObject(XMLHTTP_IDS[i]);
			} catch (e) {
			}
		}

		if (!success)
			throw new Error('Unable to create XMLHttpRequest!');
	}

	return xmlhttp;
}

	//	debugging
	function translateDebug () {
	 
    	// Call php
	    // this is my XMLHttpRequest object
		httpObjectMain = initXMLHttpClient();
	    httpObjectMain.onreadystatechange = stateChangedAfterAsk;
    	
	    var descFull = "[[Image:Jolly-roger.svg|thumb|Le Jolly Roger]] Dans l’imagerie traditionnelle, le '''Pavillon pirate''' est un pavillon noir orné d’une tête de mort surmontant deux tibias entrecroisés. On utilise parfois le terme de drapeau de pirate, mais c'est un abus de langage. En effet en langage maritime il n'y a que des pavillons. Nommé dans le monde anglo-saxon '''Jolly Roger''', ce [[pavillon (drapeau)|pavillon]] représenterait les symboles choisis par les [[pirate]]s. L'utilisation d'un pavillon noir est signalé pour la première fois en [[1700]] par un navire anglais attaqué par le pirate français [[Emmanuel Wynne]], au large de [[Cuba]]. L'expression « Jolly Roger » apparait pour la première fois en 1724 dans le livre [[Histoire Générale des Pirates]] attribué au Captain Johnson que certains supposent être un pseudonyme pour [[Daniel Defoë]]";
	    
		httpObjectMain.open("GET", "mining.php?desc="+descFull, true); // open asynchronus request
				
		httpObjectMain.send(null);
	 
	 
 }



$(document).ready( function() {
	// Allow for form submiting on Enter key
	$("#word,#dstLan,#srcLan").keyup(function(event) {
		  if(event.keyCode == 13){
		    $("#ask").click();
		  }
	});
	
	$("#innerWorkings").click(function() {
		$("#darkSide").show("slow");
		$("#whiteContent").show("slow");
		$("#closeOverlays").show("slow");
	});
	
	$("#closeOverlays").click(function() {
		$("#darkSide").hide("slow");
		$("#whiteContent").hide("slow");
		$("#closeOverlays").hide("slow");
	});
	
	$("#ask").hover(function() {
		$("#ask").attr('src', 'img/button_hover.png');
		
	},
	function() {
		$("#ask").attr('src', 'img/button_normal.png');
	});
	
	$("#ask").mousedown(function() {
		$("#ask").attr('src', 'img/button_down.png');
		
	});
});



