var Translator = (function() {
    /**
     * Class constructor
     * @param element that triggered an action
     */
    var Translator = function(element) {        
	this.element = element;
	this.apiKey = "AIzaSyACg_pFgHjLf1gMTdSrGB-a987UiRJ-6g4";	
    };

    Translator.prototype = {        
	detect: function(what, callback) {
	    var This = this;
	    new Ajax.JSONRequest('https://www.googleapis.com/language/translate/v2/detect',{
		parameters: {
		    key: this.apiKey, 
		    q: what
		},
		onSuccess: function (data) {		    
		    callback(data.responseJSON.data.detections[0][0].language);
		}				
	    });	    
	    
	},	
	detectAndTranslate:function() {
	    var This = this;
	    new Ajax.JSONRequest('https://www.googleapis.com/language/translate/v2/detect',{
		parameters: {
		    key: this.apiKey, 
		    q: this.what
		},
		onSuccess: function (data) {
		    This.source = data.responseJSON.data.detections[0][0].language;
		    This.translate(This.source,This.target,This.what,This.callback);
		}				
	    });	    
	    
	},	
	translate:function(source,target,what,callback) {	    	    
	    
	    /**
	     * If source and target languages are the same I just
	     * return the original. Google throws an exception
	     */
	    if (source == target && source != '') {
		callback(what);
		return;
	    }
	    
	    this.source = source;
	    this.target = target;
	    this.what = what;
	    this.callback = callback;
	    
	    /**
	     * If source is not specified google can detect the language
	     */
	    if (this.source == '') {		
		this.detectAndTranslate();
	    }
	    	    
	    new Ajax.JSONRequest('https://www.googleapis.com/language/translate/v2',{
		parameters: {
		    key: this.apiKey, 
		    source: source, 
		    target: target, 
		    q: what
		},		
		onSuccess: function (data) {		    
		    if (data.responseJSON.error) {
			callback(what);
			return;
		    }		    
		    callback(data.responseJSON.data.translations[0].translatedText);
		}				
	    });	    
	}
    }
    return Translator;    
})();
