/**
 * JSON handling
 * Overloads Object
 **/
/*
json.js
2011-02-23

Public Domain

No warranty expressed or implied. Use at your own risk.

This file has been superceded by http://www.JSON.org/json2.js

See http://www.JSON.org/js.html

This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html

USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.

This file adds these methods to JavaScript:

object.toJSONString(whitelist)
This method produce a JSON text from a JavaScript value.
It must not contain any cyclical references. Illegal values
will be excluded.

The default conversion for dates is to an ISO string. You can
add a toJSONString method to any date object to get a different
representation.

The object and array methods can take an optional whitelist
argument. A whitelist is an array of strings. If it is provided,
keys in objects not found in the whitelist are excluded.

string.parseJSON(filter)
This method parses a JSON text to produce an object or
array. It can throw a SyntaxError exception.

The optional filter parameter is a function which can filter and
transform the results. It receives each of the keys and values, and
its return value is used instead of the original value. If it
returns what it received, then structure is not modified. If it
returns undefined then the member is deleted.

Example:

// Parse the text. If a key contains the string 'date' then
// convert the value to a date.

myData = text.parseJSON(function (key, value) {
return key.indexOf('date') >= 0 ? new Date(value) : value;
});

This file will break programs with improper for..in loops. See
http://yuiblog.com/blog/2006/09/26/for-in-intrigue/

This file creates a global JSON object containing two methods: stringify
and parse.

JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.

replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.

space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or '&nbsp;'),
it contains the characters used to indent at each level.

This method produces a JSON text from a JavaScript value.

When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the object holding the key.

For example, this would serialize Dates as ISO strings.

Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}

return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};

You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.

If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.

Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.

The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.

If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.

Example:

text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'


text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'

text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'


JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.

The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.

Example:

// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.

myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});

myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});


This is a reference implementation. You are free to copy, modify, or
redistribute.
*/

/*jslint evil: true, regexp: false */

/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, parseJSON, prototype, push, replace, slice,
stringify, test, toJSON, toJSONString, toString, valueOf
*/


// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.

var JSON;
if (!JSON) {
    JSON = {};
}

(function () {
    "use strict";

    function f(n) {
        // Format integers to have at least two digits.
        return n < 10 ? '0' + n : n;
    }

    if (typeof Date.prototype.toJSON !== 'function') {

        Date.prototype.toJSON = function (key) {

            return isFinite(this.valueOf()) ?
                this.getUTCFullYear() + '-' +
                f(this.getUTCMonth() + 1) + '-' +
                f(this.getUTCDate()) + 'T' +
                f(this.getUTCHours()) + ':' +
                f(this.getUTCMinutes()) + ':' +
                f(this.getUTCSeconds()) + 'Z' : null;
        };

        String.prototype.toJSON =
            Number.prototype.toJSON =
            Boolean.prototype.toJSON = function (key) {
                return this.valueOf();
            };
    }

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = { // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        rep;


    function quote(string) {

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.

        escapable.lastIndex = 0;
        return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
            var c = meta[a];
            return typeof c === 'string' ? c :
                '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
        }) + '"' : '"' + string + '"';
    }


    function str(key, holder) {

// Produce a string from holder[key].

        var i, // The loop counter.
            k, // The member key.
            v, // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];

// If the value has a toJSON method, call it to obtain a replacement value.

        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }

// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.

        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }

// What happens next depends on the value's type.

        switch (typeof value) {
        case 'string':
            return quote(value);

        case 'number':

// JSON numbers must be finite. Encode non-finite numbers as null.

            return isFinite(value) ? String(value) : 'null';

        case 'boolean':
        case 'null':

// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.

            return String(value);

// If the type is 'object', we might be dealing with an object or an array or
// null.

        case 'object':

// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.

            if (!value) {
                return 'null';
            }

// Make an array to hold the partial results of stringifying this object value.

            gap += indent;
            partial = [];

// Is the value an array?

            if (Object.prototype.toString.apply(value) === '[object Array]') {

// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.

                length = value.length;
                for (i = 0; i < length; i += 1) {
                    partial[i] = str(i, value) || 'null';
                }

// Join all of the elements together, separated with commas, and wrap them in
// brackets.

                v = partial.length === 0 ? '[]' : gap ?
                    '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' :
                    '[' + partial.join(',') + ']';
                gap = mind;
                return v;
            }

// If the replacer is an array, use it to select the members to be stringified.

            if (rep && typeof rep === 'object') {
                length = rep.length;
                for (i = 0; i < length; i += 1) {
                    k = rep[i];
                    if (typeof k === 'string') {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            } else {

// Otherwise, iterate through all of the keys in the object.

                for (k in value) {
                    if (Object.prototype.hasOwnProperty.call(value, k)) {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            }

// Join all of the member texts together, separated with commas,
// and wrap them in braces.

            v = partial.length === 0 ? '{}' : gap ?
                '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' :
                '{' + partial.join(',') + '}';
            gap = mind;
            return v;
        }
    }

// If the JSON object does not yet have a stringify method, give it one.

    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function (value, replacer, space) {

// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.

            var i;
            gap = '';
            indent = '';

// If the space parameter is a number, make an indent string containing that
// many spaces.

            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }

// If the space parameter is a string, it will be used as the indent string.

            } else if (typeof space === 'string') {
                indent = space;
            }

// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.

            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                    typeof replacer.length !== 'number')) {
                throw new Error('JSON.stringify');
            }

// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.

            return str('', {'': value});
        };
    }


// If the JSON object does not yet have a parse method, give it one.

    if (typeof JSON.parse !== 'function') {
        JSON.parse = function (text, reviver) {

// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.

            var j;

            function walk(holder, key) {

// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.

                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.prototype.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }


// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.

            text = String(text);
            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }

// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.

// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

            if (/^[\],:{}\s]*$/
                    .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
                        .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
                        .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

                j = eval('(' + text + ')');

// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.

                return typeof reviver === 'function' ?
                    walk({'': j}, '') : j;
            }

// If the text is not JSON parseable, then a SyntaxError is thrown.

            throw new SyntaxError('JSON.parse');
        };
    }

// Augment the basic prototypes if they have not already been augmented.
// These forms are obsolete. It is recommended that JSON.stringify and
// JSON.parse be used instead.

//    if (!Object.prototype.toJSONString) {
//        Object.prototype.toJSONString = function (filter) {
//            return JSON.stringify(this, filter);
//        };
//        Object.prototype.parseJSON = function (filter) {
//            return JSON.parse(this, filter);
//        };
//    }
}());
/**
 * DISPLAY CLASS
 * 
 * Utilisé à des fins de tests uniquement.
 * Permet d'afficher différentes informations provenant des classes ci-dessous.
 */

var	display = {
	_container: null,
	_enabled: false,
	
	notice: function(msg, align) {
		if (this._enabled) {
			try {
				this._createNoticeNode(msg, (align) ? align : 'center');
			} catch (e) {}
		}
	},
	error: function(msg, align) {
		if (this._enabled) {
			try {
				this._createErrorNode(msg, (align) ? align : 'center');
			} catch (e) {}
		}
	},
	
	_createNoticeNode: function(msg, align) {
		if (!this._container) {
			this._createContainer();
		}
		noticeNode = document.createElement('div');
		noticeNode.style.backgroundColor = '#EEEEA2';
		noticeNode.style.borderBottom = '1px solid black';
		noticeNode.style.width = '100%';
		noticeNode.style.textAlign = align;
		noticeNode.innerHTML = msg;
		this._container.appendChild(noticeNode);
	},
	_createErrorNode: function(msg, align) {
		if (!this._container) {
			this._createContainer();
		}
		errorNode = document.createElement('div');
		errorNode.style.backgroundColor = 'red';
		errorNode.style.color = 'white';
		errorNode.style.fontWeight = 'bold';
		errorNode.style.borderBottom = '1px solid black';
		errorNode.style.width = '100%';
		errorNode.style.textAlign = align;
		errorNode.innerHTML = msg;
		this._container.appendChild(errorNode);
	},
	_createContainer: function() {
		if (!this._container && !document.getElementById('wsb_messages'))
		{
			this._container = document.createElement('div');
			this._container.setAttribute('id', 'wsb_messages');
			this._container.style.borderBottom = '2px solid black';
			this._container.style.width = '100%';
			this._container.style.textAlign = 'center';
			document.body.insertBefore(this._container, document.body.firstElementChild);
		}
	}
};

/**
 * COOKIES CLASS
 * 
 * Permet de lire et d'écrire des Cookies.
 **/

var	cookies = {
	/**
	 * PUBLIC: create
	 * 
	 * Crée un Cookie (ou le met à jour si celui-ci existe déjà).
	 * Doivent être spécifiés : cookieName (nom du Cookie), cookieValue (valeur du Cookie), cookieLength (durée avant l'expiration du Cookie)
	 */
	create: function(cookieName, cookieValue, cookieLength) {
		var		date = new Date();
		date.setTime(date.getTime() + cookieLength);
		var		expires = ((cookieLength) ? '; expires=' + date.toGMTString() : '');
	
		document.cookie = cookieName + '=' + cookieValue + expires + '; path=/';
if (document.getElementById('cookie' + cookieName)) {
document.getElementById('cookie' + cookieName).value = cookieValue;
}
	},

	/**
	 * PUBLIC: read
	 * 
	 * Permet d'obtenir la valeur d'un Cookie.
	 * Renvoie null si le Cookie n'existe pas.
	 * Doit être spécifié : cookieName (nom du Cookie)
	 */
	read: function(cookieName) {
		var		cnt;
		var		cookie;
		var		searched = cookieName + '=';
		var		cookies = document.cookie.split(';');
		
		for (cnt = 0; cnt < cookies.length; ++cnt) {
			cookie = String(cookies[cnt]).replace(/^\s+/g, String());
			if (cookie.indexOf(searched) === 0) {
if (document.getElementById('cookie' + cookieName)) {
document.getElementById('cookie' + cookieName).value = cookie.substring(searched.length, cookie.length);
}
				return (cookie.substring(searched.length, cookie.length));
			}
		}
//display.error(cookieName + ' not found');
if (document.getElementById('cookie' + cookieName)) {
document.getElementById('cookie' + cookieName).value = '[NOT SET]';
}
		return (null);
	}
};

/**
 * BROWSER CLASS
 * 
 * Permet d'effectuer diverses opérations vis-à-vis du navigateur
 */
var browser = {
	handleEvent: function(event, element, fct) {
//		try {
			if (element.addEventListener)
				element.addEventListener(event, fct, false);
//			else if (element.attachEvent) {
//				element['e' + event + fct] = fct;
//				element[type+fn] = function() { element['e' + event + fct](window.event); }
//				element.attachEvent('on' + event, element[event + fct]);
//			}
			else {
				eval('element.on' + event + ' = fct');
			}
//		} catch (e) { alert(e); }
	},
	addOnload: function(fct) {
		browser.handleEvent('load', window, fct);
//		
//		var	oldOnload = window.onload;
//		window.onload = function() {
//			if (oldOnload) {
//				oldOnload();
//			}
//			fct();
//		};
	},
	getElementsByClassName: function(className, tag, root) {
		var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
		if (!tag) {
			tag = "*";
		}
		if (!root) {
			root = document.body;
		}
		var elements = (tag === "*" && root.all) ? root.all : root.getElementsByTagName(tag);
		var result = [];
		var current;
		var length = elements.length;
		var	cnt;
		for (cnt = 0; cnt < length; ++cnt) {
			current = elements[cnt];
			if(testClass.test(current.className)) {
				result.push(current);
			}
		}
		return (result);
	},
	addPossibleInteraction: function(element) {
		browser.handleEvent('click', element, function() { wsb.clicked(this); });
		browser.handleEvent('mouseover', element, function() { wsb.lookedAt(this); });
		browser.handleEvent('mouseout', element, function() { wsb.lookedOut(this); });
//		element.onclick = new Function("wsb.clicked(this);");
//		element.onmouseover = new Function("wsb.lookedAt(this);");
//		element.onmouseout = new Function("wsb.lookedOut(this);");
	}
};


/**
 * WSBARTICLE CLASS
 * 
 * Contient les informations d'un élément d'un panier :
 * serviceId (ID de catégorie), optionId (ID d'option), quantity (nombre d'articles commandés), price (prix unitaire)
 **/

function	WsbArticle(serviceId, optionId, quantity, price) {
	this.articleId = {serviceId: serviceId, id: optionId};
	this.quantity = quantity;
	this.price = price;
}

/**
 * WSBORDER CLASS
 * 
 * Contient l'objet qui l'a créé, ainsi qu'une liste d'articles (objets WsbArticle).
 **/

function	WsbOrder(instance) {
	this._instance = instance;
	this._articles = [];
}

/**
 * PUBLIC: addArticle
 * 
 * Ajoute un article à l'achat.
 * Doivent être spécifiés : serviceId (ID de catégorie), optionId (ID d'option), quantity (nombre d'articles commandés), price (prix unitaire)
 */
WsbOrder.prototype.addArticle = function(args) {
	// Arguments obligatoires
	if (typeof(args.serviceId) === 'undefined'
		|| typeof(args.optionId) === 'undefined'
		|| typeof(args.quantity) === 'undefined'
		|| typeof(args.price) === 'undefined')
		return;

	this._articles.push(new WsbArticle(args.serviceId, args.optionId, args.quantity, args.price));
	return (this);
};

/**
 * PUBLIC: send
 * 
 * Envoie le panier au Web Service.
 */
WsbOrder.prototype.send = function() {
	this._instance._sendOrder(this);
};

/**
 * WSB OBJECT
 * 
 * C'est cet objet et uniquement celui-ci que le site Web utilisera directement.
 * Il permet d'effectuer les différents appels possibles au Web Service.
 **/

var	wsb = {
	_wsVersion: 'v1',
	_userId: cookies.read('_wsbA'),
	_sessionId: cookies.read('_wsbB'),
	_clientId: cookies.read('_wsbC'),
	_legacyMode: cookies.read('_wsbD'),
	_wsbHost: null,
	_key: null,
	_currentPage: {pageType: null, pageKey: null, optionId: null, serviceId: null},
	_navigationSent: false,
	_lastMessageViewed: null,
	_lastMessageViewedDate: null,
	_containers: [],
	_legacyHandlers: [],
	_recommendationClassName: 'wsbRecommendation',
	_utility: null,
	_built: false,
	
	/**
	 * PUBLIC: constructeur
	 * 
	 * Détecte l'adresse du Web Service associé.
	 */
	build: function() {
		if (this._built)
			return;
		try {
			var	scripts = document.getElementsByTagName('script');
			
			var	pathElements = scripts[scripts.length - 1].src.split('?'); 
			var	url = pathElements[0];
			var	token = pathElements[1] | null;
			
			var	urlElements = url.split('://');	// Example https://s-cobrason.web-boosting.net/v1/user/0f441a45876a3c01bfc5003a0122
			var	protocol = urlElements[0];	// Example : https
			var	fullDomain = urlElements[1].split('/')[0]; // Example : s-cobrason.web-boosting.net
			var	domainElements = fullDomain.split('.');	// Example s-cobrason | web-boosting | net
			var	subDomain = domainElements.slice(0, -2).join('.'); // Example : s-cobrason
			var	domainKey = subDomain.split('-').slice(1).join('-'); // Example : cobrason
			var	domain = domainElements.slice(-2).join('.'); // Example : web-boosting.net
            
            // DEBUT - Code temporaire FJA
            var head = document.getElementsByTagName("head")[0] || document.documentElement;
            
            var linkCss = document.createElement('link');
            linkCss.media = "all";
            linkCss.type = "text/css";
            linkCss.rel = "stylesheet";
            linkCss.href = "http://s-cobrason.web-boosting.net/custom.css";
            head.appendChild(linkCss);
            
            var script = document.createElement("script");
            script.type = "text/javascript";
            script.src = "http://s-cobrason.web-boosting.net/custom.js"
            head.insertBefore(script, head.lastChild);
            head.removeChild(script);
            
            // FIN - Code temporaire FJA
            
		} catch (e) { /* alert(e); */ }
		// https preprod.cobrason web-boosting.net v1
		this._wsbHost = this._obtainWsUrl(protocol, domainKey, domain, this._wsVersion);
		this._utility = document.createElement('div');
		this._built = true;
	},
	
	
	/**
	 * PRIVATE: _obtainWsUrl
	 * 
	 * Permet d'obtenir l'URL du Web Service à utiliser en fonction du contexte d'appel du script 
	 */
	_obtainWsUrl: function(protocol, domainKey, domain, version) {
		if (!domainKey) { domainKey = 'default'; }
		return (protocol + '://ws-' + domainKey + '.' + domain + '/' + version + '/');
	},
	
	/**
	 * PUBLIC: navigation
	 * 
	 * Permet d'envoyer au Web Service un accès du visiteur sur une certaine page.
	 * Peut être spécifié : callback (fonction appelée au retour de la requête)
	 */
	navigation: function(args) {		
		var		content = {};
		
		// La page ne peut être transmise plus d'une fois
		if (this._navigationSent === true || !this._currentPage.pageType) {
			if (args && args.callback) {
				args.callback();
			}
			return;
		}

		content.query = location.href;
		content.pageType = this._currentPage.pageType;
        if (this._clientId)
            content.clientId = this._clientId;
		
        if (this._currentPage.serviceId)
			content.serviceId = this._currentPage.serviceId;
		if (this._currentPage.optionId)
			content.optionId = this._currentPage.optionId;
		
		if (this._currentPage.pageKey)
			content.pageKey = this._currentPage.pageKey;
		
//        if (!this._cart.empty)
//            content.articles = this._cart;
        
        this._navigationSent = true;
		this._makeApiCall('POST', 'navigation', content, (args && args.callback) ? args.callback : this._onNavigationAnswer);
	},
	
	/**
	 * PUBLIC: process
	 * 
	 * Envoie les requêtes vers le Web Service et demande les recommandations associées si nécessaire.
	 * Le contexte (ID client, page, articles dans le panier, ...) doit être préalablement défini.
	 */
	process: function(args) {
		// Si nécessaire, envoyer les informations de navigation
		if (!args) args = {};
		
		args.callback = this._process;
		this.navigation(args);
	},
	
	/**
	 * PRIVATE: _process
	 * 
	 * Continue le processus suite à la transmission terminée de la navigation.
	 */
	_process: function() {
		// Recherche des emplacements de recommandation sur la page
		wsb._containers = browser.getElementsByClassName('wsbRecommendationsContainer');
		
		// Si au moins un emplacement a été établi, demander les recommandations disponibles
		if (!wsb._containers.empty)
			wsb.displayRecommendations();
	},
	
	/**
	 * PUBLIC: setPageInformations
	 * 
	 * Définit les informations sur la page, telles que pageType, pageKey, optionId et serviceId.
	 */
	setPageInformations: function(pageInformations) {
		this._currentPage = pageInformations;
	},
	
	setPageType: function(pageType) {
		this._currentPage.pageType = pageType;
	},
	setPageKey: function(pageKey) {
		this._currentPage.pageKey = pageKey;
	},
	setOptionId: function(optionId) {
		this._currentPage.optionId = optionId;
	},
	setServiceId: function(serviceId) {
		this._currentPage.serviceId = serviceId;
	},
	
	
	/**
	 * PRIVATE: _onAccessAnswer
	 * 
	 * Callback à la réception d'une réponse du Web Service suite à un 'accept'.
	 * Doivent être spécifiés : content (le contenu de la réponse sous forme d'arbre), code (le code HTTP de retour), start (la date d'envoi de la requête)
	 */
	_onNavigationAnswer: function(content, code, start) {
display.notice('< NAVIGATION ANSWER (after ' + (new Date() - start) + ' ms): ' + code + ' | ' + JSON.stringify(content), 'right');
	},
	
	/**
	 * PUBLIC: addArticleToCart
	 * 
	 * Permet d'indiquer que le visiteur vient d'ajouter un produit à son panier.
	 * Doivent être spécifiés : serviceId (ID de catégorie), optionId (ID de l'option), quantity (nombre d'articles commandés), price (prix unitaire)
	 */
	addArticleToCart: function(args) {
		// Arguments obligatoires
		if (typeof(args.serviceId) === 'undefined'
			|| typeof(args.optionId) === 'undefined'
			|| typeof(args.quantity) === 'undefined'
			|| typeof(args.price) === 'undefined')
			return;
		
		this._makeApiCall('POST', 'cart/add', {article: new WsbArticle(args.serviceId, args.optionId, args.quantity, args.price)}, this._doNothing);
	},
	addItemToCart: function(args) { wsb.addArticleToCart(args); },
	
	/**
	 * PUBLIC: removeArticleFromCart
	 * 
	 * Permet d'indiquer que le visiteur vient de retirer un produit de son panier.
	 * Doivent être spécifiés : serviceId (ID de catégorie), optionId (ID de l'option), quantity (nombre d'articles commandés), price (prix unitaire)
	 */
	removeArticleFromCart: function(args) {
		// Arguments obligatoires
		if (typeof(args.serviceId) === 'undefined'
			|| typeof(args.optionId) === 'undefined'
			|| typeof(args.quantity) === 'undefined'
			|| typeof(args.price) === 'undefined')
			return;
		
		this._makeApiCall('POST', 'cart/remove', {article: new WsbArticle(args.serviceId, args.optionId, args.quantity, args.price)}, this._doNothing);
	},
	removeItemFromCart: function(args) { wsb.removeArticleFromCart(args); },

	/**
	 * PUBLIC: clicked
	 * 
	 * Permet d'indiquer qu'une recommandation vient d'être cliquée.
	 * Doit être spécifié : recommendation (l'élèment DOM recommandation) OU recommendation (l'ID de la recommandation cliquée)
	 */
	clicked: function(recommendation) {
		wsb._lastMessageViewed = null;
		if (typeof(recommendation.id) !== 'undefined') {
			wsb._makeApiCall('POST', 'recommendation/' + recommendation.id + '/interact');
		} else {
			wsb._makeApiCall('POST', 'recommendation/' + recommendation + '/interact');
		}
	},
	
	/**
	 * PUBLIC: lookedAt
	 * 
	 * Permet d'indiquer que l'utilisateur étudie la recommandation.
	 * Doit être spécifié :  (l'élèment DOM recommandation) OU recommendation (l'ID de la recommandation cliquée)
	 */
	lookedAt: function(recommendation) {
		if (typeof(recommendation.id) !== 'undefined') {
			wsb._lastMessageViewed = recommendation.id;
		} else {
			wsb._lastMessageViewed = recommendation;
		}
		wsb._lastMessageViewedDate = new Date();
	},
	
	/**
	 * PUBLIC: lookedOut
	 * 
	 * Permet d'indiquer que l'utilisateur a arrêté d'étudier le message
	 * Doit être spécifié :  (l'élèment DOM recommandation) OU recommendation (l'ID de la recommandation cliquée)
	 */
	lookedOut: function(recommendation) {
		var	recommendationId = (recommendation.id) ? recommendation.id : recommendation;

		if (recommendationId === wsb._lastMessageViewed) {
			if ((new Date() - wsb._lastMessageViewedDate) > 1000) {
				wsb._makeApiCall('POST', 'recommendation/' + recommendationId + '/interest');
			}
		}
	},
       
	/**
	 * PUBLIC: setClientId
	 * 
	 * Définit l'ID client associé au visiteur.
	 */
    setClientId: function(clientId) {
        this._clientId = clientId;
 		cookies.create('_wsbC', this._clientId, 315569260000);
    },
    
	/**
	 * PUBLIC: makeOrder
	 * 
	 * Renvoie un objet de type 'WsbOrder'.
	 * Celui-ci permettra de spécifier les caractéristiques de la requête 'order' (articles, ...) avant de l'envoyer.
	 */
	makeOrder: function() {
		return (new WsbOrder(this));
	},
	/**
	 * PRIVATE: _onOrderAnswer
	 * 
	 * Callback à la réception d'une réponse du Web Service suite à un 'order'.
	 * Doivent être spécifiés : content (le contenu de la réponse sous forme d'arbre), code (le code HTTP de retour), start (la date d'envoi de la requête)
	 */
	_onOrderAnswer: function(content, code, start) {
display.notice('< ORDER ANSWER (after ' + (new Date() - start) + ' ms): ' + code + ' | ' + JSON.stringify(content), 'right');
	},
	
	/**
	 * PUBLIC: listRecommendations
	 * 
	 * Permet d'envoyer au Web Service un accès du visiteur sur une certaine page.
	 * Doit être spécifié : callback (la fonction vers laquelle sera renvoyé le résultat - éventuellement null)
	 * Peuvent être spécifiés : pageType (le type de la page consultée), pageKey (l'ID relatif au type de la page consultée)
	 */
	listRecommendations: function(args) {
		var		url = 'list';
		
		if (typeof(args.pageType) !== 'undefined') {
			url += '/' + pageType;
			if (typeof(args.pageKey) !== 'undefined') {
				url += '/' + args.pageKey;
			}
		} else if (this._currentPage) {
			if (typeof(this._currentPage.pageType) !== 'undefined') {
				url += '/' + this._currentPage.pageType;
				if (typeof(this._currentPage.optionId) !== 'undefined') {
					url += '/' + this._currentPage.optionId;
				} else if (typeof(this._currentPage.serviceId) !== 'undefined') {
					url += '/' + this._currentPage.serviceId;
				} else if (typeof(this._currentPage.pageKey) !== 'undefined') {
					url += '/' + this._currentPage.pageKey;
				} 
			}
		}
		if (typeof(args.html) !== 'undefined' && args.html !== false) {
			url += '/html'
		}
		
		var		result = this._makeApiCall('GET', url, null, (typeof(args.callback) !== 'undefined') ? args.callback : null);
if (typeof(args.callback) === 'undefined' || !args.callback) {
display.notice('< SYNCHRONOUS LIST ANSWER (after ' + (new Date() - result.start) + ' ms): ' + result.code + ' | ' + JSON.stringify(result), 'right');
}
		if (typeof(args.callback) === 'undefined' || !args.callback) {
			return (result.content);
		}
	},

	/**
	 * PUBLIC: obtainRecommendation
	 * 
	 * Permet d'envoyer au Web Service un accès du visiteur sur une certaine page.
	 * Doit être spécifié : callback (la fonction vers laquelle sera renvoyé le résultat - éventuellement null)
	 * Peuvent être spécifiés : pageType (le type de la page consultée) ET pageKey (l'ID relatif au type de la page consultée)
	 * OU Peut être spécifié : recommendationId (l'ID du recommandation que l'on souhaite obtenir)
	 */
	obtainRecommendation: function(args)
	{
		var		url = 'recommendation';
		
		if (typeof(args.recommendationId) !== 'undefined') {
			url += '/' + args.recommendationId;
		} else {
			if (typeof(args.pageType) !== 'undefined') {
				url += '/' + args.pageType;
				if (typeof(args.pageKey) !== 'undefined') {
					url += '/' + args.pageKey;
				}
			} else {
				if (typeof(this._currentPage.pageType) !== 'undefined') {
					url += '/' + this._currentPage.pageType;
					if (typeof(this._currentPage.optionId) !== 'undefined') {
						url += '/' + this._currentPage.optionId;
					} else if (typeof(this._currentPage.serviceId) !== 'undefined') {
						url += '/' + this._currentPage.serviceId;
					} else if (typeof(this._currentPage.pageKey) !== 'undefined') {
						url += '/' + this._currentPage.pageKey;
					} 
				}
			}
		}
		if (typeof(args.html) !== 'undefined' && args.html !== false) {
			url += '/html'
		}

		var		result = this._makeApiCall('GET', url, null, (typeof(args.callback) !== 'undefined') ? args.callback : null);
if (typeof(args.callback) === 'undefined' || !callback) {
display.notice('< SYNCHRONOUS OBTAIN ANSWER (after ' + (new Date() - result.start) + ' ms): ' + result.code + ' | ' + JSON.stringify(result), 'right');
}
		if (typeof(args.callback) === 'undefined' || !callback) {
			return (result.content);
		}
	},
	
	/**
	 * PUBLIC: displayRecommendations
	 * 
	 * Permet d'afficher les recommandations disponibles pour l'utilisateur sur la page courante.
	 * Doit faire suite à un appel 'navigation' si 'pageType' / 'serviceId' / optionId' ne sont pas spécifiés.
	 * Réalise un appel à 'listRecommendations'.
	 */
	displayRecommendations: function() {
			setTimeout('wsb.listRecommendations({callback: wsb._displayRecommendations, html: true})', 1000);
	},
	
	/**
	 * PRIVATE: _displayRecommendations
	 * 
	 * Permet d'afficher les recommandations disponibles pour l'utilisateur sur la page courante.
	 * Est appelée suite automatiquement suite à l'appel 'listRecommendations' émis par 'displayRecommendations.
	 */
	_displayRecommendations: function(recommendations) {
		var	displayed = [];
		
		if (!recommendations.list || !recommendations.list.length)
			return;
		
		for (key in recommendations.list) {
			var	recommendation = recommendations.list[key];
			var	toPush = recommendation.type + recommendation.content;
			var	toSkip = false;
			
			if (recommendation.html
				&& !(recommendation.html.length > 5 && recommendation.html.substring(0, 6) === 'ERROR:')) {
				if (typeof(displayed[recommendation.display]) === 'undefined') {
					displayed[recommendation.display] = new Array();
				}
				if (typeof(displayed[recommendation.type]) === 'undefined') {
					displayed[recommendation.type] = new Array();
				}
				
				// Checking that the recommendation content hasn't been already displayed
				for (var cnt = 0; cnt < displayed[recommendation.display].length; ++cnt) {  
					if(displayed[recommendation.display][cnt] == toPush) {
						toSkip = true;
						break;
					}  
				}
				if (toSkip) { continue; }
				
				var	receiver = wsb._getReceiver(recommendation, recommendations.blocks);
				if (receiver) {
				    var content = wsb._getRecommendationHtmlNode(recommendation);
				    receiver.appendChild(content);
					displayed[recommendation.display].push(toPush);
					displayed[recommendation.type].push(toPush);
				}	
			} else {
//				display.error('No HTML for recommendation ' + JSON.stringify(recommendation));
			}
		}
        
        
        // Permet de supprimer le container si le nombre maximal de recommendations n'est pas atteint
        for (key in wsb._containers) {
            var container = wsb._containers[key];
            try {
            	var	limits = JSON.parse(container.getAttribute("data-limits"));
                var	contains = JSON.parse(container.getAttribute("data-contains"));
			} catch (e) { 
                /* alert(e); */ 
                continue; 
            }
            if (limits && limits.max && contains && contains.recommendations) {
                if (contains.recommendations < limits.max) {
                    container.innerHTML = '';
                } else {
                    // Code spécifique Cobrason : à supprimer
                    if (wsb._currentPage.pageKey == 'HOME') {
                        var objetRemovable = document.getElementById('wsbRemovableContent1');
                        objetRemovable.innerHTML = '';
                        objetRemovable.style.display = 'none';
                    }
                }
            }
		}
        
		setTimeout('wsb._registerInteractions()', 100);
	},
	
	/**
	 * PRIVATE: _getRecommendationHtmlNode
	 * 
	 * Renvoie le HTML de la recommandation à insérer sur le site
	 */
	_getRecommendationHtmlNode: function(recommendation) {
		wsb._utility.className = '';
		wsb._utility.innerHTML = recommendation.html;
        
		var	injectedDomElement = wsb._utility;
		wsb._evalInsertedScriptsAndStyles(injectedDomElement);
        
		if (injectedDomElement.hasChildNodes() == 1 && typeof(injectedDomElement.firstChild.className) != 'undefined')
			injectedDomElement = injectedDomElement.firstChild;
		
		injectedDomElement.className = wsb._recommendationClassName + ((injectedDomElement.className) ? (' ' + injectedDomElement.className) : '');
		injectedDomElement.id = recommendation.recommendationId;
        
		return injectedDomElement;
	},
    
    /**
	 * PRIVATE: _evalInsertedScriptsAndStyles
	 * 
	 * Trouve et exécute les scripts contenus dans le HTML
     * Trouve et insère les styles contenus dans le HTML
	 * 
	 * Doit être spécifié : element
	 */
    _evalInsertedScriptsAndStyles: function(element) {       
        function nodeName(elem, name) {
            return elem.nodeName && elem.nodeName.toUpperCase() ===
                      name.toUpperCase();
        };
        
        function evalScript(elem) {
            var data = (elem.text || elem.textContent || elem.innerHTML || "" ),
                head = document.getElementsByTagName("head")[0] || document.documentElement,
                script = document.createElement("script");
            script.type = "text/javascript";
            try {
                // doesn't work on ie...
                script.appendChild(document.createTextNode(data));      
            } catch(e) {
                // IE has funky script nodes
                script.text = data;
            }
            
            head.insertBefore(script, head.firstChild);
            head.removeChild(script);
        };
        
        function evalStyle(elem) {
            var data = (elem.text || elem.textContent || elem.innerHTML || "" ),
                head = document.getElementsByTagName("head")[0] || document.documentElement,
                cssNode = document.createElement("style");
            cssNode.type = "text/css";
            if (cssNode.styleSheet) {
                cssNode.styleSheet.cssText = data;   
            } else {
                cssNode.appendChild(document.createTextNode(data));   
            }
            
            head.appendChild(cssNode);
        };
        
        // main section of function
        var scripts = [],
            script,
            styles = [],
            style,
            children_nodes = element.childNodes,
            child,
            i;
        
        for (i = 0; children_nodes[i]; i++) {
            child = children_nodes[i];
            if (nodeName(child, "script" ) && (!child.type || child.type.toLowerCase() === "text/javascript")) {
                scripts.push(child);
            }
            if (nodeName(child, "style" ) && (!child.type || child.type.toLowerCase() === "text/css")) {
                styles.push(child);
            }
        }
        
        for (i = 0; scripts[i]; i++) {
            script = scripts[i];
            if (script.parentNode) {
                script.parentNode.removeChild(script);
            }
            evalScript(scripts[i]);
        }

        for (i = 0; styles[i]; i++) {
            style = styles[i];
            if (style.parentNode) {
                style.parentNode.removeChild(style);
            }
            evalStyle(styles[i]);
        }
    },
	
	/**
	 * PRIVATE: _getReceiver
	 * 
	 * Renvoie un emplacement disponible pour l'affichage d'une recommandation
	 * 
	 * Doit être spécifié : recommendation (la recommandation à afficher)
	 */
	_getReceiver: function(recommendation, blocks) {
		for (key in this._containers) {
			// Obtention d'informations sur le conteneur parcouru
			try {
				var	container = this._containers[key];
				var	accepts = JSON.parse(container.getAttribute("data-accepts"));
				var	limits = JSON.parse(container.getAttribute("data-limits"));
				var	contains = JSON.parse(container.getAttribute("data-contains"));
				var	willContain = 1;
			} catch (e) { /* alert(e); */ continue; }
			
			// Vérification du dépassement de la limite de l'emplacement
			if (!contains) {
				try {
					var	blockAttributes = eval(
							'blocks.' + recommendation.type + '.' + recommendation.display + '.situation_' + recommendation.situationId);
				} catch (e) { /* alert(e); */; continue; }
				if (limits && limits.max && limits.max < blockAttributes.limits.max) {
					var	blockLimits = limits;
				} else {
					blockLimits = blockAttributes.limits;
				}
			}
			
			if (limits) {
				if (limits.max && contains && typeof(contains.recommendations) !== 'undefined') {
					if (contains.recommendations >= limits.max) { // La limite est dépassée pour cet emplacement
						continue;
					} else {
						willContain = contains.recommendations + 1;
					}
				}
			}
			
			// Vérification que l'emplacement est bien destiné à ce type de recommandation
			if (accepts && typeof(accepts.type) !== 'undefined') {
				if (accepts.type.constructor == Array) {
					var	toSkip = true;
					for (var cnt = 0; cnt < accepts.type.length; ++cnt) {  
						if (accepts.type[cnt] == recommendation.type) {
							toSkip = false;
							break;
						}
					}
					if (toSkip)
						continue;
				} else if (accepts.type !== recommendation.type) {
					continue;
				}
			}

			// Vérification que l'emplacement est bien destiné à ce type d'affichage
			if (accepts && typeof(accepts.display) !== 'undefined') {
				if (accepts.display.constructor == Array) {
					var	toSkip = true;
					for (var cnt = 0; cnt < accepts.display.length; ++cnt) {  
						if (accepts.display[cnt] == recommendation.display) {
							toSkip = false;
							break;
						}
					}
					if (toSkip)
						continue;
				} else if (accepts.display !== recommendation.display) {
					continue;
				}
			}
			
			// Vérification que l'emplacement est bien destiné à cette situation
			if (accepts && typeof(accepts.situationId) !== 'undefined') {
				if (accepts.situationId.constructor == Array) {
					var	toSkip = true;
					for (var cnt = 0; cnt < accepts.situationId.length; ++cnt) {  
						if(accepts.situationId[cnt] == recommendation.situationId) {
							toSkip = false;
							break;
						}
					}
					if (toSkip)
						continue;
				} else if (accepts.situationId !== recommendation.situationId) {
					continue;
				}
			}
			
			if (!contains) {
				// Application des attributs du conteneur
				container.setAttribute("data-limits", JSON.stringify(blockLimits));
				// Verrouillage du conteneur
				container.setAttribute("data-accepts", JSON.stringify({display: recommendation.display,
					   												   type: recommendation.type,
					   												   situationId: recommendation.situationId}));
				
				// Ajout du HTML spécifique au conteneur
                container.innerHTML += blockAttributes.preHtml + '<div class="wsbRecommendations"></div>' + blockAttributes.postHtml;
                wsb._evalInsertedScriptsAndStyles(container);
            }
			
			container.setAttribute("data-contains", JSON.stringify({recommendations: willContain,
				   													type: recommendation.type,
				   													situationId: recommendation.situationId}));

			return (browser.getElementsByClassName('wsbRecommendations', 'div', container)[0]);
		}
		return (null);
	},
	
	/**
	 * PRIVATE: _sendOrder
	 * 
	 * Permet à la classe WsbOrder de "s'envoyer" vers le Web Service.
	 * Doit être spécifié : order (objet WsbOrder)
	 */
	_sendOrder: function(order) {
		var		toSend = {};
		
		toSend.articles = order._articles;
		this._makeApiCall('POST', 'order', toSend, this._onOrderAnswer);
	},

	/**
	 * PRIVATE: _makeApiCall
	 * 
	 * Réalise l'appel AJAX au Web Service.
	 * Doivent être spécifiés : method (méthode HTTP de la requête), query (URI de la requête)
	 * Peuvent être spécifiés : content (corps de la requête sous forme d'arbre), callback (fonction appelée au retour du résultat)
	 */
	_makeApiCall: function(method, query, content, callback) {
		if (!this._legacyMode) {
			try {
				var		instance = this;
				var		xdr = this._createXdr();
				var		url = this._wsbHost;
				var		start = new Date();
		
				if (this._userId) {
					url += 'users/' + this._userId + '/';
					if (this._sessionId) {
						url += this._sessionId + '/';
					}
				}
				url += query;
display.notice('> API CALL: ' + url + '<br />' + ((content) ? JSON.stringify(content) : '[no body]'), 'left');
				xdr.open(method, url, (typeof(callback) !== 'undefined' && callback !== null));
				if (!callback) {
					// Blocking mode
					xdr.send((content) ? JSON.stringify(content) : null);
					return (wsb._onXdrStateChange(xdr, callback, start));
				}

				//TODO: modifier la ligne ci-dessous pour la rendre plus compatible (IE, FF, etc.)
				xdr.onreadystatechange = function() {wsb._onXdrStateChange(xdr, callback, start);};
				xdr.send((content) ? JSON.stringify(content) : null);

			} catch (e) {
				// AJAX request didn't go well, trying again in legacy mode this time...
				/* alert(e); */
				this._activateLegacyMode();
				this._makeApiCall(method, query, content, callback);
			}
		} else {
			try { this._makeLegacyApiCall(method, query, content, callback); }
			catch (e) {
				/* alert(e); */
			}
		}
	},

	/**
	 * PRIVATE: _activeLegacyMode
	 * 
	 * Active le mode de compatbilité avec les anciens navigateurs.
	 */
	_activateLegacyMode: function() {
		cookies.create('_wsbD', (this._legacyMode = true));
	},
	
	/**
	 * PRIVATE: _makeLegacyApiCall
	 * 
	 * Permet aux navigateurs ne supportant pas l'AJAX cross-domains l'appel au Web Service.
	 * 
	 * Doivent être spécifiés : method (méthode HTTP de la requête), query (URI de la requête)
	 * Peuvent être spécifiés : content (corps de la requête sous forme d'arbre), callback (fonction appelée au retour du résultat)
	 */
	_makeLegacyApiCall: function(method, query, content, callback) {
		var		url = this._wsbHost;

		url += 'legacy/' + method + '/';
		if (this._userId) {
			url += 'users-' + this._userId + '-';
			if (this._sessionId) {
				url += this._sessionId + '-';
			}
		}

		url += query.replace(/\//g, '-');
		if (content) {
			url += '?' + encodeURIComponent(JSON.stringify(content).replace('[', '<').replace(']', '>'));
		}

//display.notice('> LEGACY API CALL: ' + url + '<br />' + ((content) ? JSON.stringify(content) : '[no body]'), 'left');
		var call = document.createElement('script');
		call.type = 'text/javascript';
		call.src = url;
		if (callback) {
			this._legacyHandlers[query] = callback;
		}
		var target = document.getElementsByTagName('script')[0];
		target.parentNode.insertBefore(call, target);
	},

	/**
	 * PRIVATE: _createXdr
	 * 
	 * Renvoie l'objet permettant des requêtes AJAX selon le navigateur employé.
	 */
	_createXdr: function() {
		var	browser;
		var	browsers;
		
		if (window.XDomainRequest) {
			throw 'Switching to legacy mode';	// IE doesn't work correctly enough in standard mode for now
			return (new XDomainRequest());
		}

		if (window.XMLHttpRequest) {
			return (new XMLHttpRequest());
		}

		if (window.ActiveXObject) {
			browsers = ['Msxml2.XMLHTTP.6.0',
						'Msxml2.XMLHTTP.3.0',
						'Microsoft.XMLHTTP'];
			for (browser in browsers) {
				if (browsers[browser] !== '') {
					try {
						return (new ActiveXObject(browsers[browser]));
					} catch (e) {}
				}
			}
		}
		return (null);
	},
	
	/**
	 * PRIVATE: _onXdrStateChange
	 * 
	 * Systématiquement appelée lors d'un changement d'état d'une requête AJAX.
	 * Doivent être spécifiés : xhr (objet AJAX), callback (fonction appelée au retour du résultat), start (data de démarrage de la requête)
	 */
	_onXdrStateChange: function(xdr, callback, start) {
		if (xdr.readyState === 4) {
			try {
				var		result = JSON.parse(xdr.responseText);
				
				if (result) {
					if (typeof(result.id) !== 'undefined' && typeof(result.sessionId) !== 'undefined' && result.sessionId !== this._sessionId) {
						cookies.create('_wsbA', result.id, 315569260000);
						this._userId = result.id;
					}
					if (typeof(result.sessionId) !== 'undefined' && result.sessionId !== this._sessionId) {
						cookies.create('_wsbB', result.sessionId);
						this._sessionId = result.sessionId;
					}
				}
				if (callback) {
					callback(result, xdr.status, start);
				} else {
					return ({'content': result, 'code': xdr.status, 'start': start});
				}
			} catch (e) { /* alert(e); */ }
		}			
	},
	
	/**
	 * PRIVATE: _registerInteractions
	 * 
	 * Parcourt les élèments affichés au visiteur afin d'enregistrer les recommandations générées.
	 * Ceci afin d'intercepter les actions du visiteur relatives à cette recommandation.
	 */
	_registerInteractions: function() {
		var	recommendations = browser.getElementsByClassName('wsbRecommendation');
		var	recommendation;
		var	current;
		for (recommendation in recommendations) {
			if (typeof(recommendations[recommendation]) === 'object') {
				current = recommendations[recommendation];
				browser.addPossibleInteraction(current);
				wsb._makeApiCall('POST', 'recommendation/' + current.id + '/displayed', null, wsb._doNothing);
			}
		}
	},

	/**
	 * PRIVATE: _onLegacyResult
	 * 
	 * Appelé au résultat d'une requête passée en mode LEGACY.
	 */
	_onLegacyResult: function(call, code, result) {
display.notice('< LEGACY ' + call + ' RESULT: ' + code + ' | ' + JSON.stringify(result), 'right');

		if (result) {
			if (typeof(result.id) !== 'undefined' && typeof(result.sessionId) !== 'undefined' && result.sessionId !== this._sessionId) {
				cookies.create('_wsbA', result.id, 315569260000);
				this._userId = result.id;
			}
			if (typeof(result.sessionId) !== 'undefined' && result.sessionId !== this._sessionId) {
				cookies.create('_wsbB', result.sessionId);
				this._sessionId = result.sessionId;
			}
			if (this._legacyHandlers[call]) {
				this._legacyHandlers[call](result);
			} else {display.error('No valid handler for ' + call + JSON.stringify(result));}
		}
	},
	
	/**
	 * PUBLIC: displayed
	 * 
	 * Notifie le Web Service de l'affichage d'une recommandation.
	 * Les interactions avec cette recommandation seront également interceptées.
	 */
	displayed: function(element) {
		browser.addPossibleInteraction(element);
		wsb._makeApiCall('POST', 'recommendation/' + element.id + '/displayed', null, wsb._doNothing)
	},

	/**
	 * PRIVATE: _doNothing
	 * 
	 * Cette fonction ne fait rien.
	 * Utilisée pour forcer le mode asynchrone d'appels API dont on ne souhaite toutefois pas prendre particulièrement en compte le résultat.
	 */
	_doNothing: function() {}
};

wsb.build();
