var help;
var translatedWords;

function getHelp(page, parent_id, parent_type) {
//document.location='//wiki/wiki/action/getHelp/page/'+page+'/parent_type/'+parent_type+'/parent_id/'+parent_id;
	var bindArgs = {
	    url:        'http://www.ephisto.com/wiki/wiki/action/getHelp/page/'+page+'/parent_type/'+parent_type+'/parent_id/'+parent_id,
	    mimetype:   "text/plain",
	    error:      function(type, errObj){
	        // handle error here
	        //alert(type+errObj);
	    },
	    load:      function(type, data, evt){
	    	//alert(data);

			document.getElementById('sitepalBubbleContent').innerHTML = data;
			document.getElementById('sitepalBubble').style.display = ''
			//document.getElementById('quickTranslationBlock').style.display = '';
			//document.getElementById('quickTranslationBlock').innerHTML = data;
	    }
	}
	var requestObj = dojo.io.bind(bindArgs);
}

function changeWordStatus(word_id, status) {
	//alert('Saving wordstatus for '+word_id+' status: '+status);
	var bindArgs = {
	    url:        '//progress/progress/action/log/word_id/'+word_id+'/status/'+status+'/return/ajax/',
	    mimetype:   "text/plain",
	    error:      function(type, errObj){
	        // handle error here
	        //alert(type+errObj);
	    },
	    load:      function(type, data, evt){
	 //   	alert(data);
			return true;
	    }
	}
	var requestObj = dojo.io.bind(bindArgs);
}


function getSel()
{
	var txt = '';
	var foundIn = '';
	if (window.getSelection){
		txt = window.getSelection();
		foundIn = 'window.getSelection()';
	}else if (document.getSelection){
		txt = document.getSelection();
		foundIn = 'document.getSelection()';
	}else if (document.selection){
		txt = document.selection.createRange().text;
		foundIn = 'document.selection.createRange()';
	}else 
		return;
		
	return txt; //'Found in: ' + foundIn + '\n' + txt;
	//document.forms[0].selectedtext.value = 'Found in: ' + foundIn + '\n' + txt;
}

function translate_word(word, error_select_word){
	if( word=="" || word==null ){
		alert(error_select_word);
		return false;
	}
	//	alert(word);
	document.getElementById('ask_me_button').value = thinking_caption;
	sayText(word,sitepal_voice,sitepal_language,sitepal_engine);
	var bindArgs = {
	    url:        translateUrl+'word/'+encodeURI(word)+'/',
	    mimetype:   "text/plain",
	    error:      function(type, errObj){
	        // handle error here
	        //alert(type+errObj);
	    },
	    load:      function(type, data, evt){

	        // handle successful response here
	        document.getElementById('sitepalBubble').style.display = '';
	        
	        document.getElementById('quickTranslationBlock').style.display = '';
	        document.getElementById('quickTranslationBlock').innerHTML = data;
	        document.getElementById('quickTranslationListBlock').style.display = 'none';
	        hideSelectDictionary();
	        document.getElementById('ask_me_button').value = ask_me_caption;
	    }
	};
    var requestObj = dojo.io.bind(bindArgs);
	
	return true;
}

function saveWordToDictionaryOid(word, dictionaryOid){
	
var bindArgs = {
    url:        saveWordToDictionaryUrl+'word/'+encodeURI(word)+'/dictionaryOid/'+dictionaryOid,
    mimetype:   "text/plain",
    error:      function(type, errObj){
        // handle error here
        //alert(type+errObj);
    },
    load:      function(type, data, evt){
        // handle successful response here
        //document.getElementById('output').innerHTML = data;
        //Lets just ignore whatever comes back
        sitepalSayMessage(wordsAddedMsg);
    }
};

// dispatch the request
    var requestObj = dojo.io.bind(bindArgs);

	return true;
}

function addWordsToDictionary(dictionaryParentOid) {
	for( i in wordsToSave ){
		saveWordToDictionaryOid(wordsToSave[i], dictionaryParentOid);
		addToQuickTranslationList(wordsToSave[i]);
	}
	wordsToSave = new Array;
}

function addToQuickTranslationList(wordstring){
	if( wordstring=='' ) {
		return false;
	}

	parts = wordstring.split(":");
		target = document.getElementById('quickTranslationListBlock');
	if( !target.innerHTML || target.innerHTML=='' )
		target.innerHTML = '<h3>'+wordlistTitle+'</h3>';
	var content = target.innerHTML+'<b>'+parts[1]+'</b><br />'+parts[0]+'<br />';
	document.getElementById('quickTranslationListBlock').innerHTML = content;
	document.getElementById('quickTranslationBlock').style.display = 'none';
	document.getElementById('quickTranslationListBlock').style.display = '';
	document.getElementById('quickTranslateMsg').style.display = 'none';
	hideSelectDictionary();

}

function showSelectDictionary(words) {
	wordsToSave[wordsToSave.length+1] = words;
	document.getElementById('selectDictionary').style.display = '';
	document.getElementById('sitepalBubble').style.display = '';
}

function hideSelectDictionary() {
	document.getElementById('selectDictionary').style.display = 'none';
}

function sitepalSayMessage(txt, no_text) {
	
	if( !no_text )
		no_text = false;
	
	if( !no_text )
		document.getElementById('sitepalBubbleContent').innerHTML = txt;
	sayText(txt,sitepal_voice,sitepal_language,sitepal_engine);
	document.getElementById('sitepalBubble').style.display = '';
}

function hideSitepalMsg() {
	document.getElementById('sitepalBubble').style.display = 'none';
}

function helpYourFriends(){

	if( !(document.getElementById('helpYourFriends')) ) {
		return false;
	}

	var bindArgs = {
	    url:        '//learn/action/helpFriends/',
	    mimetype:   "text/plain",
	    error:      function(type, errObj){
	        // handle error here
	        //alert(type+errObj);
	    },
	    load:      function(type, data, evt){
	        // handle successful response here
	        //document.getElementById('output').innerHTML = data;
	        //Lets just ignore whatever comes back
			if( data!='false' ){
				help = dojo.json.evalJson(data);
				if( help.html_question )
					data = help.html_question+'<br /><input type="button" value="'+yesBtnMsg+'" onClick="helpout()" /> <input type="button" value="'+noBtnMsg+'" onClick="hideSitepalMsg();">';
				
				document.getElementById('helpYourFriends').innerHTML = data;
			}
	    }
	};
	// dispatch the request
    var requestObj = dojo.io.bind(bindArgs);
}

function helpout() {
	data = help.html_question+'<br /><strong>'+help.language+' '+translationMsg+'</strong><br /><input type="text" value="" id="helpout_translation" /><br /><input type="button" value="'+helpOutMsg+'" onClick="saveHelpOut(document.getElementById(\'helpout_translation\').value);">';
	document.getElementById('helpYourFriends').innerHTML = data;
}

function saveHelpOut(translation) {
	if( !help.source_word || help.source_word=="" )
		word = translation+':'+help.target_word;
	else
		word = help.source_word+':'+translation;
	var bindArgs = {
	    url:        saveWordToDictionaryUrl+'word/'+encodeURI(word)+'/dictionaryOid/'+help.oid,
	    mimetype:   "text/plain",
	    error:      function(type, errObj){
	        // handle error here
	        //alert(type+errObj);
	    },
	    load:      function(type, data, evt){
	        // handle successful response here
	        //document.getElementById('output').innerHTML = data;
	        //Lets just ignore whatever comes back
	        sitepalSayMessage(wordsTranslatedMsg);
	    }
	};

	// dispatch the request
    var requestObj = dojo.io.bind(bindArgs);

	return true;

}

/*

getWordFromEvent, derived from 
http://www.faqts.com/knowledge_base/view.phtml/aid/33674

*/

/*
function getWordFromEvent (evt) {
  if (document.body && document.body.createTextRange) {
    var range = document.body.createTextRange();
    range.moveToPoint(evt.clientX, evt.clientY);
    range.expand('word');
    return range.text;
  }
  else if (evt.rangeParent && document.createRange) {
    var range = document.createRange();
    range.setStart(evt.rangeParent, evt.rangeOffset);
    range.setEnd(evt.rangeParent, evt.rangeOffset);
    expandRangeToWord(range);
    var word = range.toString();
    range.detach();
    return word;    
  }
  else {
    return null;
  }
}
*/

function getWordFromEvent (evt) {
	if (document.body && document.body.createTextRange) {
		var range = document.body.createTextRange();
		range.moveToPoint(evt.clientX, evt.clientY);
		range.expand('word');
		return range.text;
	}else if (evt.rangeParent && document.createRange) {
		var range = document.createRange();
		var rangeStart = evt.rangeOffset;
		var rangeEnd = evt.rangeOffset;
		var ws = /[\s\d\.\,?¿!¡(){}\[\];:&°@#§~_"'/\\]/;
		range.setStart(evt.rangeParent, evt.rangeOffset);
		range.setEnd(evt.rangeParent, evt.rangeOffset);
		while(!ws.test(range.toString()[0]) && rangeStart >= 0) {
			rangeStart--;
		if(rangeStart >= 0)
			range.setStart(evt.rangeParent, rangeStart);
		}
		rangeStart++;
		range.setStart(evt.rangeParent, rangeStart);
		while(!ws.test(range.toString().substr(-1,1))) {
			rangeEnd++;
		try {
			range.setEnd(evt.rangeParent, rangeEnd);
		}
		catch(ex) {
			// dunno how to figure out if rangeEnd is too big?
			break;
		}
	}
rangeEnd--;
range.setEnd(evt.rangeParent, rangeEnd);
var word = range.toString();
range.detach();
return word;
}
else {
return null;
}
} 


/* The implementation below of expandRangeToWord is not meant to be a
complete
   implementation of the functionality to expand a range to a word, with
W3C DOM
   ranges allowing different types of start/endContainer and the offset
being
   a text offset or a node offset depending on the container node type
it would
   take more than the few lines below to have a complete implementation.
   So this function is here to demonstrate within this test case that
finding a
   word from an event is possible but if you want to use it in complex
cases you
   need a better implementation of expandRangeToWord as the one below
can throw
   errors.
   Also the current implementation considers any \S+ between \s and \s a
'word',
   your aim when finding a work might differ.
*/
function expandRangeToWord (range) {
  var startOfWord = /^\s\S+$/;
  var endOfWord = /^\S+\s$/;
  var whitespace = /^\s+$/;
  // if offset is inside whitespace
  range.setStart(range.startContainer, range.startOffset - 1);

  while (whitespace.test(range.toString())) {
    range.setEnd(range.endContainer, range.endOffset + 1);
    range.setStart(range.startContainer, range.startOffset + 1);
  }
  while (!startOfWord.test(range.toString())) {
    range.setStart(range.startContainer, range.startOffset - 1);
  }
  range.setStart(range.startContainer, range.startOffset + 1);
  while (!endOfWord.test(range.toString())) {
    range.setEnd(range.endContainer, range.endOffset + 1);
  }
  range.setEnd(range.endContainer, range.endOffset - 1);
  return range.toString();
}


