var regExpBeginning = /^\s+/;
var regExpEnd       = /\s+$/;

// Supprime les espaces inutiles en début et fin de la chaîne passée en paramètre.
function trim(aString) 
{
  return aString.replace(regExpBeginning, "").replace(regExpEnd, "");
}

// Supprime les espaces inutiles en début de la chaîne passée en paramètre.
function ltrim(aString) 
{
  return aString.replace(regExpBeginning, "");
}

// Supprime les espaces inutiles en fin de la chaîne passée en paramètre.
function rtrim(aString) 
{
  return aString.replace(regExpEnd, "");
}


// Fonction permettant de tronquer une chaine de caractères et d'y ajouter "..." le cas échéant
// maxLength est la longeur maximale de la chaine de caractères de sortie "..." inclus
// La troncature est toujours effectuée entre 2 mots
function raccourcirChaine (myString, maxLength)
{
	var lastSpaceIndex;
	
	if (myString == null)
	{
		myString = "";
	}
	
	//myString = trim(myString);

	if (myString.length < maxLength)
	{
		return myString;
	}
	else
	{
		// Si la chaine est plus longue que maxLength, il faut la tronquer ET ajouter "..."
		// On fait -2 et non -3 pour gérer la situation où (titleMaxLength-3) tombe pile 
		// sur la fin d'un mot (e.g. "LES DIX COMMANDEMENDS" avec titleMaxLength=10)

		myString = myString.substring(0, (maxLength)-2);
		lastSpaceIndex = myString.lastIndexOf(" ");

		if (lastSpaceIndex != -1)
		{
			myString = myString.substring(0, lastSpaceIndex);
		}

		myString = myString + "...";
		
		return myString;
	}
}
	
function urlEncode(str) 
{
	str = escape(str);
	str = str.replace(/\//g, '%2F');
	
	//str = str.replace(/+/g, '%2B');
	//str = str.replace(/%20/g, '+');
	//str = str.replace(/*/g, '%2A');
	//str = str.replace(/@/g, '%40');
	
	return str;
}

function urlComponentEncode(str)
{
	str = urlEncode(str);
	str = str.replace(/\+/g, '%2B');
	str = str.replace(/\*/g, '%2A');
	str = str.replace(/@/g, '%40');
	
	return str;
}

function urlDecode(str) 
{
	str = str.replace('+', ' ');
	str = unescape(str);
	
	return str;
}

function getProperties(/*Object*/ obj)
{
    var msg = "";
    for (prop in obj)
    {
        msg += "property : " + prop + "\t\t value : " + obj[prop] + "\n";
    }
    // alert(msg);
}

function free(/*Object*/ obj)
{
    for (prop in obj)
    {
        obj[prop] = null;
    }
}

/*****************************************************************/
/*               TEST DE L'OS et Redirection vers page d'erreur  */
/*****************************************************************/
testOSAndRedirect=function(pErrorPage)
{
	this.errorPage = pErrorPage;
}	

testOSAndRedirect.prototype=
{
	errorPage:null,
	
	/** 
	 * This script sets OSName variable as follows:
	 * "Windows"    for all versions of Windows
	 * "MacOS"      for all versions of Macintosh OS
	 * "Linux"      for all versions of Linux
	 * "UNIX"       for all other UNIX flavors 
	 * "Unknown OS" indicates failure to detect the OS
	 */
	detectOS : function()
	{
		var OSName="Unknown OS";
		if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
		if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
		if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
		if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";
		return OSName;
	},
	
	onPageLoad : function()
	{
		var os = this.detectOS();
		if( os == "Windows")
		{
			//document.write("Ok");
		}
		else
		{
			//document.write("Nok");
			window.location=this.errorPage;
		}
	}
}


/*****************************************************************/
/* Fonctions de gestion des cookies                              */
/*****************************************************************/
function setCookie( name, value, expires, path, domain, secure ) 
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	
	/*
	if the expires variable is set, make the correct 
	expires time, the current script below will set 
	it for x number of days, to make it for hours, 
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" + escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
	( ( path ) ? ";path=" + path : "" ) + 
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

function getCookie( checkName ) 
{
	// alert('getCookie ' + checkName);
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var allCookies = document.cookie.split( ';' );
	var tempCookie = '';
	var cookieName = '';
	var cookieValue = '';
	var cookieFound = false; // set boolean t/f default f
	
	for ( i = 0; i < allCookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		tempCookie = allCookies[i].split( '=' );
		
		
		// and trim left/right whitespace while we're at it
		cookieName = tempCookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed checkName
		if ( cookieName == checkName )
		{
			cookieFound = true;
			
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( tempCookie.length > 1 )
			{
				cookieValue = unescape( tempCookie[1].replace(/^\s+|\s+$/g, '') );
			}
			
			// alert(cookieValue);
			// note that in cases where cookie is initialized but no value, null is returned
			return cookieValue;
			break;
		}
		tempCookie = null;
		cookieName = '';
	}
	
	if ( !cookieFound )
	{
		return null;
	}
}

function deleteCookie( name, path, domain ) 
{
	if ( getCookie( name ) ) 
	{
		document.cookie = name + "=" +
		( ( path ) ? ";path=" + path : "") +
		( ( domain ) ? ";domain=" + domain : "" ) +
		";expires=Thu, 01-Jan-1970 00:00:01 GMT";
	}
}

function deleteAllCanalCookies() 
{
	var canalCookieTab = new Array("fromCatalogue", "idRubrique", "idContenu", "identifiantContenu", "identifiantChaine", "numeroThematique", "isTLPOpen", "isTLCOpen", "rechercheStr", "isRechercheDisplayed");
	
	for (cookieIndex=0; cookieIndex<canalCookieTab.length ; cookieIndex++)
	{
		deleteCookie( canalCookieTab[cookieIndex], '/', '' );
	}
}



function waitForDsRubriqueToBeLoaded()
{
	if (dsRubrique.getLoadDataRequestIsPending())
	{
		setTimeout("waitForDsRubriqueToBeLoaded()", 300);
	}
}

/*
 * Mise en majuscule de la première lettre de la chaine strObj
 * Les autres lettres sont passées en minuscules
 *
 */
function strCap(strObj)
{
	return(strObj.charAt(0).toUpperCase()+strObj.substr(1).toLowerCase());
}

/*
 * Fonction strCapFirstLetters
 * Mise en majuscules de la première lettre de chaque mot de la chaine strObj
 * strObj        : la chaine à traiter
 * wordIndexStart: l'index du mot à partir duquel on commence à mettre la première lettre en majuscule
 *
 */
function strCapFirstLetters(strObj, wordIndexStart)
{				
	var finalStrObj = "";
	
	// On divise la chaine en mots
	var regSpace=new RegExp(" +", "g"); // 0 ou 1 espace
	var wordTab=strObj.split(regSpace);

	if (wordIndexStart > wordTab.length)
	{ // On traite toute la chaine
		wordIndexStart = 0;
	}

	if (wordIndexStart > 0)
	{ // On recopie les premiers mots sans modification de la case
		for (var i=0; i<wordIndexStart; i++) 
		{
			finalStrObj = finalStrObj.concat(wordTab[i]+" ");
		}
	}
	
	for (var i=wordIndexStart; i<wordTab.length; i++) 
	{ // Mise en majuscule de la première lettre de chaque mot
		finalStrObj = finalStrObj.concat(strCap(wordTab[i])+" ");
	}
	
	// on retire le dernier espace (en trop)
	finalStrObj = finalStrObj.substr(0, strObj.length);
	
	return(finalStrObj);
}


/*
 * Fonction highlightSearchedString
 * Surligner la chaine searchedStr dans la chaine strObj
 * Les premières lettres de chaque mot de la chaine de sortie sont mises en majuscule
 * strObj     : la chaine à traiter
 * searchedStr: la chaine à surligner
 *
 */
function highlightSearchedString(strObj, searchedStr)
{
	var finalSearchedString = "";
	var highlightTagOpen  = "<span style='background-color:#FFFFFF; color:#323232;'>";
	var highlightTagClose = "</span>";
	
	// Mise en majuscule des premières lettres de la chaine à traiter
	strObj=strCapFirstLetters(trim(strObj), 0);

	var idx = strObj.toLowerCase().indexOf(searchedStr.toLowerCase());
	
	// On met en majuscules les premières lettres de la chaine recherchée
	// si ces lettres correspondent à des débuts de mot
	if (idx != -1)
	{ // Il y a des occurences de la chaine recherchée
		if ((idx == 0) || (strObj[idx-1] == " "))
		{ // La chaine recherchée commence au début d'un mot
			finalSearchedString = strCapFirstLetters(searchedStr, 0);
		}
		else
		{ // La chaine recherchée commence au mileu d'un mot
			finalSearchedString = strCapFirstLetters(searchedStr, 1);
		}
		
		var fireg = new RegExp(finalSearchedString, "gi");
		var newString = strObj.replace(fireg, highlightTagOpen+finalSearchedString+highlightTagClose);
	}
	else
	{
		newString = strObj;
	}
	
	return newString;
}

