/**
 * Find searched text in page
 * Designed for dotclear2 with Gandi Hosting
 * Benjamin Bellamy - 2006
 * Uses existing js programs from :
 * - http://www.webtoolkit.info/
 * - http://www.howtocreate.co.uk/jslibs/script-findinpage
 **/

/**
*  UTF-8 data decode
*  http://www.webtoolkit.info/
**/
function utf8_decode(utftext) {
	var string = "";
	var i = 0;
	var c = c1 = c2 = 0;

	while ( i < utftext.length ) {

		c = utftext.charCodeAt(i);

		if (c < 128) {
			string += String.fromCharCode(c);
			i++;
		}
		else if((c > 191) && (c < 224)) {
			c2 = utftext.charCodeAt(i+1);
			string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
			i += 2;
		}
		else {
			c2 = utftext.charCodeAt(i+1);
			c3 = utftext.charCodeAt(i+2);
			string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
			i += 3;
		}

	}
	return string;
}

//The referrer url which looks like http://domain/?q=searched%20text if we come from the result page
var referrer=document.referrer;

if(referrer.indexOf("/?q=",0)>0)
{
	// We extract the query, the we unescape it, then we decode it from utf8 :
	var q=utf8_decode(unescape(referrer.substring(referrer.indexOf("/?q=",0)+4,referrer.length)));

	/**
	* Find-in-page script By Mark Wilton-Jones 11-12/10/2002
	* http://www.howtocreate.co.uk/jslibs/script-findinpage
	*/
	if(window.find)
	{
		//Netscape compatible browsers provide the window.find method
		if( document.layers )
		{
			//Against the JS spec, Netscape 4 will produce errors if too many arguments are given
			window.find( q, false, false );
		}
		else
		{
			//window.find('search query', caseSensitive, searchBackwards, wrapAround, wholeWord, searchInFrames, showDialog)
			window.find( q, false, false, true, false, true, false );
		}
	}
	else if( document.body && document.body.createTextRange )
	{
		//IE or compatible use various TextRange features
		if( document.selection && document.selection.type != 'None' )
		{
			//If some text is selected already (previous search or if they have selected it)
			//make that the text range. Then move to the end of it to search beyond it
			var theRange = document.selection.createRange();
			theRange.collapse( false );
		} 
		else 
		{
			//If no text is selected, start from the start of the document
			var theRange = document.body.createTextRange();
		}
		//find the next occurrence of the chosen string
		var ifFound = theRange.findText( q );
		if( ifFound ) { theRange.select(); }
	}
}