/*
	Global methods
*/
Array.prototype.first = function(e)
{
    return (this.length) ? this[0] : null;
};
Array.prototype.last = function(e)
{
    return (this.length) ? this[this.length-1] : null;
};
var _trace = function(message, args)
{
    var _console = window.console || false;

    if(_console)
    {
            _console.log(message, (args || ""));
    }
};

/*
 * Function _setAbstract
 * Permet de coupler methode privée avec methode public
 * dans une même classe
 */
var _setAbstract = function(_methods)
{
    var _this = this,
        name;
        
    for (name in _methods)
    {
        if (typeof _this[name] === "function")
        {		
            var _publicMethod = _this[name];
            this[name] = function(param0, param1, param2)
            {
                    var 
                            properties = arguments.callee.prototype,
                            name = properties.name || null,
                            publicMethod = properties["public"]
                    ;

                    //console.log(" ==> " + name)
                    //console.log(publicMethod)

                    if (typeof publicMethod === "function" && name)
                    {
                            return publicMethod.call(this, _methods[properties.name].call(this, param0, param1, param2));
                    }
                    return false;
            };
            _this[name].prototype = {"public": _publicMethod, "name": name};
        }
    }
};

/*
 * Classe "fullscreenElm"
 * Chaque élément s'adapte aux dimensiosn de la fenêtre
 */
var fullscreenElm = function(elm, params)
{
    //this.init(elm, params);
    return this;
};
fullscreenElm.prototype = 
{
    "container": null,
    "elements": [],
    "initialized": false,
    "current": [0, 0],

    "resize": function(width, height)
    {
        if (!this.initialized)
        {
        	return false;
        }
        
        var
        	_width = (typeof width !== "undefined") ? width : this.container.clientWidth,
        	_height = (typeof height !== "undefined") ? height : this.container.clientHeight,
        	_elements = this.elements || []
        ;
        
        for(var i=0, len=_elements.length; i<len; i++)
        {
            var elm = _elements[i] || null;
            if (!elm)
            {
            	continue;
            }     
            elm.style.width = _width + "px";
            elm.style.height = _height + "px";
        }

        this.current = [_width, _height];
        return this.current;
    },

    "reset": function()
    {
    	var _elements = this.elements || [];
        for(var i=0, len=_elements.length; i<len; i++)
        {
            var elm = _elements[i] || null;
            if (!elm)
            {
            	continue;
            }
            elm.removeAttribute('style');
        }
    },

    "init": function(elm, params)
    {
        if (typeof elm === "undefined" || !elm)
        {
                return false;
        }

        this.initialized = true;

        driver.extend(this, params);
        this.container = elm;

        // Resize de la fenêtre
        var 
        	_this = this,
        	_isFullScreenElement = _this.container.getAttribute("data-fullscreen") || "true"
        ;
        if (_isFullScreenElement == "true")
        {
	        driver.addEvent(window, "resize", function(e)
	        {
            	// _trace(_this.elements, "window.resize : " + document.body.clientWidth + ", " + document.body.clientHeight + ", " + _this.current)
                _this.resize.apply(_this);
                return true;
	        });
        }

        return this;
    }
};

/*
 * Classe Générique
 * FIXME : défnir les comportements par défaut (historique, délégation d'événement etc.)
 * FIXME : pas encore utilisée
var sandbox = function(params)
{	
	this.init(params);
};
sandbox.prototype = 
{
	"content": null,
	"init": function(params)
	{
		driver.extend(this, params);
	}
}
 */

/*
 * Feature : AjaxForm
 * Submit in Ajax and reload the content
 */
var AjaxFormElements = {};
var AjaxForm = function(params)
{
	driver.extend(this, params);
	_setAbstract.call(this,
	{
		"init": function(elm)
		{
			//_trace("AjaxForm.init : ", elm)
			if (typeof elm === "undefined" || !elm)
			{
				return false;
			}
			if (typeof AjaxFormElements[elm.id] != "undefined")
			{
				this.destroy();
			}
			
			if (typeof VarienForm !== "undefined")
			{
				elm.varientForm = new VarienForm(elm);
			}
			
			AjaxFormElements[elm.id] = this;
						
			this.elm = elm;
			var _this = this;
			if (!this.initialized)
			{
				driver.addEvent(elm, "reset", function(e)
				{
					e.preventDefault();
					_this.reset.call(_this);
				});
				driver.addEvent(elm, "submit", function(e)
				{
					e.preventDefault();
					var 
						_isFilled = (typeof this.varientForm !== "undefined") ? this.varientForm.validator.validate() : true,
						_goForSubmit = _this.onBeforeSubmit()
					;
					if (_isFilled && _goForSubmit)
					{				
						_this.submit.call(_this);
					}
				});
			}
			this.initialized = true;
			return true;
		},
		"onBeforeSubmit": function() 
		{
			//console.log("(private) onBeforeSubmit");
			return true;
		},
		"destroy": function()
		{
			if (this.elm || false)
			{
				delete AjaxFormElements[this.elm.id];
			}
			this.initialized = false;
			return true;
		}
	}, params);
	return this;
};
AjaxForm.prototype = 
{
	"initialized": false,

	"className":
	{
		"loading": 'loading'
	},
	"init": function(data)
	{
		//console.log("(public) Init");
		return true;
	},
	"onBeforeSubmit": function() 
	{
		//console.log("(public) onBeforeSubmit");
		return true;
	},
	"loading": function(data)
	{
		driver.addClass(this.elm, this.className.loading);
	},
	"complete": function(data)
	{
	  //driver.removeClass(this.elm, this.className.loading);
	},
	"reset": function() 
	{
		//console.log("(public) reset");
		return true;
	},
	"success": function() 
	{
		//console.log("(public) success");
		return true;
	},
	"error": function() 
	{
		//console.log("(public) error");
		return true;
	},
	"destroy": function(){},
	"submit": function(e)
	{
		if (driver.hasClass(this.elm, this.className.loading))
		{
			return false;
		}
		var
			_this = this
		;
		_this["loading"].call(this);
		driver.ajaxRequest.call(this, driver.extend(
		{
			"url": this.elm.action || document.location.href,
			"type": this.elm.method || "get",
			"evalJS": true,
			"complete": function(response)
			{
				driver.removeClass(_this.elm, _this.className.loading);
				_this["complete"].call(_this, response);
			},
			"error": function(response)
			{
				driver.removeClass(_this.elm, _this.className.loading);
				_this["error"].call(_this, response);
			},
			"success": function(response)
			{
				_this["success"].call(_this, response);
			}
		}, 
		{
			"data": driver.serialize(this.elm)
		}));
	}
};

/*
 * Class ajaxBox
 * Découpage de la page en plusieurs zones de chargements en ajax
 */
 
var ajaxBox = function(params)
{
	driver.extend(this, params);
	_setAbstract.call(this,
	{
		"init": function(elm)
		{
			if (typeof elm == "undefined" || !elm)
			{
				return false;
			}		
			var _this = this;

			this.initialized = true;
			this.elm = elm;
			
			// Clique sur le site
			driver.addEvent(this.elm, "click", function(e)
			{
				_this.gotoContent.call(_this, e);
			});
			this.init.call(this);
			
			/*
			// Validation des formulaires
			// FIXME : possibilité de conflit avec la partie "checkout" ou "customer"
			var forms = driver.find(elm, "form[data-target]");
			for (var i=0, len=forms.length; i<len; i++)
			{
				forms[i].submit = function(e)
				{
					var result = _this.gotoContent.call(_this, 
					{
						"target": this.form,
						"data" : driver.serialize(this.form)
					});
				}
			}
			*/
		}
	}, params);
	
	return this;
};
ajaxBox.prototype = 
{
	"elm": null,
	
	"busy": false,
	
	"init": function(){},
	"onchange": function(){},
	"loading": function(elm)
	{
		if (elm)
		{
			driver.addClass(elm, "loading");
		}
	},
	"success": function(){},
	
	"getAttrValue" : function(elm, value)
	{
		return (typeof elm.getAttribute == "undefined") ? elm[value] : elm.getAttribute(value);
	},
	
	"history": {},
	
	"destroy": function()
	{
		this.initialized = false;
		
		this.elm.removeAttribute("data-target");
		this.elm.removeAttribute("data-id");
		delete this.elm;
		delete this;
	},
	
	"getContent": function(elm)
	{
		if (!elm)
		{
			return false;
		}
		var
			_target = this.getAttrValue(elm, "data-target"),
			_id = this.getAttrValue(elm, "data-id") || null,
			_href = elm.href || elm.action || elm.getAttribute("data-action") || window.location.href
		;
		if (!_target)
		{
			return false;
		}
		return {"url": _href, "data": {"target": _target, "id": _id || null}};
	},
	
	"save": function(key, value)
	{
		this.history[key] = value;
	},
	
	"gotoContent": function(e)
	{
		var elm = e.target || false;
		if (!elm)
		{
			return false;
		}
		
		/*
		if (this.busy)
		{
			console.log("!!! un contenu est déjà en cours de chargement")
			return false;
		}
		*/
		
		// Donot care of <span> including in <a>
		var parent = elm.parentNode || null;
		if (typeof elm.tagName == "string" && parent && elm.parentNode.tagName.toLowerCase() == "a")
		{
			elm = elm.parentNode || false;
		}
		
		var 
			_recursiveContent = 0,
			_maxUp = 5,
			_loadContent = this.getContent(elm),
			_elm = elm
		;
		while(_recursiveContent<_maxUp && !_loadContent)
		{
			_elm = _elm.parentNode || null;
			if (!_elm || _elm.tagName.toLowerCase() == "body")
			{
				_recursiveContent = _maxUp;
			}
			_loadContent = this.getContent(_elm);
			_recursiveContent++;
		}
		if (!_loadContent)
		{
			return false;
		}

		//console.log("gotoContent " + this.busy);
		this.busy = true;
		
		var
			_data = _loadContent["data"],
			_path = _data["target"].split("/"),
			_target = _path[_path.length-1],
			_id = _data["id"] || "",
			
			_container = document.getElementById(_target),
			_content = document.getElementById(_id)
		;
		// Check if content already exist
		if (!_container || _content)
		{
			return false;
		}		
		
        // Reset default behaviour
        if (e.type == "click")
		{
        	window.scrollTo(0, 0);
			e.preventDefault();
		}
		
		// Load Content
		var
			_this = this,
			_url = _loadContent["url"],
			_className = "loading",
			_delay = 1200,
			_startDate = new Date(),
			_handleLoading = function(_handleSuccess)
			{
				var 
					_endDate = new Date(),
					_timeout = _delay - (_endDate.getTime() - _startDate.getTime())
				;
				if (_timeout>0)
				{
					setTimeout(_handleSuccess, _timeout);
					return;
				}
				
				_handleSuccess();
				return;
			}
		;
		
		_loadContent["data"] = driver.serialize(_data);
		_loadContent["data"] += "&" + (e.data || "");
		
		_this.loading.call(_this, _container);
		var plop = driver.ajaxRequest(driver.extend(_loadContent,
		{
			"dataType": "text/html",
			"type": "get",			
			"error": function(response)
			{
				_handleLoading(function()
				{
					_this.onchange(_data);
					_this.save.call(_this, _path[0] + '/' + _id, [_data["target"], _url]);
					_this.busy = false;
					
					driver.removeClass(_container, _className);
					driver.putHTML(_container, response.responseText);
				});
			},			
			// FIXME : le PHP est sensé renvoyer que le contenu désiré
			// identifié par le namespace "params.id"
			"success": function(response)
			{
				_handleLoading(function()
				{
					_data["url"] = _url;
					_this.currentData = _data;
					
					_this.onchange(_data);					
					_this.save.call(_this, _path[0] + '/' + _id, [_data["target"], _url]);
					_this.busy = false;
					
					driver.removeClass(_container, _className);
					driver.putHTML(_container, response.responseText);
					_this.success.call(_this);
				});
			}
		}));
		
		return true;
	}	
};


/*
 * Class fakeHistory
 * Gestion des actions back/next dans le navigateur
 */
var fakeHistory = function(params)
{
	// Params contextuels
	driver.extend(this, params);
	
	// (private) behaviors
	// the public method is called after those ones
	_setAbstract.call(this, 
	{
		"contentLoaded" : function(){},
		"onHashChange" : function(){},
		"init": function(params)
		{
			var 
				_this = this,
				_isIE = driver.hasClass(document.body, "msie"),
				_isIE8 = driver.hasClass(document.body, "msie8"),
				
				_hash = _this.getHash(),
				_data = _hash,
				_counter = history.length,
                 _newHash
			;
			
			
			// FIX : code pour IE
			if (_isIE && !_isIE8)
			{
				if (!_this.iframe)
				{
					var elm = document.createElement("iframe");
					elm.id = "historyIE";
					document.body.appendChild(elm);
					_this.iframe = elm;
				}
				_this.setIframe(_data);
				_this.setHash(_data);
			}
			
			this.initialized = true;
			
			// Update					
			setInterval(function()
			{
				// code pour IE
				if (_isIE && !_isIE8)
				{
					try
					{
						_newHash  = _this.iframe.contentWindow.document.body.innerText;
						if (_newHash !== _data) 
						{
							_data = _newHash;
							_this.setHash(_data);
							_this.navigatorEvent = true;
							_this.onHashChange();
						}
						
						// Mettre à jour l'iframe 
						// (hash vient detre changé)
						else
						{
							_newHash = _this.getHash();		
							if (_newHash !== _data)
							{
								_data = _newHash;
								_this.setIframe(_newHash);
								_this.navigatorEvent = false;
							}
						}

					} catch(e){}
				}
				
				else
				{
					_newHash = _this.getHash();
					if (_newHash != _data)
					{
						_data = _newHash;
						_this.navigatorEvent = (_counter == history.length);
						_counter = history.length;
						_this.onHashChange();
					}
				}
				
			}, 50);
			
			return true;
		}
	}, params);
	
	return this;
};
fakeHistory.prototype =
{
	"suffixe": "/",
	"counter": null,
	"navigatorEvent": false,

	"init": function(params)
	{
		//_trace("fakeHistory : (default) init");
	},
	
	// (public) onHashChange
	// called when the hash is modified
	"onHashChange" : function()	{},		
	
	"setHash" : function(hash)
	{
		if (document.location.hash != hash)
		{
			document.location.hash = hash;
		}
	},
	
	"setIframe" : function(hash)
	{
		var doc = this.iframe.contentWindow.document;
		doc.open();
		doc.write('<html><body id="hashValue">' + hash + '</body></html>');
		doc.close();
	},
	
	"getHash": function()
	{
		var 
			index = location.href.indexOf('#'),
			hash = (index === -1 ? '' : location.href.substr(index + 1))
		;
		return hash;
	}	
};

/*
 * PlaceHolder
 * FIXME : gérer le fallback avec le placeHolder HTML5
 */
var placeholder = function(elm, params)
{
	this.init(elm, params);
	return this;
};
placeholder.prototype = 
{
	"className":
	{
		"container": "placeholder-container",
		"elm": "placeholder-item"
	},
	
	"displayValue": function(e, displayValue)
	{
		var 
			_elm = e.target,
			_defaultValue = _elm.getAttribute("placeholder") || _elm.defaultValue
		;
		
		if (!_elm.defaultValue && _defaultValue)
		{
			_elm.defaultValue = _defaultValue;
		}
		
		// Focus du champ
		if (displayValue)
		{
			driver.addClass(_elm, "active");
			if (_elm.value == _defaultValue)
			{
				_elm.value = "";
			}
			return false;
		}
		
		// Désélection du champ
		driver.removeClass(_elm, "active");
		if (!_elm.value)
		{
			_elm.value = _defaultValue;
		}
		
		return true;
	},
	
	"init": function(elm)
	{
		if (typeof elm === "undefined" || !elm)
		{
			return false;
		}

		this.initialized = true;
		
		// Création du container
		driver.addClass(elm.parentNode, this.className["container"]);
		
		// AJout événement
		var _this = this;
		driver.addEvent(elm, "focus", function(e)
		{
			_this.displayValue(e, true);
		});
		driver.addEvent(elm, "blur", function(e)
		{
			_this.displayValue(e, false);
		});
		
		// Init des événements
		_this.displayValue({target: elm});
		
	}
};

/*
 * Accordéon
 */

var Accordion = function(params)
{
	var _defaultClassName = this.className;
        
        params = params || {};
	
	driver.extend(this, params);

	if(typeof this.className["content"] === "undefined")
	{
		this.className["content"] = _defaultClassName["content"];
	}
	if(typeof this.className["active"] === "undefined")
	{
		this.className["active"] = _defaultClassName["active"];
	}
	
	_setAbstract.call(this, 
	{
		"onsuccess": function()
		{
			if (this.busy)
			{
				this.busy--;
			}			
			if (!this.busy && (this.history && this.history.length == 2))
			{
				this.activeItem(this.history[0], this.history[1]);
				this.history = null;
				return this.history;
			}
			return true;
		},		
		"addToHistory": function(elm, isActive)
		{
			this.history = [elm, isActive];
			return true;
		},
		"activeItem": function(elm, isActive)
		{

			if (typeof elm === "undefined")
			{
				//_trace("DEBUG : DOM Element : 'activeItem' failed : ", arguments);
				return false;		
			}
			
			if (this.busy)
			{
				if (this.addToHistory(elm, isActive))
				{
					//_trace("DEBUG : Accordion is already playing : 'addToHistory' : ", arguments);
					return false;
				}
			}
			
			var
				_this = this,
				_elements = this.items,
				_className = this.className["active"] || "",
				_isActive = isActive || false,
				
				// FIXME : cette fonction ne semble plus fonctionner vu que "animate" existe pas défaut
				_onsuccess = function()
				{   
					_this["onsuccess"].call(_this);
				},
				_animate = this["animate"]
			;
				
			// Sauvegrader de l'élément courant
			this.current["element"] = (this.current["element"] == elm && !_isActive) ? false : elm;
			this.current["active"] = isActive;
			this.current["animations"] = [];	
			
			// Activer/Désactiver
			for(var i=0, len=_elements.length; i<len; i++)
			{
				var 
					_elm = _elements[i],
					_active = (_elm == this.current["element"]) ? _isActive : false
				;
				
				driver[(_active) ? "addClass" : "removeClass"](_elm, _className);

				this.busy++;
				if (_animate)
				{
					_animate.call(this, _elm, _active, _onsuccess);
				}
				else
				{
					_onsuccess();
				}
			}			
			return true;
		},
		
		"save": function()
		{
			//_trace("Accordion : (private) save : ", this);

			var _accordionID = this.container.id || false;
			if (!_accordionID)
			{
				_accordionID = "accordion-" - Object.keys(sliderElements).length;
				this.container.id = _sliderID;
			}			
			if (typeof accordionElements == "undefined")
			{
				window.accordionElements = {};
			}
			accordionElements[_accordionID] = this;
			return true;
		},
		
		"stop": function()
		{
			_trace("Accordion : (private) stop : ", this.current["animations"]);

			delete this.current["animations"];
			this.current["animations"] = null;
			return true;
		},
		
		"destroy": function()
		{
			_trace("Accordion : (private) destroy : ", this.current["animations"]);

			// Arret des animations
			this.stop();			

			// Suppression des événements
			var events = this.events || [];
			for(var i=0, len=events.length; i<len; i++)
			{
				var args = events[i] || ['', '', ''];
				driver.stopEvent(args[0], args[1], args[2]);
			}
			
			
			return true;
		},
		
		"init": function(elm)
		{	
			
			this.container = elm;
			
			var 
				_this = this,
				_hover = false,
				_handleEvent = this.handleEvent,
				_items = driver.find(elm, "." + this.className["item"]),
				_slides = driver.find(elm, "." + this.className["content"])
			;
			
			this.items = _items;		
			this.slides = _slides;
			// Désactivation de l'item courant
			if (_handleEvent == "mouseover")
			{
				var _handleMouseout = function(e)
				{
					_hover = false;
					setTimeout(function()
					{
						if (!_hover)
						{
							_this.activeItem(_this.current["element"], false);
						}
					}, 10);
				};
				this.events.push([elm, "mouseout", _handleMouseout]);
				driver.addEvent(elm, "mouseout", _handleMouseout);
			}
			
			// Activation de l'item
			if (_handleEvent)
			{
				for(var i=0, len=_items.length; i<len; i++)
				{
					var item = _items[i];
					item.setAttribute("data-accordion", i);
					
					var _handleActive = function(e)
					{
						_hover = true;
						if (_this.current["element"] == this && _this.current["active"])
						{
							return false;
						}
						_this.activeItem(this, true);
					};
					this.events.push([item, _handleEvent, _handleActive]);
					driver.addEvent(item, _handleEvent, _handleActive);
				}
			}
				
			this.save();
			
			return true;
		}
	});
	
	return this;
};
Accordion.prototype = 
{
	"current": 
	{
		"element": null,
		"active": false,
		"animations": []
	},
	"events": [],

	// FIXME : reference bug if 
	// those properties are defined here
	"history": null,
	"busy": 0,	
	"delay": 0,
	
	"className":
	{
		"item" : "submenu-container",
		"content": "submenu-item",
		"active": "active"
	},
	
	"handleEvent": "click",
	
	"init": function()
	{
		//_trace("(public) Accordion.init : ", arguments)
	},
	"save": function()
	{
		//_trace("(public) Accordion.save : ", arguments)
	},
	"stop": function()
	{
		//_trace("(public) Accordion.stop : ", arguments)
	},
	"destroy": function()
	{
		//_trace("(public) Accordion.destroy : ", arguments)
	},
	"animate": function()
	{
		//_trace("(public) Accordion.animate : ", arguments);
	},
	"onsuccess": function()
	{
		//_trace("(public) Accordion.onsuccess : ", arguments)
	},
	"addToHistory": function()
	{
		//_trace("(public) Accordion.addToHistory : ", arguments)
	},
	"activeItem": function()
	{
		//_trace("(public) Accordion.activeItem : ", arguments)
	}
};


var addBookmark = function(title, url)
{
	if (window.sidebar) 
	{
		window.sidebar.addPanel(title, url, "");
	} 
	else if(document.all)
	{
		window.external.AddFavorite( url, title);
	} 
	else if(window.opera && window.print)
	{
		return true;
	}
};

/*
 * Tooltip
 * Génère une infobulle personnalisable en CSS
 * à partir de la balise title de l'élément passé en argument
 */
window.tooltipElements = {};
var Tooltip = function(elm)
{
	//this.init(elm);
	return this;
};

Tooltip.prototype = 
{
	"className":
	{
		"container": "tooltip-container",
		"element": "tooltip-element",
		"active": "active"
	},
	
	"setPosition": function(coords)
	{
		if (!this.tooltip)
		{
			return false;
		}
		
		this.tooltip.style.left = coords[0] + "px";
		this.tooltip.style.top = coords[1] + "px";
		
		return coords;
	},
	
	"createElement": function(elm)
	{
		var 
			_elm = driver.getElement(elm, ".tooltip-target") || null,
			_title = _elm ? this.getTextData(_elm) : null
		;
		if (!_elm || !_title)
		{
			return false;
		}
		
		var _tooltipElement = document.createElement("p");		
		_title = document.createTextNode(_title);		
		_tooltipElement.appendChild(_title);
		
		driver.addClass(_tooltipElement, this.className["element"]);
		
		_elm.removeAttribute("title");

		var 
			_containerId = elm.getAttribute("data-tooltip-container") || null,
			_container = _containerId ? document.getElementById(_containerId) : document.body
		;
		this.container = _container;
		_container.appendChild(_tooltipElement);
		driver.addClass(_container, this.className["container"]);

		return _tooltipElement;
	},
	
	"getTextData": function(elm)
	{
		if (typeof elm == "undefined" || !elm)
		{
			return false;
		}
		var _title = elm.getAttribute("title");
		elm.removeAttribute("title");						
		return _title || false;
	},
	
	"init": function(elm)
	{
		if (typeof elm == "undefined" || !elm)
		{
			return false;
		}

		var 
			_this = this,
			_tooltipElement = this.createElement(elm)
		;
		
		if (!_tooltipElement)
		{
			return false;
		}

		// CreateElement
		this.element = elm;
		this.tooltip = _tooltipElement;		
		
		// Evénement
		driver.addEvent(elm, "mouseover", function(e)
		{
			driver.addClass(this, _this.className["active"]);
		});
		driver.addEvent(elm, "mouseout", function(e)
		{
			_this.setPosition([-5000, -5000]);
			driver.removeClass(this, _this.className["active"]);
		});
		driver.addEvent(elm, "mousemove", function(e)
		{
			_this.setPosition([e.clientX, e.clientY]);
		});
		
		var 
			_tooltipLength = Object.keys(tooltipElements).length,
			_tooltipId = elm.id || "tooltipElement-" + _tooltipLength
		;
		elm.id = _tooltipId;
		tooltipElements[_tooltipId] = this;
	}
};
/**
 * Function selectMenuElement
 * 
 * Highlight a menu item
 * 
 * @param   params  object with elem (css selector), enableClass, disableClass
 */
var selectMenuElement = function(params){
    var defaults = {
        elem:           null,
        enableClass:    'enable',
        disableClass:   'disable'
    };
    
    params = driver.extend(defaults, params);
    
    if(params.elem == null)
        return false;
    
    function init(){
        var items = driver.getElements(params.elem);
  
        for(var i = 0, len = items.length; i < len; i++){
            driver.addEvent(items[i], 'click', function(e){
                var target = e.target;

                driver.addClass(target, params.enableClass);                    
                driver.removeClass(target, params.disableClass);
                
                for(var j = 0, len = items.length; j < len; j++){
                    if(items[j] != target){                        
                        driver.removeClass(items[j], params.enableClass);
                        driver.addClass(items[j], params.disableClass);
                    }
                }
                
            });
        }
    }
    
    init();
    
    return this;
};


/*
 * Feature : fakeWindow
 * Set Window Event to a DOM element
 */

var FakeWindowElements = {};
var fakeWindow = function(params)
{
	var _params = params || {};
	if (typeof _params.type != "undefined")
	{
		this.type = _params.type;
	}
	return this;
};
fakeWindow.prototype = 
{
	"type": null,
	"links": [],
	"handleActive": function(value)
	{
		// Positionnement de la fenêtre en hauteur
		var _setTopPosition = (this.elm.getAttribute("data-scrollTop") || true).toString();
		if (_setTopPosition == "true")
		{
			var _scrollTop = (typeof window.scrollY != "undefined") ? window.scrollY : document.documentElement.scrollTop;
			this.elm.style.top = _scrollTop + "px";
		}
		
		if (!value)
		{
			driver.removeClass(this.elm, "active");
			return false;
		}

		driver.addClass(this.elm, "active");
		return true;
	},
	
	"close": function()
	{
		if (this.type == "ajax")
		{
			this._ajaxConstructor.destroy(this.elm);
			return false;
		}
		var _destroy = this.elm.getAttribute("data-windowDestroy") || this.elm["data-windowDestroy"] || null;
		if (_destroy && _destroy != "false")
		{
			this.destroy(this.elm);
		}
		this.handleActive(false);
	},
	
	"destroy": function(elm)
	{
		delete FakeWindowElements[elm.id];
		if (elm.parentNode)
		{
			elm.parentNode.removeChild(elm);
		}
		else
		{
			delete elm;
		}
	},
	
	"init": function(elm, params)
	{
		if (typeof elm == "undefined" || !elm)
		{
			return false;
		}
		
		// Supprimer la fenêtre si elle existe déjà
		if (typeof FakeWindowElements[elm.id] != "undefined")
		{
			this.destroy(elm);
		}
		
		driver.extend(this, params || {});
		var 
			_this = this,
			_params = params || {},
			_classCancel = "cancel-button",
			_defaultStatus = (window.location.hash.search(elm.id) > -1) || driver.hasClass(elm, "active") || _params["show"] || false
		;
		
		var _backgroundElement = document.createElement("span");
		driver.addClass(_backgroundElement, "background-window");
		elm.appendChild(_backgroundElement);
		driver.addEvent(_backgroundElement, "click", this.close.bind(this));

		this.background = _backgroundElement;
		this.elm = elm;
		this.elm.fake = this;
		
		FakeWindowElements[this.elm.id] = this;
		
		// Afficher
		for(var i=0, len= this.links.length; i<len; i++)
		{
			this.addLink(this,this.links[i]);
		}
		
		// Masquer
		driver.addEvent(this.elm, "click", function(e)
		{
			var 
				_elm = (driver.hasClass(e.target.parentNode, _classCancel)) ? e.target.parentNode : e.target,
				_isCancelLink = driver.hasClass(_elm, _classCancel),
				_isOpenerWindow = _elm["data-window"] || _elm.hasAttribute("data-window") || false
			;
			if (_elm == _this.background || _isCancelLink || _isOpenerWindow)
			{
				 // FIX : si ce même lien doit ouvrir une autre lightbox
				// Le setTimeout permet que les deux événements se chevauchent
				//e.preventDefault();
				setTimeout(function(){_this.close.call(_this);}, 10);
			}
		});
		// Chargement de la page
		this.handleActive(_defaultStatus);
	},

	// Add link event
	"addLink":function(fake, link)
	{
		driver.addEvent(link, "click", function(e)
		{
			e.preventDefault();
			fake.handleActive(true);
		});
	}
	
};

/*

Fakewindow DOM Ajax 
CREATE FAKE WINDOW AND OPEN IT

format d'un lien pour ouvrir une Fakewindow : 
 - <a href="%url%" data-window="#%hash%">%lien%</a>

*/
var AjaxFakeWindow = function(params)
{
	var _params = params || {};
	if (typeof _params["success"] != "undefined")
	{
		this["success"] = _params["success"];
	}
	return this;
};
AjaxFakeWindow.prototype = 
{
	"container": null,
	"elements": {},
	"getTargetElement": function(e)
	{
		var _elm = e.target || {};
		return (_elm.parentNode.tagName.toLowerCase() == "a") ? _elm.parentNode : _elm;
	},
	"init": function(elm)
	{
		if (typeof elm == "undefined" || !elm)
		{
			return false;
		}
		this.container = elm;

		var _this = this;
		driver.addEvent(elm, "click", function(e)
		{
			var
				_elm = _this.getTargetElement(e),
				_hash = _elm.hash || "",
				_windowId = _elm["data-window"] || _elm.getAttribute("data-window") || false,
				_url = _elm["data-href"] || _elm.getAttribute("data-href") || (_elm.href || "").replace(_hash, "") || false
			;			
			
			if (!_windowId || _windowId == "true" || !_url)
			{
				return false;
			}
			e.preventDefault();
			
			var _idContainer = _elm.getAttribute("data-window-container");
			_this.open({
				"url" : _url,
				"id": _windowId,
				"container": _idContainer ? document.getElementById(_idContainer) : null
			});
		});
	},
	
	"destroy": function(elm)
	{
		delete FakeWindowElements[elm.id];
		if (typeof elm.parentNode == "undefined" || !elm.parentNode)
		{
			delete elm;
			return false;
		}
		elm.parentNode.removeChild(elm);
	},
	
	"success": function()
	{
		_trace("(public) AjaxFakeWindow.success");
	},
	
	"setContent": function(_content, params)
	{
		var
			_this = this,
			_id = params.id,
			_url = params.url,
			_container = params.container || this.container,
			_data = params.data || null,
			_delay = 500,
			_startDate = params["startDate"] || new Date(),
			_endDate = new Date(),
			_timeout = _delay - (_endDate.getTime() - _startDate.getTime()),
			_handleSuccess = function(data)
			{
				driver.removeClass(_content, "loading");
				driver.putHTML(_content, _data);
				
				// Centrer la lighbox
				// dans la fenêtre parente
				var
					_height = _content.offsetHeight,
					_heightMax = document.body.clientHeight,
					_top = (_heightMax-_height)/2
				;
				if (_top < 0)
				{
					_top = 50;
					_height = (_heightMax-_top*2);
					_content.style.height = _height + "px";	
				}
				_content.style.top = _top + "px";
				
				var _scrollContent = driver.getElement(_content, ".scroll") ||  driver.getElement(_content, ".std") || null;
				if (_scrollContent)
				{
					
					var 
						_marginBottom = ($(_scrollContent).getStyle('margin-bottom') || 0).replace("px", "")*1,
						_paddingBottom = ($(_scrollContent).getStyle('padding-bottom') || 0).replace("px", "")*1,
						_scrollHeight = _content.offsetHeight - (_scrollContent.offsetTop + _marginBottom + _paddingBottom)
					;
					
					_scrollContent.style.height = _scrollHeight + "px";	
					
				}
				
				// Callback de chargement
				_this.success.call(_this, {"url": _url, "target": _id});
				
				// Exécution des scripts présents dans le contenu
				_handleScriptAfterOnload();
			}
		;
		// Différer l'affichage du contenu
		// pour éviter un effet de scintillement
		if (_timeout>0)
		{
			setTimeout(_handleSuccess, _timeout);
			return;
		}
		_handleSuccess();
		return;
	},

	"open": function(params)
	{
		var
			_url = params.url,
			_id = params.id,
			_container = params.container || this.container,
			_data = params.data || null,
			_elm = document.getElementById(_id),
			_classWindow = "box-window",
			_classContent = "box-container",
			_this = this,
			_content = null
		;

		// Création du container
		if (!_elm)
		{
			_elm = document.createElement("div");
			_elm.id = _id;
			_elm.className = _classWindow;
			
			_content = document.createElement("div");
			_content.className = _classContent;	
			_elm.appendChild(_content);
			
			_container.appendChild(_elm);
		}
		if (typeof _content == "undefined" || !_content)
		{
			_content = driver.getElement(_elm, "." + _classContent);
			_content.style = "";
		}

		// Instanciation de la fenêtre		
		var _window = new fakeWindow({"type": "ajax"});
		if (!_window)
		{
			return false;
		}
		_window._ajaxConstructor = this;
		_window.init(_elm);
		
		// Afficher la fenêtre
		driver.addClass(_elm, "active");
		
		// Garder le contenu du DOM
		var _location = document.location.href.replace((document.location.hash|| "#"), "");
		if (_url == _location)
		{
			return;
		}

		// Chargement du contenu
		driver.addClass(_content, "loading");
		params["startDate"] = new Date();
		
		// Insertion et affichage du contenu
		if (_data)
		{
			_this.setContent(_content, params);
			return false;
		}
		
		driver.ajaxRequest(
		{
			"url": _url,
			"success": function(response)
			{
				params["data"] = response.responseText;
				_this.setContent(_content, params);
			}
		});

		return;
	}
};

/*
 * Function _askForXFBMLParsing
 * Permet d' s'inscrire pour un reparsing de FBML
 * cette methode est safe pour ne s'executer qu'une seule fois si elle est demandée plusieurs fois
 */
var _askForXFBMLParsing = function(id)
{       
	
    if(typeof id === "undefined" || typeof FB == "undefined"){
        _trace('_askForXFBMLParsing doit cibler id');
    }else{
        FB.XFBML.parse(document.getElementById(id)); 
    }
};
/*

Validator AJAX
CALL AND DISPLAY ERROR MESSAGE

form (DOM)	-	Form to validate
*/
var AJAXValidation = function(form){
    
	this.init(form);
	return this;
};
AJAXValidation.prototype = 
{	
	// Vars
	form:null,
	fields:null,
	url:null,
	progress:false,

	// Constructor
	init:function(form){
		
		// Store vars
		var	_this = this;
		this.form = form;
		this.fields = driver.find(form,".field");
		this.url = form.getAttribute("action");

		// Event
		driver.addEvent(form,"submit",function(e){
			
			e.preventDefault();

			// Prevent multiple call
			if(!_this.progress){
				_this.progress = true;
				_this.call();
			}
		});
	},

	// Call
	call:function(){
		
		var _this = this;

		// AJAX
		driver.ajaxRequest({
			url:_this.url,
			type:"post",
			data:driver.serialize(_this.form),
			success:function(response){ 
				
                        // Allow new call
                            _this.progress = false;

                            var	JSON = response.responseJSON;

                            // If success
                            if(JSON.success){                                
                                _this.success();    
                            }
                            // If has errors
                            else if(JSON.errors.length > 0){                             
                                _this.errors(JSON.errors);
                            } 

			}
		});
		
	},

	// Success
	success:function(){
		
		return this;
	},

	// Errors
	errors:function(errors){
	
		var _this = this;

		// Add error class and display message
		for(var i=0; i<errors.length; i++){

			var	field = document.getElementById(errors[i].id).parentNode;
			driver.addClass(field,"error");
			
			// Create message box
			if(!field.message)
			{
				var message = document.createElement("small");
				message.className = "errormsg";
				message.innerHTML = errors[i].message;
				field.appendChild(message);
				field.message = message;

				// Event (clean)
				driver.addEvent(field,"click",function(){
					// Clean field
					_this.clean([this]);
				});
			}
		}

	},
	
	// Clean previous validation
	clean:function(fields)
	{
		// Remove error Class on each field
		for(var i=0; i<fields.length; i++){
			
			var	field = fields[i];
			driver.removeClass(field,"error");
			
			var tmp = field.message || null;
			if (tmp)
			{
				field.removeChild(tmp);
				delete field.message;
			}
		}
	}

};

/*

SyncFields
SYNCHRONIZE FIELDS

from (DOM)	-	Field that call synchronization
to (DOM)	-	Field to be updated

*/

// FIXME : ce script est un doublon
// un plugin de prototype est déjà chargé pour gérer ce genre de sujet
var SyncFields = function(from,to){
	this.init(from,to);
	return this;
};
SyncFields.prototype = {
	
	// Vars
	from:null,
	to:null,
	url:null,
	progress:false,

	// Constructor
	init:function(from,to){
		
		// Store vars
		var _this = this;
		_this.from = from;
		_this.to = to;
		_this.url = from.getAttribute("data-sync");

		// Event
		driver.addEvent(from,"change",function(){
			// Prevent pultiple call
			if(!_this.progress){
				_this.progress = true;
				_this.call();
			}
		});

	},

	// Call
	call:function(){
		
		var	_this = this,
			datas = this.from.id+"="+this.from.value;

		// AJAX
		driver.ajaxRequest({
			url:_this.url,
			type:"post",
			data:datas,
			success:function(response){ 
				var	JSON = response.responseJSON;
				// If success
				if(JSON.success){
					_this.update(JSON.list);
				}

				// Allow new call
				_this.progress = false;
			}
		});

	},

	// Update
	// entries (Array of Object)	-	Couples of value / label
	update:function(entries){
		
		// Empty targeted field and fill with new data
		var	field = this.to,
			tag = field.tagName.toLowerCase();

		switch(tag){
			case "select":
				
				// If empty
				if(entries.length == 0){
					
					// Disable
					field.setAttribute("disabled","disabled");
					driver.putHTML(field,"<option value=\"null\">&nbsp;</option>");

				} else {
					
					// Enable
					field.removeAttribute("disabled");

					// Update with received entries
					var	options = "";
					for(var i=0; i<entries.length; i++){
						options += "<option value=\""+entries[i].value+"\">"+entries[i].label+"</option>";
					}
					driver.putHTML(field,options);
					
				}

			break;
		}

	}

};

/*
 * Placement for shop menu
 */
// FIXME : pas besoin de script pour placer les éléments
/*
var placeShopMenu = function(){
    var articleInfos    = $('article-content'),
        shopMenu        = $('select-choice-cart');
        
    function init(){
        var calc = articleInfos.cumulativeOffset()[0] - shopMenu.cumulativeOffset()[0] - shopMenu.getWidth();
        shopMenu.style.marginRight = calc > 0 ? calc : 0;
    }
    
    init();
};
*/

/*
 * Menu Gauche du site
 */
var menuPage = function(){};
menuPage.prototype =
{
	"elements":
	{
		"container": null,
		"content": null
	},
	"animation": null,
	"animate": function(isActive)
	{
		var
			_this = this,
			_delay = 400,
			_isActive = (typeof isActive != "undefined") ? isActive : !this.isActive,
			_height = (_isActive) ? 230 : 290,
			_opacity = (_isActive) ? "0" : "1"
		;

		this.isActive = _isActive;
		
		this.onstart();

		if (this.animation)
		{
			driver.deleteAnimate(this.elm, this.animation);
		}
		
		this.animation = driver.animateCSS(this.elm, {"height" : _height + "px", "opacity": _opacity}, _delay, function()
		{
			_this.onsuccess.call(_this);
		});

	},
	"onstart": function()
	{
		//this.elm.style.visibility = "visible";
	},
	"onsuccess": function()
	{
		//this.elm.style.visibility = (this.isActive) ? "hidden" : "visible";
	},
	"init": function (element)
	{
		if (typeof element == "undefined" || !element)
		{
			return false;
		}
		
		this.elm = element;
		this.height = this.elm.offsetHeight;

		// Comportement du logo
		var _logoElement = this.elm.parentNode || null;
		if (_logoElement && typeof menuBrand != "undefined")
		{
			driver.addClass(_logoElement, "menuPage-container");
			driver.addEvent(_logoElement, "mouseover", function(e)
			{
				if(document.getElementsByClassName("homeBrand").length == 0) menuBrand.animate(false);
			});
			driver.addEvent(_logoElement, "mouseout", function(e)
			{
				if(document.getElementsByClassName("homeBrand").length == 0) menuBrand.animate(true);
			});
		}
	}
};


/*
 * Composant fakeSelect
 * Simule un element "select" pour faciliter le design du champs
 * Met à jour le champ associé
 */
var selectElement = function(params)
{
	driver.extend(this, params);
	_setAbstract.call(this,
	{
		"init": function(elm)
		{
			if (typeof elm == "undefined" || !elm)
			{
				return false;
			}

			// Sauvegarde de l'instance
			if (typeof selectElements == "undefined")
			{
				selectElements = {};
			}
			
			var _id = elm.id + "-fake";
			if (typeof selectElements[_id] != "undefined")
			{
				this.destroy(selectElements[_id]);
			}
			selectElements[_id] = this;
			
			var 
				container = elm.parentNode,
				content = this.createElement(container, elm)
			;
			
			driver.addClass(container, "selectElement-container");
			
			// Créer l'élément
			if (!content)
			{
				return false;
			}

			this.selectElm = elm;
			this.container = container;
			this.content = content;
			this.selectItem(this.selectedItem);	
			
			//
			// FIXME : gérer la position du selectBox dans la fenêtre
			// Ce sujet est actuellement géré en dur :
			// ajout de la class "topright-layout" au container pour positionner le sens d'ouverture du contenu
			//
			
			// Afficher/masquer les résultats 
			// Gestion des événements		
			var _this = this;
			
			content.tabIndex = "1";
			driver.addEvent(content, "mouseover", function(e)
			{
				_this.isHover = true;
			});
			driver.addEvent(content, "mouseout", function(e)
			{
				_this.isHover = false;
			});
			
			driver.addEvent(content, "click", function(e)
			{
				// Force le blur
				if (_this.active)
				{
					this.blur();
					return;
				}
				
				// Focus naturel
				this.focus();
				_this.handleActive.call(_this, !_this.active, true);
				return;
			});
			driver.addEvent(content, "blur", function(e)
			{
				setTimeout(function()
				{
					_this.handleActive.call(_this, false);
					
				}, 100);
			});
			this.initialized = true;

			//
			// FIXME : gérer les événement keyPress/keyUp
			//
			/*
			driver.addEvent(content, "keydown", function(e)
			{
				switch(e.keyCode) 
				{
			        case 38: //up arrow  
			        	_trace("Select NextItem")
			        	
			            break;
			        
			        case 40: //down arrow
			        	_trace("Select PrevItem")
			            break;
			            
			        case 27: // escape
			        	_trace("Fermer le select")
			            break;
			    
			        case 13: //enter
			        	_trace("Update la valeur"")
			            break;
			        case 9: // tab <= Problème avec les pseudos qui ne sont pas encore dans la base.
			        	//_trace("idem que keyDown")
			            break;
			    }

			});
			
			driver.addEvent(content, "keyup", function(e)
			{
			});*/
		},
		"destroy": function(elm)
		{
			var _oldContent = elm.content;
			if (_oldContent)
			{
				_oldContent.parentNode.removeChild(_oldContent);
			}
			delete elm;
			this.initialized = false;
			return true;
		}
	}, params);
	return this;
};
selectElement.prototype = 
{
	"container": null,
	"selectElm": null,
	"selectedItem": null,

	"destroy": function(elm){},
	
	"onchange": function(params)
	{
		if (this.selectedItem && this.selectedItem.href)
		{
			if(this.selectedItem.getAttribute("data-ajax") == null)
			{
				document.location.href = this.selectedItem.href;
			}
		}
	},
	
	"getSelectedIndex": function(elm)
	{
		return (elm || this.selectedItem).getAttribute("data-index");
	},
	
	"selectItem": function(elm)
	{
		var 
			_oldElm = this.selectedItem || null,
			_elm = elm || null,
			_className = "selected",
			_this = this
		;
		if (!_elm || _elm == _oldElm)
		{
			return false;
		}
		
		// Update Component
		driver.removeClass(_oldElm, _className);
		elm.className = _className;
		this.selectedItem = _elm;

		// Update Form
		var 
			_oldIndex = this.selectElm.selectedIndex,
			_newIndex = this.getSelectedIndex(),
			_onchange = this.selectElm.onchange || this.onchange
		;
		
		if (_oldIndex != _newIndex)
		{
			// Update Select Value
			_this.selectElm.selectedIndex = _newIndex;
			
			// Change Callback
			try
			{
				driver.triggerEvent(_this.selectElm, "change");
			}
			catch(e){};
			
			_onchange.call(this, {"target": this.selectElm, "type": "change"});
		}
		return false;
	},
	
	"handleActive": function(value, clickEvent)
	{
		var
			elm = this.container, 
			_content = this.content, 
			className = "active"
		;
		
		if(clickEvent)
		{
			this.isHover = false;
		}
		
		// Afficher
		if (value)
		{
			this.active = true;
			driver.addClass(elm, className);
			
			var
				_coords = _content.cumulativeOffset() || [0, 0],
				_height = _coords[1] + _content.offsetHeight,
				_width = _coords[0] + _content.offsetWidth,
				_pasTop = (document.body.clientHeight-30) - _height,
				_pasLeft = (document.body.clientWidth-30) - _width
			;
			
			// Décaler vers le haut	
			if (_pasTop < 0)
			{
				driver.addClass(elm, "bottom-layout");
			}
			// Décaler sur la droite		
			if (_pasLeft < 0)
			{
				driver.addClass(elm, "right-layout");
			}			
			return true;
		}
		
		// Masquer
		if (!this.isHover || !value)
		{
			this.active = false;
			driver.removeClass(elm, className);
			driver.removeClass(elm, "bottom-layout");
			driver.removeClass(elm, "right-layout");	
			return false;
		}
		
		return;
	},

	"createElement" : function(container, elm)
	{
		var 
			_this = this,
			_defaultItem = driver.getElement(elm, ".selected"),
			_className = "selected",
			
			_isCreated = (typeof elm != "string") ? (elm.tagName.toLowerCase() == "ul") : false,
			_children = (!_isCreated) ? elm.getElementsByTagName("option") : elm.getElementsByTagName("a"),
			_links = (_isCreated) ? _children : [],
			_elm0 = (!_isCreated) ? document.createElement("ul") : elm
		;

		if (!_children.length)
		{
			return false;
		}
		
		// Le container doit avoir la même taille que son contenu
		// Si le container à la classe : topright-layout, alors "elm" est en position "absolute"
		container.style.width = elm.offsetWidth + "px";
		container.style.height = elm.offsetHeight + "px";

		for(var i=0, len=_children.length; i<len; i++)
		{
			var _child = _children[i], _item, _link;
			
			if (_isCreated)
			{
				_link = _child;
			}
			else
			{
				_link = document.createElement("a");
				_item = document.createElement("li");
				_link.appendChild(document.createTextNode(_child.textContent || _child.innerText));
				_item.appendChild(_link);
				_elm0.appendChild(_item);
				_links.push(_link);
			}
			
			_link.setAttribute("data-index", i);

			// Afficher le menu
			driver.addEvent(_link, "click", function(e)
			{
				e.preventDefault();
				_this.selectItem(this);
			});
		}
		
		_this.links = _links;
		
		if (!_isCreated)
		{
			container.insertBefore(_elm0, elm);	
			
			// Sélectionner la valeur par défaut
			var _links = _elm0.getElementsByTagName("a");
			_defaultItem = _links[elm.selectedIndex] || null;
			driver.addClass(_defaultItem, "selected");
			
			// Mettre à jour la liste
			driver.addEvent(elm, "change", function(e)
			{
				var 
					_oldLink = driver.getElement(_this.container, ".selected"),
					_newLink = _this.links[this.selectedIndex]
				;
				driver.removeClass(_oldLink, "selected");
				driver.addClass(_newLink, "selected");
			});
		}
		
		
		// Item par défaut
		this.selectedItem = _defaultItem;
		
		return _elm0;
	},
	
	"init": function(elm){}
};

function setCookie(c_name,value)
{
    var c_value=escape(value);
    document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name)
{
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++)
    {
        x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
        y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
        x=x.replace(/^\s+|\s+$/g,"");
        if (x==c_name)
        {
            return unescape(y);
        }
    }
    return false;
}

// Menu déroulant sous IE
var _handleElementsHover = function(elm)
{
	if (!driver.hasClass(document.getElementsByTagName("body")[0], "msie7"))
	{
		_trace("_handleElementsHover : Browser is not IE7 ou older", elm);
		return false;
	}
	if (typeof elm == "undefined" || !elm)
	{
		_trace("_handleElementsHover : 'elm' is undefined", elm);
		return false;
	}

	var 
		_submenuElements = driver.find(elm, ".submenu-container"),
		_className = "hover"
	;
	
	for(var i=0, len=_submenuElements.length; i<len; i++)
	{
		var 
			_elm = _submenuElements[i],
			_isInitialized = _elm.hoverInitialized || false,
			_menu = driver.getElement(_elm, ".submenu-item")
		;
		if (!_isInitialized)
		{
			_elm.hoverInitialized = true;
			
			_elm._hover = false;
			driver.addEvent(_elm, "mouseover", function()
			{
				if (!this._hover)
				{
					this._hover = true;
					driver.addClass(this, _className);
				}
			});
			driver.addEvent(_menu, "mouseover", function()
			{
				_elm._hover = true;
			});
			driver.addEvent(_elm, "mouseout", function()
			{
				_elm._hover = false;
				var _this = this;
				setTimeout(function()
				{
					if (!_this._hover && driver.hasClass(_this, _className))
					{
						driver.removeClass(_this, _className);
					}
				}, 500);
			});
		}
	}
};

var SimpleGallery = function(data)
{
	this.data = data;
	this.id = -1;
	this.init();
};
SimpleGallery.prototype = 
{
	"init": function()
	{
		var container = document.getElementById('simpleGal'),
			i,
			str = '<img id="simpleGalImg" />'+
				  '<nav role="navigation">'+
					'<ul class="more-views menu-container">';
			
		for (i=this.data.imgs.length-1;i>=0;i--) {
			str += '<li class="menu-item"><a href="#0" data-slide="'+i+'"><span>'+i+'</span></a></li>';
		}		
		str += '</ul></nav>';		
		
		container.innerHTML = str;
		
		var link = container.getElementsByTagName('a');
		for (i=link.length-1;i>=0;i--) {
			driver.addEvent(link[i], 'click', this.change.bind(this,i) );
		}
		
		this.change(0);
		
	},
	
	"change": function(id,e) {
		document.getElementById('simpleGalImg').setAttribute('src', this.data.imgs[id].url );
		var a = document.getElementById('simpleGal').getElementsByTagName('a');
		driver.addClass(a[id], 'active');
		if (this.id!=-1) {
			driver.removeClass(a[this.id], 'active');
		}
		this.id = id;
	}
	
};

function openShare(url) {
	window.open(url, 'sharer', 'toolbar=0, status=0, width=630, height=540');
	return false;
}

function frenchkissChooseProduct (fragID,lang) {
	driver.ajaxRequest({
		url:'/brand/'+lang.toLowerCase()+'/cross/'+fragID, 
		type:"get",
		success:function(response){
			var cross = driver.getElements('.menu-previous .cross'),
				i;
			for (i=cross.length-1;i>=0;i--) {
				cross[i].innerHTML = response.responseText;
			}
			
		}
	});
}
