// * g?rer le focu et le blur des champs input *
function inFoc(objet){objet.className='input_focus';}
function inBlu(objet){objet.className='input_normal';}

// * convertit valeur objet en integer *
function toGoodInt(object) {
	object.value = verifyContain(object.value, "0123456789","", 0);
}

// * convertit valeur objet en float *
function toGoodFloat(object) {
	object.value = verifyContain(object.value, "0123456789.", ",.", 0);
}

// *** fonctions priv?es ***
function verifyContain(valueToVerify, accepted, replace, maxlength) {
	var acceptedValues = accepted;
	var result = "";
	for (i=0;i<valueToVerify.length;i++)  {
	  	var trouve = false;
		for (j=0;j<replace.length;j+=2) {
  			if (valueToVerify.charAt(i) == replace.charAt(j))
				result += replace.charAt(j+1);
		}
		for (j=0;j<acceptedValues.length;j++) {
  			if (valueToVerify.charAt(i) == acceptedValues.charAt(j))
				result += valueToVerify.charAt(i);
		}
	}
	if (maxlength != 0)
	if (result.length > maxlength)
  	result = result.substring(0, maxlength);
	return result;
}

// permet pour un ID donne de faire varier sa visibilite
function alternateVisibility(objectID) {
	var domStyle = findDOM(objectID,1);
	if (domStyle.display =='block') 
		domStyle.display='none';
	else domStyle.display='block';
	return false;
}

function alternateVisibilityDble(objectID, objectID1) {
	alternateVisibility(objectID);
	alternateVisibility(objectID1);
	return false;
}

// fonction demandant confirmation d'une action
// envoi vrai si action = OK
function askConfirm(message) {
    if (confirm(message)) {
       return true;
    }else{
       return false;
    }
}

function toVisible(objectID) {
	var domStyle = findDOM(objectID,1);
	domStyle.display ='block';
	return false;
}
function toNotVisible(objectID) {
	var domStyle = findDOM(objectID,1);
	domStyle.display ='none';
	return false;
}

function toVisibleInline(objectID) {
	var domStyle = findDOM(objectID,1);
	domStyle.display ='inline';
	return false;
}
function toNotVisibleInline(objectID) {
	var domStyle = findDOM(objectID,1);
	domStyle.display ='none';
	return false;
}

// use for openning a popup with the exact image size

// Script Source: CodeLifter.com
// Copyright 2003
// Do not remove this notice.

// SETUPS:
// ===============================

// Set the horizontal and vertical position for the popup

var PositionX = 100;
var PositionY = 100;

// Set these value approximately 20 pixels greater than the
// size of the largest image to be used (needed for Netscape)

var defaultWidth  = 500;
var defaultHeight = 500;

// Set autoclose true to have the window close automatically
// Set autoclose false to allow multiple popup windows

var AutoClose = true;

// Do not edit below this line...
// ================================
if (parseInt(navigator.appVersion.charAt(0))>=4){
var isNN=(navigator.appName=="Netscape")?1:0;
var isIE=(navigator.appName.indexOf("Microsoft")!=-1)?1:0;}
var optIE='scrollbars=no,width=150,height=100,left='+PositionX+',top='+PositionY;


//
// Deprecated
//
// This method was replaced by lightbox script available in revision 597 for plici release further plici_1.0.0.RC.3.r.582
// Is always used for compatibility

// fonction qui permet d'afficher une image en popup avec les bonnes dimensions
function popImage(imageURL,imageTitle, defaultWidthSet, defaultHeightSet ){
	if (defaultWidthSet != null) {
	    defaultWidth = defaultWidthSet;
	}
	if (defaultHeightSet != null) {
	    defaultHeight = defaultHeightSet;
	}
	var optNN='scrollbars=no,width='+defaultWidth+',height='+defaultHeight+',left='+PositionX+',top='+PositionY;
    canIPreview = true;
     if (imageURL=="")
        canIPreview = false;
     if (canIPreview == false) {
		alert('Aucune image ? voir');
		return false;
     }
    if (isNN)
       {imgWin=window.open('about:blank','',optNN);}
    else /*if (isIE)*/
       {imgWin=window.open('about:blank','',optIE);}
    with (imgWin.document){
        writeln('<html><head><title></title><style>body{margin:0px;}</style>');writeln('<sc'+'ript>');
        writeln('var isNN,isIE;');writeln('if (parseInt(navigator.appVersion.charAt(0))>=4){');
        writeln('isNN=(navigator.appName=="Netscape")?1:0;');writeln('isIE=(navigator.appName.indexOf("Microsoft")!=-1)?1:0;}');
        writeln('function reSizeToImage(){');writeln('if (isIE){');writeln('window.resizeTo(100,100);');
        writeln('width=100-(document.body.clientWidth-document.images[0].width);');
        writeln('height=100-(document.body.clientHeight-document.images[0].height);');
        writeln('window.resizeTo(width,height);}');writeln('if (isNN){');       
        writeln('window.innerWidth=document.images["George"].width;');writeln('window.innerHeight=document.images["George"].height;}}');
        writeln('function doTitle(){document.title="'+imageTitle+'";}');writeln('</sc'+'ript>');
        if (!AutoClose) 
			writeln('</head><body bgcolor=000000 scroll="no" onload="reSizeToImage();doTitle();self.focus()">')
        else 
			writeln('</head><body bgcolor=000000 scroll="no" onload="reSizeToImage();doTitle();self.focus()" onblur="self.close()">');
        writeln('<img name="not_used" src="'+imageURL+'" style="display:block"></body></html>');
        close();        
    }
    return true;
}



// used for InfoBulle Collapse style

var isDHTML = 0;
var isLayers = 0;
var isAll = 0;
var isID = 0;
if (document.getElementById) {
	isID = 1; isDHTML = 1;
} else {
	browserVersion = parseInt(navigator.appVersion);
	if ((navigator.appName.indexOf('Netscape') != -1) && (browserVersion == 4)) {
		isLayers = 1; isDHTML = 1;
	} else {
		if (document.all) {
			isAll = 1; isDHTML = 1;
		}
	}
}


function findDOM(objectID,withStyle) {
var menuArea = "menuArea";
    if (withStyle == 1) {
        if (isID) { return (document.getElementById(objectID).style) ; }
        else { 
            if (isAll) { return (document.all[objectID].style); }
        else {
            if (isLayers) { return (document.layers[menuArea].layers[objectID]); }
        };}
    }
    else {
        
        if (isID) { return (document.getElementById(objectID)) ; }
        else { 
            if (isAll) { return (document.all[objectID]); }
        else {
            if (isLayers) { return (document.layers[menuArea].layers[objectID]); }
        };}
    }
    return null;
}





// ********* START FOR PRINTING METHOD ************



function replaceIntoTags(start_separator, end_separator, replaceString, content, case_sensitive) {


	var mustNotStop = true;
	var i = 0;
	
	var contentForFind = content;
	if (!case_sensitive) {
		contentForFind 	= contentForFind.toUpperCase();
		start_separator = start_separator.toUpperCase();
		end_separator 	= end_separator.toUpperCase();
	}	 
	
	var tmp;
	var tmp2;
	var start_index;
	var end_index;
	for (i=0; (i<10 && mustNotStop); i++)
	 {
		tmp="";
		tmp2="";
		start_index = contentForFind.indexOf(start_separator);
		end_index   = contentForFind.indexOf(end_separator);

		if (start_index>=0 && end_index>=0) {
			tmp += content.substring(0, start_index);
			tmp += replaceString;
			tmp += content.substring(end_index+end_separator.length);
			content = tmp;
			
			tmp2 += contentForFind.substring(0, start_index);
			tmp2 += replaceString;
			tmp2 += contentForFind.substring(end_index+end_separator.length);
			contentForFind = tmp2;
		} else {
			mustNotStop = false;
		}
	
	}
	
	return content;
}

//	bodyLine = getIntoTagsFirst("<body",">", contentNoBorder, false);
//
function getIntoTagsFirst(start_separator, end_separator, content, case_sensitive) {

	stringFinded = "";

	mustNotStop = true;
	i = 0;

	contentChanged = content;
	if (!case_sensitive) {
		contentChanged 	= contentChanged.toUpperCase();
		start_separator = start_separator.toUpperCase();
		end_separator 	= end_separator.toUpperCase();
	}

	start_index = contentChanged.indexOf(start_separator);
	end_index   = contentChanged.indexOf(end_separator);
	
	//alert(start_index+"<=>"+end_index);
	
	if (start_index>=0 && end_index>=0) {
		stringFinded = content.substring(start_index, end_index+end_separator.length);
	}
	
	
	return stringFinded;
}

function popForPrinting(){

	var contentNoBorder = replaceIntoTags("<!--*JS:START_NOT_INCLUDED_FOR_PRINTING*"+"-->"
									 , "<!--*JS:END_NOT_INCLUDED_FOR_PRINTING*"+"-->"
									 , ""
									 , document.getElementsByTagName('html')[0].innerHTML
									 , false);

	contentNoBorder = replaceIntoTags("<"+"!"+"--*JS:START_WIDTH_TO_CHANGE_FOR_PRINTING*-"+"-"+">"
									 , "<"+"!"+"--*JS:END_WIDTH_TO_CHANGE_FOR_PRINTING*-"+"-"+">"
									 , " <table width='640' cellpadding='0' cellspacing='0' height='100%' > "
									 , contentNoBorder
									 , false);

	// on remplace pour le tag de haut niveau si il existe
	var eXpr = new RegExp("id=(['\"]?)body(['\"]?)([ >])");
	contentNoBorder = contentNoBorder.replace(eXpr, "id=$1body_print$2$3");

// il faut supprimer les SCRIPTS du header, car ca perturbe IE fortement
	contentNoBorder = replaceIntoTags("<"+"SCRIPT"
									 , "/"+"SCRIPT"+">"
									 , ""
									 , contentNoBorder);

	contentNoBorder = contentNoBorder.replace("<"+"!"+"--*JS:FORCE_PRINTING*-"+"-"+">",
						"<"+"SCRIPT"+" language='javascript'"+">"+" window.print();<"+"/"+"SCRIPT"+">");

	content = contentNoBorder;

    var pageWin=window.open('about:blank','_blank', 'menubar=yes');

    pageWin.document.writeln(contentNoBorder);
    pageWin.document.close();		

    return false;
}
// ********* END FOR PRINTING METHOD ************



// ********* START FOR HIGHTLIGTH From Google or From local ************
/* New: Variable searchhi_string to keep track of words being searched. */
var searchhi_string = '';

var plop_i = 0;

/* http://www.kryogenix.org/code/browser/searchhi/ */
/* Modified 20021006 to fix query string parsing and add case insensitivity */
function highlightWord(node,word) {
	

	
	// Iterate into this nodes childNodes
	if (node.hasChildNodes) {
		var hi_cn;
		for (hi_cn=0;hi_cn<node.childNodes.length;hi_cn++) {
			highlightWord(node.childNodes[hi_cn],word);
		}
	}
	
	// And do this node itself
	if (node.nodeType == 3) { // text node
		var tempNodeVal = node.nodeValue.toLowerCase();
		var tempWordVal = word.toLowerCase();
		if (tempNodeVal.indexOf(tempWordVal) != -1) {
			var pn = node.parentNode;
			if (pn.className != "searchword") {
				// word has not already been highlighted!
				var nv = node.nodeValue;
				var ni = tempNodeVal.indexOf(tempWordVal);
				// Create a load of replacement nodes
				var before = document.createTextNode(nv.substr(0,ni));
				var docWordVal = nv.substr(ni,word.length);
				var after = document.createTextNode(nv.substr(ni+word.length));
				var hiwordtext = document.createTextNode(docWordVal);
				var hiword = document.createElement("span");
				hiword.className = "searchword";
				hiword.appendChild(hiwordtext);
				pn.insertBefore(before,node);
				pn.insertBefore(hiword,node);
				pn.insertBefore(after,node);
				pn.removeChild(node);
			}
		}
	}
}

function googleSearchHighlight() {
	if (!document.createElement) return;
	var ref = document.referrer;
        ref = ref.replace(/\/search\/web\//,'?search&q='); // Most WebCrawler searches
	if (ref.indexOf('?') == -1) return;
	var qs = ref.substr(ref.indexOf('?')+1);
    var qsa = qs.split('#');
        qs = qsa[0];
        qs = qs.replace(/(^|&)p=Q&ts=e&/,'&'); // Most Eurekster searches
        qs = qs.replace(/(^|&)query=/,'&q='); // Most Lycos searches
        qs = qs.replace(/(^|&)key=/,'&q='); // Most Walhello searches
        qs = qs.replace(/(^|&)keywords=/i,'&q='); // Most Overture searches
        qs = qs.replace(/(^|&)searchfor=/,'&q='); // Most Mysearch.com searches
        qs = qs.replace(/(^|&)qt=/,'&q='); // Most Acoona.com searches
	qsa = qs.split('&');
	var qsip;
	for (var i=0;i<qsa.length;i++) {
		qsip = qsa[i].split('=');
	        if (qsip.length == 1) continue;
        	if (qsip[0] == 'q' || qsip[0] == 'p' || qsip[0] == 'w') { // q= for Google, p= for Yahoo, w= for Eurekster
			// Trim leading and trailing spaces after unescaping
			qsip[1] = unescape(qsip[1]).replace(/^\s+|\s+$/g, "");
			if( qsip[1] == '' ) continue;
                        phrases = qsip[1].replace(/\+/g,' ').split(/\"/);
			for(p=0;p<phrases.length;p++) {
			        phrases[p] = unescape(phrases[p]).replace(/^\s+|\s+$/g, "");
				if( phrases[p] == '' ) continue;
				if( p % 2 == 0 ) words = phrases[p].replace(/([+,()]|%(29|28)|\W+(AND|OR)\W+)/g,' ').split(/\s+/);
				else { words=Array(1); words[0] = phrases[p]; }
	                	for (w=0;w<words.length;w++) {
					if( words[w] == '' ) continue;
					highlightWord(document.getElementsByTagName("body")[0],words[w]);
					if( p % 2 == 0 ) searchhi_string = searchhi_string + ' ' + words[w];
					else searchhi_string = searchhi_string + ' "' + words[w] + '"';
                		}
			}

	        }
	}
}

// Everything form this point on is modified to allow for highlighting
// of terms found in the REQUEST URI
function localSearchHighlight(terms, divIdWhereToFind) {
			
			//alert(document.getElementsByTagName(divIdWhereToFind).length);
			//alert(document.getElementsByTagName("body")[0]);
			
			if (findDOM(divIdWhereToFind))
				var start_search_here = findDOM(divIdWhereToFind);
			else
				return;
				
			var qsip = Array();
			// Trim leading and trailing spaces after unescaping
			qsip[0] = 'h';
			qsip[1] = terms;
			if (qsip[1] == '' ) return;
			
			qsip[1] = unescape(qsip[1]).replace(/^\s+|\s+$/g, "");
            var phrases = qsip[1].replace(/\+/g,' ').split(/\"/);
            var words;
			for(var p=0;p<phrases.length;p++) {
			        phrases[p] = unescape(phrases[p]).replace(/^\s+|\s+$/g, "");
				if( phrases[p] == '' ) continue;
				if( p % 2 == 0 ) words = phrases[p].replace(/([+,()]|%(29|28)|\W+(AND|OR)\W+)/g,' ').split(/\s+/);
				else { words=Array(1); words[0] = phrases[p]; }
	                	for (var w=0;w<words.length;w++) {
					if( words[w] == '' ) continue;
					highlightWord(start_search_here,words[w]);
					if( p % 2 == 0 ) searchhi_string = searchhi_string + ' ' + words[w];
					else searchhi_string = searchhi_string + ' "' + words[w] + '"';
                		}
			}
}

var global_terms_for_search = "";

function setGlobalSearch(terms){
	global_terms_for_search = terms;
}

function SearchHighlight() {
	googleSearchHighlight();
	if (global_terms_for_search != "") {
		localSearchHighlight(global_terms_for_search, "where_to_search_in_1");
		localSearchHighlight(global_terms_for_search, "where_to_search_in_2");
	}
        // Trim any leading or trailing space
        // (this is an overkill way of getting rid of the leading
        //  space that always is present in searchhi_string)
        searchhi_string = searchhi_string.replace(/^\s+|\s+$/g, "");

        // In MSIE, sometimes the dynamic generation of the spans
        // for the highlighting takes the anchor out of focus.
        // Here, we put it back in focus.
        if( location.hash.length > 1 ) location.hash = location.hash;
}

//window.onload = SearchHighlight;
// ********* END FOR HIGHTLIGTH From Google or From local ************



function favoris(url, title) {
if ( navigator.appName != 'Microsoft Internet Explorer' )
{ window.sidebar.addPanel(title,url,""); }
else { window.external.AddFavorite(url,title); } }



// Php Function in Javascript
// @author: http://www.andrewpeace.com/

// @author: http://www.andrewpeace.com/javascript-is-int.html
function form_input_is_int(input){
    return !isNaN(input)&& ((parseInt(input)==input) || (parseFloat(input)==input));
}
//@author: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_explode/
function explode( delimiter, string, limit ) {
    // http://kevin.vanzonneveld.net
    // +     original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: kenneth
    // +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: d3x
    // +     bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: explode(' ', 'Kevin van Zonneveld');
    // *     returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}
    // *     example 2: explode('=', 'a=bc=d', 2);
    // *     returns 2: ['a', 'bc=d']

    var emptyArray = { 0: '' };

    // third argument is not required
    if ( arguments.length < 2
        || typeof arguments[0] == 'undefined'
        || typeof arguments[1] == 'undefined' )
    {
        return null;
    }

    if ( delimiter === ''
        || delimiter === false
        || delimiter === null )
    {
        return false;
    }

    if ( typeof delimiter == 'function'
        || typeof delimiter == 'object'
        || typeof string == 'function'
        || typeof string == 'object' )
    {
        return emptyArray;
    }

    if ( delimiter === true ) {
        delimiter = '1';
    }

    if (!limit) {
        return string.toString().split(delimiter.toString());
    } else {
        // support for limit argument
        var splitted = string.toString().split(delimiter.toString());
        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;
    }
}
// @author http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_wordwrap/
function wordwrap( str, int_width, str_break, cut ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Nick Callen
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Sakimori
    // *     example 1: wordwrap('Kevin van Zonneveld', 6, '|', true);
    // *     returns 1: 'Kevin |van |Zonnev|eld'
    // *     example 2: wordwrap('The quick brown fox jumped over the lazy dog.', 20, '<br />\n');
    // *     returns 2: 'The quick brown fox <br />\njumped over the lazy<br />\n dog.'
    // *     example 3: wordwrap('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.');
    // *     returns 3: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod \ntempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim \nveniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea \ncommodo consequat.'

    // PHP Defaults
    var m = ((arguments.length >= 2) ? arguments[1] : 75   );
    var b = ((arguments.length >= 3) ? arguments[2] : "\n" );
    var c = ((arguments.length >= 4) ? arguments[3] : false);

    var i, j, l, s, r;

    str += '';

    if (m < 1) {
        return str;
    }

    for (i = -1, l = (r = str.split("\n")).length; ++i < l; r[i] += s) {
        for(s = r[i], r[i] = ""; s.length > m; r[i] += s.slice(0, j) + ((s = s.slice(j)).length ? b : "")){
            j = c == 2 || (j = s.slice(0, m + 1).match(/\S*(\s)?$/))[1] ? m : j.input.length - j[0].length || c == 1 && m || j.input.length + (j = s.slice(m).match(/^\S*/)).input.length;
        }
    }

    return r.join("\n");
}
//@author http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_strrev/
function strrev( string ){
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // *     example 1: strrev('Kevin van Zonneveld');
    // *     returns 1: 'dlevennoZ nav niveK'

    var ret = '', i = 0;

    string += '';
    for ( i = string.length-1; i >= 0; i-- ){
       ret += string.charAt(i);
    }

    return ret;
}
// @author: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_str_pad/
function str_pad( input, pad_length, pad_string, pad_type ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // + namespaced by: Michael White (http://getsprink.com)
    // *     example 1: str_pad('Kevin van Zonneveld', 30, '-=', 'STR_PAD_LEFT');
    // *     returns 1: '-=-=-=-=-=-Kevin van Zonneveld'
    // *     example 2: str_pad('Kevin van Zonneveld', 30, '-', 'STR_PAD_BOTH');
    // *     returns 2: '------Kevin van Zonneveld-----'

    var half = '', pad_to_go;

    var str_pad_repeater = function(s, len) {
        var collect = '', i;

        while(collect.length < len) collect += s;
        collect = collect.substr(0,len);

        return collect;
    };

    input += '';

    if (pad_type != 'STR_PAD_LEFT' && pad_type != 'STR_PAD_RIGHT' && pad_type != 'STR_PAD_BOTH') { pad_type = 'STR_PAD_RIGHT'; }
    if ((pad_to_go = pad_length - input.length) > 0) {
        if (pad_type == 'STR_PAD_LEFT') { input = str_pad_repeater(pad_string, pad_to_go) + input; }
        else if (pad_type == 'STR_PAD_RIGHT') { input = input + str_pad_repeater(pad_string, pad_to_go); }
        else if (pad_type == 'STR_PAD_BOTH') {
            half = str_pad_repeater(pad_string, Math.ceil(pad_to_go/2));
            input = half + input + half;
            input = input.substr(0, pad_length);
        }
    }

    return input;
}
// @author:http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_substr/
function substr( f_string, f_start, f_length ) {
    // http://kevin.vanzonneveld.net
    // +     original by: Martijn Wieringa
    // +     bugfixed by: T.Wild
    // +      tweaked by: Onno Marsman
    // *       example 1: substr('abcdef', 0, -1);
    // *       returns 1: 'abcde'
    // *       example 2: substr(2, 0, -6);
    // *       returns 2: ''

    f_string += '';

    if(f_start < 0) {
        f_start += f_string.length;
    }

    if(f_length == undefined) {
        f_length = f_string.length;
    } else if(f_length < 0){
        f_length += f_string.length;
    } else {
        f_length += f_start;
    }

    if(f_length < f_start) {
        f_length = f_start;
    }

    return f_string.substring(f_start, f_length);
}

// @author: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_str_replace/
function str_replace(search, replace, subject) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'

    var f = search, r = replace, s = subject;
    var ra = r instanceof Array, sa = s instanceof Array, f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;

    while (j = 0, i--) {
        if (s[i]) {
            while (s[i] = (s[i]+'').split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
        }
    };

    return sa ? s : s[0];
}

// @author: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_sprintf/
function sprintf( ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Ash Searle (http://hexmen.com/blog/)
    // + namespaced by: Michael White (http://getsprink.com)
    // +    tweaked by: Jack
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Paulo Ricardo F. Santos
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: sprintf("%01.2f", 123.1);
    // *     returns 1: 123.10
    // *     example 2: sprintf("[%10s]", 'monkey');
    // *     returns 2: '[    monkey]'
    // *     example 3: sprintf("[%'#10s]", 'monkey');
    // *     returns 3: '[####monkey]'

    var regex = /%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuidfegEG])/g;
    var a = arguments, i = 0, format = a[i++];

    // pad()
    var pad = function(str, len, chr, leftJustify) {
        if (!chr) chr = ' ';
        var padding = (str.length >= len) ? '' : Array(1 + len - str.length >>> 0).join(chr);
        return leftJustify ? str + padding : padding + str;
    };

    // justify()
    var justify = function(value, prefix, leftJustify, minWidth, zeroPad, customPadChar) {
        var diff = minWidth - value.length;
        if (diff > 0) {
            if (leftJustify || !zeroPad) {
                value = pad(value, minWidth, customPadChar, leftJustify);
            } else {
                value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
            }
        }
        return value;
    };

    // formatBaseX()
    var formatBaseX = function(value, base, prefix, leftJustify, minWidth, precision, zeroPad) {
        // Note: casts negative numbers to positive ones
        var number = value >>> 0;
        prefix = prefix && number && {'2': '0b', '8': '0', '16': '0x'}[base] || '';
        value = prefix + pad(number.toString(base), precision || 0, '0', false);
        return justify(value, prefix, leftJustify, minWidth, zeroPad);
    };

    // formatString()
    var formatString = function(value, leftJustify, minWidth, precision, zeroPad, customPadChar) {
        if (precision != null) {
            value = value.slice(0, precision);
        }
        return justify(value, '', leftJustify, minWidth, zeroPad, customPadChar);
    };

    // finalFormat()
    var doFormat = function(substring, valueIndex, flags, minWidth, _, precision, type) {
        if (substring == '%%') return '%';

        // parse flags
        var leftJustify = false, positivePrefix = '', zeroPad = false, prefixBaseX = false, customPadChar = ' ';
        var flagsl = flags.length;
        for (var j = 0; flags && j < flagsl; j++) switch (flags.charAt(j)) {
            case ' ': positivePrefix = ' '; break;
            case '+': positivePrefix = '+'; break;
            case '-': leftJustify = true; break;
            case "'": customPadChar = flags.charAt(j+1); break;
            case '0': zeroPad = true; break;
            case '#': prefixBaseX = true; break;
        }

        // parameters may be null, undefined, empty-string or real valued
        // we want to ignore null, undefined and empty-string values
        if (!minWidth) {
            minWidth = 0;
        } else if (minWidth == '*') {
            minWidth = +a[i++];
        } else if (minWidth.charAt(0) == '*') {
            minWidth = +a[minWidth.slice(1, -1)];
        } else {
            minWidth = +minWidth;
        }

        // Note: undocumented perl feature:
        if (minWidth < 0) {
            minWidth = -minWidth;
            leftJustify = true;
        }

        if (!isFinite(minWidth)) {
            throw new Error('sprintf: (minimum-)width must be finite');
        }

        if (!precision) {
            precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type == 'd') ? 0 : void(0);
        } else if (precision == '*') {
            precision = +a[i++];
        } else if (precision.charAt(0) == '*') {
            precision = +a[precision.slice(1, -1)];
        } else {
            precision = +precision;
        }

        // grab value using valueIndex if required?
        var value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];

        switch (type) {
            case 's': return formatString(String(value), leftJustify, minWidth, precision, zeroPad, customPadChar);
            case 'c': return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad);
            case 'b': return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'o': return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'x': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'X': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad).toUpperCase();
            case 'u': return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'i':
            case 'd': {
                var number = parseInt(+value);
                var prefix = number < 0 ? '-' : positivePrefix;
                value = prefix + pad(String(Math.abs(number)), precision, '0', false);
                return justify(value, prefix, leftJustify, minWidth, zeroPad);
            }
            case 'e':
            case 'E':
            case 'f':
            case 'F':
            case 'g':
            case 'G': {
                var number = +value;
                var prefix = number < 0 ? '-' : positivePrefix;
                var method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())];
                var textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2];
                value = prefix + Math.abs(number)[method](precision);
                return justify(value, prefix, leftJustify, minWidth, zeroPad)[textTransform]();
            }
            default: return substring;
        }
    };

    return format.replace(regex, doFormat);
}