/* jquery set_windowed */
;(function($j){
	var enabled = ($j.browser.msie && $j.browser.version == "6.0");
	
	$j.fn.extend({
		setWindowed: function(){
			if (enabled) {
				this.each(function(){
					if(this._topElementFrame){
						$j(this).reposWindowed()[0]._topElementFrame.show();
					}
					else {
						this._topElementFrame = $j('<iframe src="javascript:\'<html></html>\';" scrolling="no" frameborder="0"></iframe>').hide().insertAfter(this);
						$j(this).reposWindowed();
						this._topElementFrame.show();
					}
				});
			}
			return this;
		},
		unsetWindowed: function(){
			if (enabled) {
				this.each(function(){
					if(this._topElementFrame)
						this._topElementFrame.hide();
				});
			}
			return this;
		},
		reposWindowed: function(){
			if (enabled) {
				this.each(function(){
					if(this._topElementFrame){
						var cur_elmt = $j(this);
						this._topElementFrame.css({
							position: cur_elmt.css("position"),
							zIndex: "0",
							top: cur_elmt.css("top"),
							right: cur_elmt.css("right"),
							bottom: cur_elmt.css("bottom"),
							left: cur_elmt.css("left"),
							width: cur_elmt.outerWidth() + "px",
							height: cur_elmt.outerHeight() + "px",
							marginTop: cur_elmt.css("marginTop"),
							marginRight: cur_elmt.css("marginRight"),
							marginBottom: cur_elmt.css("marginBottom"),
							marginLeft: cur_elmt.css("marginLeft"),
							border: "0"
						});
					}
				});
			}
			return this;
		}
	});
})(jQuery);

/* Misc scripts (maybe not used at all) */
function openL(link) {
    TextPopUp = window.open(link, "remotewindow", 'toolbar=0,location=0,directories=0,status=no,menubar=no,scrollbars=1,resizable=0,width=435,height=200,left=300,top=30', "mainwindow")
}

function openW(link) {
    TextPopUp = window.open(link, "remotewindow", 'toolbar=0,location=0,directories=0,status=no,menubar=no,scrollbars=1,resizable=0,width=450,height=320,left=300,top=30', "mainwindow")
}

function openY(link) {
    TextPopUp = window.open(link, "remotewindow", 'toolbar=0,location=0,directories=0,status=no,menubar=no,scrollbars=1,resizable=0,width=650,height=530,left=0,top=0', "mainwindow")
}

function openB(link) {
    TextPopUp = window.open(link, "remotewindow", 'toolbar=0,location=0,directories=0,status=no,menubar=no,scrollbars=1,resizable=1,width=650,height=550,left=0,top=0', "mainwindow")
}

function openZ(link) {
    TextPopUp = window.open(link, "remotewindow", 'toolbar=0,location=0,directories=0,status=no,menubar=no,scrollbars=1,resizable=0,width=320,height=180,left=480,top=0', "mainwindow")
}

function openA(link) {
    TextPopUp = window.open(link, "remotewindow", 'toolbar=0,location=0,directories=0,status=no,menubar=no,scrollbars=1,resizable=1,width=600,height=500,left=10,top=0', "mainwindow")
}

function openA(link) {
    TextPopUp = window.open(link, "remotewindow", 'toolbar=0,location=0,directories=0,status=no,menubar=no,scrollbars=1,resizable=1,width=580,height=300,left=10,top=0', "mainwindow")
}

function openV(link) {
    TextPopUp = window.open(link, "remotewindow", 'toolbar=0,location=0,directories=0,status=no,menubar=no,scrollbars=1,resizable=1,width=250,height=450,left=500,top=0', "mainwindow")
}

function openT(link) {
    TextPopUp = window.open(link, "remotewindow", 'toolbar=0,location=0,directories=0,status=no,menubar=yes,scrollbars=1,resizable=1,width=250,height=450,left=500,top=0', "mainwindow")
}

function openO(link) {
    TextPopUp = window.open(link, "remotewindow", 'toolbar=0,location=0,directories=0,status=no,menubar=no,scrollbars=1,resizable=0,width=580,height=300,left=300,top=30', "mainwindow")
}

function Search_hideIt(layer) {
    if (document.getElementById) {
        document.getElementById(layer).style.display = "none"
    } else if (document.all) {
        document.all[layer].style.display = "none"
    } else if (document.layers) {
        document.layers[layer].display = "none"
    }
}

function Search_showIt(layer) {
    if (document.getElementById) {
        document.getElementById(layer).style.display = "inline"
    } else if (document.all) {
        document.all[layer].style.display = "inline"
    } else if (document.layers) {
        document.layers[layer].display = "inline"
    }
}

function Search_viewSelect(box, layer) {
    if (box.value == "15") {
        Search_showIt(layer)
    } else {
        Search_hideIt(layer)
    }
}

function showFlux() {
    var disPlay = document.getElementById("flux").style.display;
    if (disPlay == 'none') {
        document.getElementById("flux").style.display = '';
        document.getElementById("fluxoff").style.display = 'none'
    } else if (disPlay != 'none') {
        document.getElementById("flux").style.display = 'none';
        document.getElementById("fluxoff").style.display = ''
    }
}

function jlink(url) {
    document.location.href = url;
    return true
}

function AC_AddExtension(src, ext) {
    if (src.indexOf('?') != -1) return src.replace(/\?/, ext + '?');
    else return src + ext
}

function AC_Generateobj(objAttrs, params, embedAttrs) {
    var str = '<object ';
    for (var i in objAttrs) str += i + '="' + objAttrs[i] + '" ';
    str += '>';
    for (var i in params) str += '<param name="' + i + '" value="' + params[i] + '" /> ';
    str += '<embed ';
    for (var i in embedAttrs) str += i + '="' + embedAttrs[i] + '" ';
    str += ' ></embed></object>';
    document.write(str)
}

function AC_FL_RunContent() {
    var ret = AC_GetArgs(arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000", "application/x-shockwave-flash");
    AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs)
}

function AC_SW_RunContent() {
    var ret = AC_GetArgs(arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000", null);
    AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs)
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType) {
    var ret = new Object();
    ret.embedAttrs = new Object();
    ret.params = new Object();
    ret.objAttrs = new Object();
    for (var i = 0; i < args.length; i = i + 2) {
        var currArg = args[i].toLowerCase();
        switch (currArg) {
        case "classid":
            break;
        case "pluginspage":
            ret.embedAttrs[args[i]] = args[i + 1];
            break;
        case "src":
        case "movie":
            args[i + 1] = AC_AddExtension(args[i + 1], ext);
            ret.embedAttrs["src"] = args[i + 1];
            ret.params[srcParamName] = args[i + 1];
            break;
        case "onafterupdate":
        case "onbeforeupdate":
        case "onblur":
        case "oncellchange":
        case "onclick":
        case "ondblClick":
        case "ondrag":
        case "ondragend":
        case "ondragenter":
        case "ondragleave":
        case "ondragover":
        case "ondrop":
        case "onfinish":
        case "onfocus":
        case "onhelp":
        case "onmousedown":
        case "onmouseup":
        case "onmouseover":
        case "onmousemove":
        case "onmouseout":
        case "onkeypress":
        case "onkeydown":
        case "onkeyup":
        case "onload":
        case "onlosecapture":
        case "onpropertychange":
        case "onreadystatechange":
        case "onrowsdelete":
        case "onrowenter":
        case "onrowexit":
        case "onrowsinserted":
        case "onstart":
        case "onscroll":
        case "onbeforeeditfocus":
        case "onactivate":
        case "onbeforedeactivate":
        case "ondeactivate":
        case "type":
        case "codebase":
            ret.objAttrs[args[i]] = args[i + 1];
            break;
        case "width":
        case "height":
        case "align":
        case "vspace":
        case "hspace":
        case "class":
        case "title":
        case "accesskey":
        case "name":
        case "id":
        case "tabindex":
            ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i + 1];
            break;
        default:
            ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i + 1]
        }
    }
    ret.objAttrs["classid"] = classid;
    if (mimeType) ret.embedAttrs["type"] = mimeType;
    return ret
}

function _goto() {
    var u = "";
    var i = 0;
    if (!document.cookie || document.cookie.length > 0) {
        for (i = arguments.length - 1; i > 0; i--) {
            u += arguments[i].toString();
        }
        window.location.href = u.replace(/\|/g, '/').replace(/@/g, '.');
    }
};;

/* hrefizer & purchasePopIn */
(function ($) {
    $.hrefizer = function () {
        $j("a[data-url]").bind("mouseover focus", function f() {
            var j = $(this);
            j.attr("href", j.attr("data-url").split(",").reverse().join("").replace(/\|/g, "/").replace(/@/g, ".")).unbind("mouseover focus", f);
            j.removeAttr("data-url");
        }).attr("tabindex", "0");
    };
    initPurchasePopIn = function () {
        var jOverlay = $j("#TB_overlay");
        if (jOverlay.length < 1) {
            jOverlay = $j('<div id="TB_overlay" class="TB_overlayBG TB_dark"></div>').appendTo("body");
        }
        var jPurchaseTooltip = $j("#action-cart").addClass("js").appendTo("body");
        var jContinueShop = jPurchaseTooltip.find("ul.actions a.button-continue");
        if ($j.browser.msie && $j.browser.version == 6) {
            $j("select").hide();
        }
        jPurchaseTooltip.fadeIn(200);
        var sPurchaseTooltipHeight = jPurchaseTooltip.outerHeight();
        jPurchaseTooltip.css({
            marginTop: (-(sPurchaseTooltipHeight / 2)) + "px"
        })
        jOverlay.bind("remove.overlay", function () {
            jOverlay.fadeOut(300, function () {
                jOverlay.remove();
            });
            if ($j.browser.msie && $j.browser.version == 6) {
                $j("select").show();
            }
        });
        jContinueShop.click(function (e) {
            e.preventDefault();
            jPurchaseTooltip.hide();
            jOverlay.trigger("remove.overlay");
        });
    };
})(jQuery);

/* jquery simpletooltip */
(function ($j) {
    $j.viewportHeight = function () {
        return self.innerHeight || jQuery.boxModel && document.documentElement.clientHeight || document.body.clientHeight;
    };
    $j.fn.simpletooltip = function (options) {
        var all_tooltips = [];
        var openTooltip = function (e) {
            e.preventDefault();
            var tooltipE = e.data.tooltipE;
            var tooltip = e.data.tooltip;
            var hideDelay = e.data.hideDelay;
            var hideOnMouseOut = e.data.hideOnMouseOut;
            var winWidth = $j(window).width();
            var winHeight = $j(window).height();
            var winYViewLimit = (window.pageYOffset || document.documentElement.scrollTop) + $j.viewportHeight();
            if (tooltipE._effect && (tooltipE._effect == "fadeIn" || tooltipE._effect == "slideDown" || tooltipE._effect == "show")) {
                window.eval("tooltip." + tooltipE._effect + "('fast')");
            }
            else {
                tooltip.show();
            }
            if (!tooltipE._width) {
                tooltipE._width = tooltip.width();
                tooltipE._height = tooltip.height();
            }
            var tPosX = e.pageX - (tooltipE._width / 2);
            var tPosY = e.pageY - (tooltipE._height / 2);
            if (tPosX < 0) {
                tPosX = tooltipE._margin;
            }
            else if (tPosX + tooltipE._width > winWidth) {
                tPosX = winWidth - tooltipE._width - tooltipE._margin;
            }
            if (tPosY < 0) {
                tPosY = tooltipE._margin;
            }
            else if (tPosY + tooltipE._height > winYViewLimit) {
                tPosY = winYViewLimit - tooltipE._height - tooltipE._margin;
            }
            var timer = new Number();
            tooltip.css({
                "left": tPosX + "px",
                "top": tPosY + "px",
                "cursor": "help"
            });
            if (hideOnMouseOut) {
                tooltip.hover(function () {
                    window.clearTimeout(timer);
                }, function () {
                    timer = window.setTimeout(function () {
                        tooltip.hide();
                    }, hideDelay * 1000);
                });
            }
        };
        this.each(function () {
            var currentHref = $j(this).attr("href");
            if (currentHref && currentHref.match(/^#.+/)) {
                var tooltip = $j(currentHref);
                if (tooltip.length > 0) {
                    var tooltipE = tooltip.get(0);
                    if (!tooltipE._tooltipInit) {
                        all_tooltips.push(tooltipE);
                        if (options && options.margin) {
                            tooltipE._margin = options.margin;
                        }
                        else {
                            tooltipE._margin = 5;
                        }
                        if (options && options.effect) {
                            tooltipE._effect = options.effect;
                        }
                        else {
                            tooltipE._effect = false;
                        }
                        tooltip.find("a[href^=#][rel=close]").click(function (e) {
                            e.preventDefault();
                            tooltip.hide();
                        });
                        tooltipE._tooltipInit = true;
                    }
                    if (options && options.hideOnMouseOut != null) {
                        var hideOnMouseOut = options.hideOnMouseOut;
                    }
                    else {
                        var hideOnMouseOut = true;
                    }
                    if (options && options.click) {
                        var showEvent = "click";
                    }
                    else {
                        var showEvent = "mouseover";
                    }
                    if (options && options.hideDelay && options.hideDelay > 0) {
                        var hideDelay = options.hideDelay;
                    }
                    else {
                        var hideDelay = 0;
                    }
                    $j(this).bind(showEvent, {
                        "tooltipE": tooltipE,
                        "tooltip": tooltip,
                        "hideDelay": hideDelay,
                        "hideOnMouseOut": hideOnMouseOut
                    }, openTooltip);
                }
            }
        });
        $j(all_tooltips).appendTo("body").css({
            "position": "absolute",
            "zIndex": "9999",
            "display": "none"
        });
        return this;
    };
})(jQuery);

;(function($){
	$.unobtrusivelib = function (enabled_modules) {
		
		var modules = {
			popup: function () {
				$("a[rel^=popup]").each(function (i) {
					var popupName = 'popup_' + i + '_' + new Date().getTime();
					
					$(this).click(function (e) {
						e.preventDefault();
						var dims = this.getAttribute('rel').match(/.*\[([0-9]+)-([0-9]+)\].*/);
						window.open(this.getAttribute('href'), popupName, 'width=' + dims[1] + ',height=' + dims[2] + ',resizable,scrollbars');
					});
				});
			},
			
			external: function () {
				$("a[rel~=external]").each(function(){
					var jExtLink = $(this); 
					if ( jExtLink.children().is('img')) { 
						jExtLink.addClass("prevent-ext-icon");
					}
				});
				$("a[rel~=external]").click(function(e){
					e.preventDefault();
					window.open(this.href);
				});
			},
			
			maxLength: function () {
				$("textarea[maxlength]").each(function(){
					var jThis = $(this);
					var sMaxLimit = jThis.attr("maxlength")-0;
					
					if (jThis.hasClass("counter")) {
						var jCount = $('<span class="counter">' + sMaxLimit + '</span>');
						jThis.after(jCount);
						
						var charCount = sMaxLimit - jThis.val().length;
						jCount.text(charCount);
					}
					
					jThis.keyup(function(e) {
						var charCount = sMaxLimit - jThis.val().length;
						if ( charCount < 1 ) {
							jThis.val( jThis.val().slice(0, sMaxLimit) );
						}
						if ( !!jCount ) {
							jCount.text(charCount);
						}
					});
					
				});
			},
			
			autoClearInput: function () {
				
				var defaultClass = "autoclear-default";
				
				$("input.autoclear:text, input.autoclear:password, textarea.autoclear").each(function(){
					
					var $this = $(this);
					
					if ($this.is(":password") && !$.browser.msie) {
						
						var $original = $this;
						
						$this = $this.clone().attr("type", "text").removeAttr("name");
						$original.after($this).hide();
						
						$this.focus(function(){
							$this.hide();
							$original.show().focus();
						});
						
						if ( $this.val() == this.defaultValue ) {
							$this.addClass(defaultClass);
						}
						
						$original
						.focus(function () {
							if ( this.defaultValue == $original.val() ) {
								$original.removeClass(defaultClass).val("");
							}
						})
						.blur(function () {
							if ( $original.val() == "" ) {
								$original.hide();
								$this.show().addClass(defaultClass).val( this.defaultValue );
							}
						});
							
					} else {
						
						if ( $this.val() == this.defaultValue ) {
							$this.addClass(defaultClass);
						}
						
						$this
						.focus(function () {
							if ( this.defaultValue == $this.val() ) {
								$this.removeClass(defaultClass).val("");
							}
						})
						.blur(function () {
							if ( $this.val() == "" ) {
								$this.addClass(defaultClass).val( this.defaultValue );
							}
						});
					}
					
				});
			},
			
			autoFocusInput: function () {
				var focusElmts = $("input.autofocus");
				if (focusElmts.length != 0){
					focusElmts.get(0).focus();
				}
			}
		};
		
		if (!!enabled_modules) {
			$.each(enabled_modules,function(i,n){
				if(modules[n]){
					modules[n]();
				}
			});
		}
		else {
			$.each(modules,function(i,n){n();});
		}
		
	};
})(jQuery);

$j(function(){
	$j.unobtrusivelib(["popup", "external", "maxLength", "autoClearInput", "autoFocusInput"]);
});

/* simpleacc */
(function($j){
	$j.fn.simpleacc = function(options){
		
		var opts = $j.extend({
            open: false
        }, options);
        
		return this.each(function(){
			var toggleBtn = $j(this);
			
            toggleBtn.css("cursor", "pointer")
			.click(function(e){
                e.preventDefault();
				if(toggleBtn.next().is(":visible")){
					toggleBtn.next().slideUp(function(){toggleBtn.removeClass("selected")});
				}
				else {
					toggleBtn.next().slideDown(function(){toggleBtn.addClass("selected")});
				}
			})
			.hover( function(){toggleBtn.addClass("hover")}, function(){toggleBtn.removeClass("hover")} )
			.next().hide();
			
			if (opts.open){
				toggleBtn.addClass("selected").next().show();
			}
		});
	};
})(jQuery);

(function($) {
	$.fn.hoverIntent = function(f,g) {
		// default configuration options
		var cfg = {
			sensitivity: 7,
			interval: 100,
			timeout: 0
		};
		// override configuration options with user supplied object
		cfg = $.extend(cfg, g ? { over: f, out: g } : f );

		// instantiate variables
		// cX, cY = current X and Y position of mouse, updated by mousemove event
		// pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
		var cX, cY, pX, pY;

		// A private function for getting mouse position
		var track = function(ev) {
			cX = ev.pageX;
			cY = ev.pageY;
		};

		// A private function for comparing current and previous mouse position
		var compare = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			// compare mouse positions to see if they've crossed the threshold
			if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
				$(ob).unbind("mousemove",track);
				// set hoverIntent state to true (so mouseOut can be called)
				ob.hoverIntent_s = 1;
				return cfg.over.apply(ob,[ev]);
			} else {
				// set previous coordinates for next time
				pX = cX; pY = cY;
				// use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
				ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
			}
		};

		// A private function for delaying the mouseOut function
		var delay = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			ob.hoverIntent_s = 0;
			return cfg.out.apply(ob,[ev]);
		};

		// A private function for handling mouse 'hovering'
		var handleHover = function(e) {
			// next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
			var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
			while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } }
			if ( p == this ) { return false; }

			// copy objects to be passed into t (required for event object to be passed in IE)
			var ev = jQuery.extend({},e);
			var ob = this;

			// cancel hoverIntent timer if it exists
			if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

			// else e.type == "onmouseover"
			if (e.type == "mouseover") {
				// set "previous" X and Y position based on initial entry point
				pX = ev.pageX; pY = ev.pageY;
				// update "current" X and Y position based on mousemove
				$(ob).bind("mousemove",track);
				// start polling interval (self-calling timeout) to compare mouse coordinates over time
				if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

			// else e.type == "onmouseout"
			} else {
				// unbind expensive mousemove event
				$(ob).unbind("mousemove",track);
				// if hoverIntent state is true, then call the mouseOut function after the specified delay
				if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
			}
		};

		// bind the function to the two event listeners
		return this.mouseover(handleHover).mouseout(handleHover);
	};
})(jQuery);

/* jQuery SuperBox! 0.9.2-dev */
;(function($) {
	// Local variables
	var $curLink, $overlay, $wrapper, $caption, $container, $superbox, $closeBtn, $loading, $nextprev, $nextBtn, $prevBtn, settings,
	
	// Default settings
	defaultSettings = {
		boxId: "superbox",
		boxClasses: "",
		overlayOpacity: .8,
		boxWidth: "600",
		boxHeight: "400",
		loadTxt: "Loading...",
		closeTxt: "Close",
		prevTxt: "Previous",
		nextTxt: "Next",
		beforeOpen: function(){},
		afterOpen: function(){}
	},
	
	galleryGroups = {},
	galleryMode = false,
	hideElts = $([]),
	isWaiting = false;
	
	// Init dispatcher
	$.superbox = function() {
		
		// Settings
		settings = $.extend({}, defaultSettings, $.superbox.settings);
		
		// If IE6, select elements to hide
		if ($.browser.msie && $.browser.version < 7) {
			hideElts = hideElts.add("select");
		}
		
		// Do not init SuperBox! twice
		if ($.superbox.mainInit !== true) {
			
			// Create base elements
			createElements();
			
			// Init global events (left / right, echap)
			initGlobalEvents();
			
			$.superbox.mainInit = true;
		}
		
		// Dispatch types
		dispatch();
	};
	
	// Dispatch types
	function dispatch() {
		
		// Match all superbox links
		$("a[rel^=superbox],area[rel^=superbox]").each(function() {
			
			// Optimisation
			var $this = $(this),
			relAttr = $this.attr("rel"),
			
			// Match first argument. Ex: superbox[gallery#my_id.my_class][my_gallery] > gallery#my_id.my_class
			firstArg = relAttr.match(/^superbox\[([^\]]+)\]/)[1],
			
			// Match type. Ex: superbox[gallery#my_id.my_class][my_gallery] > gallery
			type = firstArg.match(/^([^#\.]+)/)[1],
			
			// Match additionnal classes or IDs (#xxx.yyy.zzz)
			boxCurrentAttrs = firstArg.replace(type, "").match(/([#\.][^#\.\]]+)/g) || [],
			
			// Box ID and classes
			newBoxId = settings.boxId,
			newBoxClasses = settings.boxClasses;
			
			// Prevent multiple inits
			if ($this.data("superbox_init")) { return; }
			$this.data("superbox_init", true);
			
			// Additionnal rel settings
			this._relSettings = relAttr.replace("superbox["+ type + boxCurrentAttrs.join("") +"]", "");
			
			// Redefine settings
			$.each(boxCurrentAttrs, function(i, val) { // each class or id
				if (val.substr(0,1) == "#") {
					newBoxId = val.substr(1);
					
				} else if (val.substr(0,1) == ".") {
					newBoxClasses += " " + val.substr(1);
				}
			});
			
			// Call type method
			if (type.search(/^image|gallery|iframe|content|ajax$/) != -1) {
				$this.superbox(type, {boxId: newBoxId, boxClasses: newBoxClasses});
			}
		});
	};
	
	/*-- Superbox Method --*/
	$.fn.superbox = function(type, curSettings) {
		curSettings = $.extend({}, settings, curSettings);
		$.superbox[type](this, curSettings);
		
		this.click(function(e) {
			e.preventDefault();
			$curLink = this;
		});
	};
	
	/*-- Types --*/
	$.extend($.superbox, {
		
		// Wait... (loading)
		wait: function(callback) {
			
			isWaiting = true;
			
			prepareBox();
			
			// Loading anim
			initLoading(function() {
				
				// Execute callback after animation
				callback();
			});
		},
		
		// Custom SuperBox!
		open: function(content, curSettings) {
			
			curSettings = $.extend({}, settings, curSettings);
			
			// Launch load animation
			if (!isWaiting) {
				$.superbox.wait(function(){
					$.superbox.open(content, curSettings);
				});
				return;
			}
			
			// Specified dimensions
			$superbox.width( curSettings.boxWidth+"px" );
			$innerbox.height( curSettings.boxHeight+"px" );
			
			// Set Id and Classes
			$superbox.attr("id", curSettings.boxId).attr("class", curSettings.boxClasses);
			
			// Append content
			$(content).appendTo($innerbox);
			
			// Show box
			showBox(curSettings);
			
			// Stop waiting
			isWaiting = false;
		},
		
		// Close SuperBox!
		close: function() {
			hideBox();
			$overlay.fadeOut(300, function() {
				// Show hidden elements for IE6
				hideElts.show();
			});
			galleryMode = false;
		},
		
		// Image
		image: function($elt, curSettings, isGallery) {
			
			// On click event
			$elt.click(function() {
				
				galleryMode = !!isGallery;
				
				$.superbox.wait(function() {
					
					var relSettings = getRelSettings($elt.get(0)),
					dimensions = false;
					
					// Extra settings
					if (!!relSettings) {
						
						var relDimensions;
						
					 	if (galleryMode) {
							relDimensions = relSettings[1];
							
						} else {
							relDimensions = relSettings[0];
						}
						
						if (!!relDimensions) {
							dimensions = relDimensions.split("x");
						}
					}
					
					// Image
					var $curImg = $('<img src="'+ $elt.attr("href") +'" title="'+ ($elt.attr("title") || $elt.text()) +'" />');
					
					
					// On image load
					$curImg.load(function() {
						
						// Image box dimensions
						if (!!dimensions && dimensions[0] != "") {
							var boxWidth = dimensions[0] - 0;
						} else {
							// image width + $innerbox padding
							var boxWidth = $curImg.width() + ($innerbox.css("paddingLeft").slice(0,-2)-0) + ($innerbox.css("paddingRight").slice(0,-2)-0);
						}
						if (!!dimensions && dimensions[1] != "") {
							var boxHeight = dimensions[1] - 0;
						} else {
							var boxHeight = $curImg.height();
						}
						
						curSettings = $.extend({}, curSettings, {
							boxClasses: (galleryMode? "gallery " : "image ") + curSettings.boxClasses,
							boxWidth: boxWidth,
							boxHeight: boxHeight,
							beforeOpen: function() {
								if (galleryMode) {
									// "Prev / Next" buttons
									nextPrev($elt, relSettings[0]);
								}
							}
						});
						
						// Open SuperBox!
						$.superbox.open($curImg, curSettings);
						
					});
					
					// Append image to SuperBox! (to trigger loading)
					$curImg.appendTo($innerbox);
				});
				
			});
		},
		
		// Gallery
		gallery: function($elt, curSettings) {
			
			// Extra settings
			var extraSettings = getRelSettings($elt.get(0));
			
			// Create group
			if(!galleryGroups[extraSettings[0]]) {
				galleryGroups[extraSettings[0]] = [];
			}
			
			// Add element to current group
			galleryGroups[extraSettings[0]].push($elt);
			
			$elt.data("superboxGroupKey", galleryGroups[extraSettings[0]].length - 1);
			
			// Image Box
			$.superbox["image"]($elt, curSettings, true);
		},
		
		// iframe
		iframe: function($elt, curSettings) {
			
			// On click event
			$elt.click(function() {
				
				$.superbox.wait(function() {
					
					// Extra settings
					var extraSettings = getRelSettings($elt.get(0));
					
					// Dimensions
					var dims = false;
					if (extraSettings) {
						dims = extraSettings[0].split("x");
					}
					
					curSettings = $.extend({}, curSettings, {
						boxWidth: dims[0] || curSettings.boxWidth,
						boxHeight: dims[1] || curSettings.boxHeight,
						boxClasses: "iframe " + curSettings.boxClasses
					});
					
					// iframe element
					var $iframe = $('<iframe title="'+ $elt.text() +'" src="'+ $elt.attr("href") +'" name="'+ $elt.attr("href") +'" frameborder="0" scrolling="auto" width="'+ curSettings.boxWidth +'" height="'+ curSettings.boxHeight +'"></iframe>');
					
					// On iframe load
					$iframe.one("load", function() {
						
						// Open SuperBox!
						$.superbox.open($iframe, curSettings);
					});
					
					// Append iframe to SuperBox! (to trigger loading)
					$iframe.appendTo($innerbox);
				});
				
			});
		},
		
		// Content
		content: function($elt, curSettings) {
			
			// On click event
			$elt.click(function() {
				
				$.superbox.wait(function() {
					var elt_href = $elt.attr('href');
					
					curSettings.boxWidth = $(elt_href).width();
					curSettings.boxHeight = $(elt_href).height();
				
					// Extra settings
					var extraSettings = getRelSettings($elt.get(0));
					
					// Dimensions
					var dims = false;
					if (extraSettings) {
						dims = extraSettings[0].split("x");
					}
					
					// Specific settings
					curSettings = $.extend({}, curSettings, {
						boxWidth: dims[0] || curSettings.boxWidth,
						boxHeight: dims[1] || curSettings.boxHeight,
						boxClasses: "content " + curSettings.boxClasses
					});

					// Open SuperBox!
					$.superbox.open($(elt_href).clone(), curSettings);
					$('#' + curSettings.boxId).find(elt_href).show();
				});
				
			});
		},
		
		// Ajax
		ajax: function($elt, curSettings) {
			
			// On click event
			$elt.click(function() {
				
				$.superbox.wait(function() {
					
					// Extra settings
					var extraSettings = getRelSettings($elt.get(0));
					
					// Dimensions
					var dims = false;
					if (extraSettings && extraSettings[1]) {
						dims = extraSettings[1].split("x");
					}
					
					// Extend default dimension settings
					curSettings = $.extend({}, curSettings, {
						boxWidth: dims[0] || curSettings.boxWidth,
						boxHeight: dims[1] || curSettings.boxHeight,
						boxClasses: "ajax " + curSettings.boxClasses
					});
					
					// Get Ajax URL + ID
					var splitUrl = extraSettings[0].split("#");
					var ajaxUrl = splitUrl[0];
					var anchor = splitUrl[1] || false;
					
					$.get( ajaxUrl, function(data) {
						
						// Get a specific element (by ID)?
						if (anchor !== false) {
							data = $(data).find("#" + anchor);
							if (data.length == 0) {
								data = $(data).filter("#" + anchor);
							}
						}
						
						// Open SuperBox!
						$.superbox.open(data, curSettings);
					});
				});
			});
		}
	});
	
	// Get extra settings in rel attribute
	function getRelSettings(elt) {
		return elt._relSettings.match(/([^\[\]]+)/g);
	};
	
	// Next / Previous
	function nextPrev($elt, group) {
		
		$nextprev.show();
		
		galleryMode = true;
		
		var nextKey = $elt.data("superboxGroupKey") + 1,
			prevKey = nextKey - 2;
		
		// Next
		if (galleryGroups[group][nextKey]) {
			$nextBtn.removeClass("disabled").unbind("click").bind("click", function() {
				galleryGroups[group][nextKey].click();
			});
			
		} else {
			$nextBtn.addClass("disabled").unbind("click");
		}
		
		// Prev
		if (galleryGroups[group][prevKey]) {
			$prevBtn.removeClass("disabled").unbind("click").bind("click", function() {
				galleryGroups[group][prevKey].click();
			});
			
		} else {
			$prevBtn.addClass("disabled").unbind("click");
		}
		
		// Keys shortcuts
		$(document)
			.unbind("keydown.superbox_np")
			.bind("keydown.superbox_np", function(e) {
				
				// Left/right arrows
				if (e.keyCode == 39) {
					$nextBtn.click();
				
				} else if (e.keyCode == 37) {
					$prevBtn.click();
				}
			});
	};
	
	// Hide Box
	function hideBox() {
		
		/* creates errors in IE.
		if (!!$curLink) {
			$curLink.focus();
		}*/
		
		$(document).unbind("keydown.spbx_close").unbind("keydown.superbox_np");
		$loading.hide();
		$nextprev.hide();
		$wrapper.hide().css({position: "fixed", top: 0});
		$innerbox.empty().removeAttr("style");;
		$curLink = null;
	};
	
	// "Loading..."
	function initLoading(callback) {
		
		// Keys shortcuts
		$(document)
			.unbind("keydown.spbx_close")
			.bind("keydown.spbx_close",function(e) {
				
				// Escape
				if (e.keyCode == 27) {
					$.superbox.close();
				}
			});
		
		var loading = function() {
			
			// IE6
			if($.browser.msie && $.browser.version < 7) {
				$wrapper.css({position: "absolute", top:"50%"});
			}
			
			// Hide elements for IE6
			hideElts.hide();
			
			$loading.show();
			callback();
		};
		
		if (galleryMode) {
			$overlay.css("opacity", settings.overlayOpacity).show();
			loading();
		}
		else {
			$overlay.css("opacity", 0).show().fadeTo(300, settings.overlayOpacity, loading);
		}
	};
	
	// "Prepare" box : Show $superbox with top:-99999px;
	function prepareBox() {
		$wrapper.show();
		$innerbox.empty();
		$superbox.css({position: "absolute", top: "-99999px"});
	};
	
	// Display box
	function showBox(curSettings) {
		
		curSettings = $.extend({}, settings, curSettings);
		
		// Stop "Loading..."
		$loading.hide();
		
		// Show $superbox
		$superbox.css({position: "static", top: 0, opacity: 0});
		
		// IE6 and IE7
		if ($.browser.msie && $.browser.version < 8) {
			$superbox.css({position: "relative", top:"-50%"});
			
			// IE6
			if ($.browser.msie && $.browser.version < 7) {
				$wrapper.css({position: "absolute", top:"50%"});
			}
		}
		
		// Position absolute if image height > window height
		if ( $(window).height() < $wrapper.height() ) {
			$wrapper.css({position: "absolute", top: ($wrapper.offset().top + 10) + "px"});
		}
		
		curSettings.beforeOpen();
		
		$superbox.fadeTo(300, 1, function(){
			curSettings.afterOpen();
		}).focus();
	};
	
	// Create base elements (overlay, wrapper, box, loading)
	function createElements() {
		
		// Overlay (background)
		$overlay = $('<div id="superbox-overlay"/>').appendTo("body").hide();
		
		// Wrapper
		$wrapper = $('<div id="superbox-wrapper"/>').appendTo("body").hide();
		
		// Box container
		$container = $('<div id="superbox-container"/>').appendTo($wrapper);
		
		// Box
		$superbox = $('<div id="superbox" tabindex="0"/>').appendTo($container);
		
		// Inner box
		$innerbox = $('<div id="superbox-innerbox"/>').appendTo($superbox);
		
		// "Next / Previous"
		$nextprev = $('<p class="nextprev"/>').appendTo($superbox).hide();
		$prevBtn = $('<a class="prev" tabindex="0" role="button"><strong><span>'+ settings.prevTxt +'</span></strong></a>').appendTo($nextprev);
		$nextBtn = $('<a class="next" tabindex="0" role="button"><strong><span>'+ settings.nextTxt +'</span></strong></a>').appendTo($nextprev);
		
		// Add close button
		$closeBtn = $('<p class="close"><a tabindex="0" role="button"><strong><span>'+ settings.closeTxt +'</span></strong></a></p>').prependTo($superbox).find("a");
		
		// "Loading..."
		$loading = $('<p class="loading">'+ settings.loadTxt +'</p>').appendTo($container).hide();
	};
	
	// Init global events : close (echap), keyboard access (focus + enter)
	function initGlobalEvents() {
		// Hide on click
		$overlay.add($wrapper).add($closeBtn).click(function() {
			$.superbox.close();
		});
	
		// Remove "hide on click" on superbox
		$superbox.click(function(e) {
			e.stopPropagation();
		});
		
		// Opera already click on "focus + enter"
		if (!window.opera) {
			// Keyboard (focus + enter)
			$prevBtn.add($closeBtn).add($nextBtn).keypress(function(e) {
				if (e.keyCode === 13) {
					$(this).click();
				}
			});
		}
	}
})(jQuery);

/* misc scripts : jsStyle, dsg object creation, hrefizer init */
(function($){
	/* Global object */
	window.dsg = { fn: {} };
	
	/* Add "js" class to body element */
	dsg.fn.jsStyle = function() {
		document.body.className += " js";
	};
	
	// On document ready
	$(function() {
		$.hrefizer();
	});

})(jQuery);

