﻿/**
* BRP Base namespace setup
*/
window.BRP = window.BRP || {};

var SelectedSiteMapNodes = "";


BRP = {
    // Main function call (page init)
    Init: function() {
        //document.body.className += " hasJS";
    }

};

//YAHOO.util.Event.addListener(window, "load", BRP.Init, BRP, true);

// ------[ Expand ]------------------------------------------------- //	
BRP.Expand = function(el) {
    if (el) {
        this.Root = el;
        YAHOO.util.Event.addListener(window, "load", this.Init, this, true);
    }
};

BRP.Expand.prototype = {

    Root: null,

    Init: function() {
        div = document.getElementById(this.Root);
        if (div) {
            dl = div.getElementsByTagName("dl");

            for (var j = 0; j < dl.length; j++) {
                var dt = dl[j].getElementsByTagName('dt');
                dt[0].dl = dl[j];
                dl[j].className += ' closed';
                dt[0].onclick = function() {
                    state = (this.dl.className.indexOf("opened") != -1) ? false : true;
                    if (state) {
                        this.dl.className = this.dl.className.replace('closed', 'opened');
                    } else {
                        this.dl.className = this.dl.className.replace('opened', 'closed');
                    }
                };
            }
        }
    }
};

// ------[ Other Products ]------------------------------------------------- //	
BRP.OtherProducts = {
    IsShow: false,
    Timer: null,
    DivElement: null,

    Init: function() {
        this.DivElement = document.getElementById("other-brp-products");
        if (this.DivElement) {
            this.DivElement.onmouseover = this.Show;
            this.DivElement.onmouseout = this.Hide;
        }
    },

    Show: function() {
        clearTimeout(BRP.OtherProducts.Timer);
        BRP.OtherProducts.Timer = false;
        BRP.OtherProducts.DivElement.style.display = "block";
        BRP.OtherProducts.IsShow = true;
        window.scrollTo(0, 10000000);
    },

    Hide: function() {
        BRP.OtherProducts.Timer = setTimeout('BRP.OtherProducts.HideTimer()', 500);
    },

    HideTimer: function() {
        BRP.OtherProducts.Timer = false;
        BRP.OtherProducts.DivElement.style.display = "none";
        BRP.OtherProducts.IsShow = false;
    },

    Display: function() {
        if (this.DivElement) {
            if (!this.IsShow) {
                this.Show();
                //this.Timer = setTimeout('BRP.OtherProducts.HideTimer()',1500);
            }
            else this.Hide();
        }
    }
};
//YAHOO.util.Event.addListener(window, "load", BRP.OtherProducts.Init, BRP.OtherProducts, true);

BRP.Cookie = {

    Load: function(id) {
        var search = id + "=";
        var cookie = null;
        if (document.cookie.length > 0) { 					// if there are any cookies      
            offset = document.cookie.indexOf(search);
            if (offset != -1) { 							// if cookie exists          
                offset += search.length; 					// set index of beginning of value         
                end = document.cookie.indexOf(";", offset); // set index of end of cookie value         
                if (end == -1) end = document.cookie.length;
                cookie = unescape(document.cookie.substring(offset, end));
            }
        }
        return cookie;
    },

    Save: function(id, data, session) {
        if (session) {
            var now = new Date();
            var expires = now.getTime() + 365 * 24 * 60 * 60 * 1000;
            var expires = new Date(expires);
            session = "; expires=" + expires.toGMTString();
        } else session = "";

        document.cookie = id + "=" + escape(data) + session + "; path=/";
    }

};

// ------[ QueryUrl ]---------------------------------- //
BRP.QueryUrl = {

    Search: function(q) {
        if (q.length >= 1) this.q = q.substring(0, q.length);
        else this.q = null;
        this.keyValuePairs = new Array();
        if (q) {
            if (this.q.split("?")[1] != "undefined") {            
                this.keyValuePairs[0] = this.q.split("?")[1].split("&")[0]; //find the first query
                for (var i = 1; i < this.q.split("&").length; i++) {
                    this.keyValuePairs[i] = this.q.split("&")[i]; //Find all others query
                }
            }
        }
        this.getKeyValuePairs = function() { return this.keyValuePairs; };
    	this.getValue = function(s) { //Find specific query
            for (var j = 0; j < this.keyValuePairs.length; j++) {
                if (this.keyValuePairs[j].split("=")[0] == s) return this.keyValuePairs[j].split("=")[1];
            }
            return;
        };
    	this.getParameters = function() {
            var a = new Array(this.getLength());
            for (var j = 0; j < this.keyValuePairs.length; j++) {
                a[j] = this.keyValuePairs[j].split("=")[0];
            }
            return a;
        };
    	this.getLength = function() { return this.keyValuePairs.length; };
    },

    Get: function(key) {
        //Find QueryString in the url with the var param (key)
        var page = new BRP.QueryUrl.Search(window.location.search);
        return unescape(page.getValue(key));
    }
};
/*
I don't know where this methot is use.
*/
/*
var Modal = function() {
    var modal = null;
    this.hide = function() {
        if (modal) {
            modal.style.display = "none";
        };
    };
    this.show = function() {
        if (!modal) {
            var mainContent = document.getElementById("main-content");
            modal = document.createElement('div');
            modal.id = "brpModal";
            modal.style.position = "absolute";
            modal.style.height = "600px";
            modal.style.width = "100%";
            modal.style.zIndex = "1000";
            modal.style.top = "0px";
            modal.style.left = "0px";
            mainContent.appendChild(modal);
            UFO.create({
                movie: "/Files/neutral/flash/Preloader.swf",
                width: "100%",
                height: "100%",
                majorversion: "9.0.115.0",
                build: "0",
                wmode: "transparent",
                allowfullscreen: "true",
                allowScriptAccess: "always",
                quality: "high",
                flashvars: "",
                id: "brpModalFlash",
                name: "brpModalFlash"
            }, "brpModal");
        };
        modal.style.display = "block";
    };
};
/*
// ------[ Send to Friend pop up ]------------------------------------------------- //

/**
* SKI-DOO Base namespace setup
*/
var SKIDOO = {
    globals: {
        labels: {}
    },
    pages: {
        cultureSelection: {},
        all: {},
        previousYears: {},
        buildYourSled: {},
        promotionalSeason: {},
    	compareVehicles: {},
    	openHouseDefault: {},
    	openHouseDetail: {},
    	openHouseList: {},
    	getAQuote: {},
    	sheffieldFinancing:{},
    	videos: {},
        cufon: {},
    	showroom: {},
		iceblockreveal: {},
		enginetechnologies: {}
    },
    util: {},
    widgets: {}
};


SKIDOO.globals.centerPanelOnLoad = function() {
    var pnl = arguments[0] || null;
  
    if (pnl && pnl.cfg.getProperty('visible')) {
        var ViewX = arguments[1] || YAHOO.util.Dom.getViewportWidth();
        if (ViewX <= '940') ViewX = '940';
        var PanelX = parseInt(pnl.cfg.getProperty("width"), 10);
        var positionX = (ViewX - PanelX) / 2;

        pnl.cfg.setProperty("x", (positionX >= 0) ? positionX : 0);
        switch (pnl.id) {
            case 'yui-zipcodepopup-info':
                pnl.cfg.setProperty("x", positionX - 110);
                break;
            case 'moreInfoPanel':
                pnl.cfg.setProperty("x", positionX - 110);
                break;
        }
        pnl.cfg.setProperty('y', pnl.cfg.getProperty('y'));
    }
    return pnl;
};

SKIDOO.globals.centerPanelOnResize = function(evt, args, obj) {
    SKIDOO.globals.centerPanelOnLoad(obj);
    obj.sizeMask();
    
};

SKIDOO.globals.renderPanelIframe = function(pnl, HTMLBodyContent) {
    var viewPortWidth = YAHOO.util.Dom.getViewportWidth();
    var fn = [{ fn: 'setBody', args: HTMLBodyContent }, { fn: 'render', args: document.body }, { fn: 'show', args: null}];
    for (var i = 0; i < fn.length; i++) {
        var fx = fn[i];
        if (fx.args) {
            pnl[fx.fn](fx.args);
        }
        else pnl[fx.fn]();
    }
    SKIDOO.globals.centerPanelOnLoad(pnl, viewPortWidth);
};

SKIDOO.globals.isEnterKeyPress = function(e) {
    //e is event object passed from function invocation
    var characterCode;
    try {
        e = (e != null) ? e : event;
        characterCode = e.keyCode;
    } catch (e) { }
    return (characterCode == 13) ? true : false;
};
SKIDOO.globals.extendPnlParams = function(params) {
    var _r = {};
    for (var p in params) {
        _r[p] = params[p];
    }

    for (var p in SKIDOO.globals.pnlInitParams) {
        if (_r.hasOwnProperty(p)) continue;
        else {
            _r[p] = SKIDOO.globals.pnlInitParams[p];
        }
    }

    return _r;
};

/*-- Base settings for all panels ---*/
SKIDOO.globals.pnlInitParams = {
    height: '400px',
    width: '915px',
    constraintoviewport: false,
    underlay: "shadow",
    close: true,
    visible: false,
    fixedcenter: false,
    draggable: false,
    zIndex: 9997,
    y: 88,
    modal: true
};

SKIDOO.globals.iFrames = {};
SKIDOO.globals.iFrames.bigModalPanel = "<iframe width='915' height='400' marginwidth='0' marginheight='0' scrolling='auto' frameborder='0' src='%href%'></iframe>";
SKIDOO.globals.iFrames.newsletterPanel = "<iframe width='915' height='400' marginwidth='0' marginheight='0' scrolling='auto' frameborder='0' src='%href%'></iframe>";

/**
* Init for all pages
*/
SKIDOO.pages.all.init = function() {

    SKIDOO.globals.initPageTracking();

    //-ModalPopUp---------*/
    var modalPanelParams = SKIDOO.globals.extendPnlParams({ zIndex: 9998 });
    SKIDOO.globals.modalPopup = new YAHOO.widget.Panel("yui-modalpopup-info", modalPanelParams);
    SKIDOO.globals.modalPopup.render(document.body);

    // Settings Position + eventHandler onResize 
    SKIDOO.globals.centerPanelOnLoad(SKIDOO.globals.modalPopup);
    YAHOO.widget.Overlay.windowResizeEvent.subscribe(SKIDOO.globals.centerPanelOnResize, SKIDOO.globals.modalPopup);

    SKIDOO.globals.bindYUIModalPopUp = function() {
        var el = YAHOO.util.Dom.getElementsByClassName('yui-modalpopup', 'a') || arguments[0];
        for (var i = 0; el[i]; i++) {
            el[i].onclick = function(e) {
                e = e || event;
                YAHOO.util.Event.preventDefault(e);
                parent.scrollTo(0, 0);
                var IframeBody = SKIDOO.globals.iFrames.bigModalPanel.replace(/%href%/g, this.href);
                parent.SKIDOO.globals.renderPanelIframe(parent.SKIDOO.globals.modalPopup, IframeBody);
            };
        	el[i].style.visibility = "visible";
        }

        return;
    };
    
    SKIDOO.globals.bindYUIModalPopUp();
    //-ModalPopUp---------*/

    SKIDOO.globals.bindYUIBigModalPopUp = function() {

        //-BIGModalPopUp---------*/
        var bigModalPanelParams = SKIDOO.globals.extendPnlParams({ height: '400px', width: '680px', zIndex: 9998 });
        SKIDOO.globals.bigModalPopup = new YAHOO.widget.Panel("yui-bigmodalpopup-info", bigModalPanelParams);
        SKIDOO.globals.bigModalPopup.render(document.body);

        /* Settings Position + eventHandler onResize */
        SKIDOO.globals.centerPanelOnLoad(SKIDOO.globals.bigModalPopup);
        YAHOO.widget.Overlay.windowResizeEvent.subscribe(SKIDOO.globals.centerPanelOnResize, SKIDOO.globals.bigModalPopup);

        var el = YAHOO.util.Dom.getElementsByClassName('yui-bigmodalpopup', 'a');
        for (var i = 0; el[i]; i++) {
            el[i].onclick = function(e) {
                e = e || event;
                YAHOO.util.Event.preventDefault(e);
                var IframeBody = SKIDOO.globals.iFrames.bigModalPanel.replace(/%href%/g, this.href);
                parent.SKIDOO.globals.renderPanelIframe(parent.SKIDOO.globals.bigModalPopup, IframeBody);
            };
        	el[i].style.visibility = "visible";
        }
        return;
    };
    
    SKIDOO.globals.bindYUIBigModalPopUp();

    SKIDOO.globals.bigModalPopup.launch = function(href) {
        var pnl = parent.SKIDOO.globals.bigModalPopup;
        var IframeBody = SKIDOO.globals.iFrames.bigModalPanel.replace(/%href%/g, href);
        parent.SKIDOO.globals.renderPanelIframe(pnl, IframeBody);
    }; //-BIGModalPopUp---------*/
    
    
    //-ModalPopUpNewsletter---------*/
    /* Open register newsletter - Setting with parent scoping */
    var getNewsletterPanelParams = SKIDOO.globals.extendPnlParams({ zIndex: 9998 });
    SKIDOO.globals.bigModalGetNewsletter = new YAHOO.widget.Panel("yui-bigmodalpopup-newsletter", getNewsletterPanelParams);
    SKIDOO.globals.bigModalGetNewsletter.render(document.body);

    /* Settings Position + eventHandler onResize */
    SKIDOO.globals.centerPanelOnLoad(SKIDOO.globals.bigModalGetNewsletter);
    YAHOO.widget.Overlay.windowResizeEvent.subscribe(SKIDOO.globals.centerPanelOnResize, SKIDOO.globals.bigModalGetNewsletter);

    var el = YAHOO.util.Dom.getElementsByClassName('yui-bigmodalgetnewsletter', 'a');
    for (var i = 0; el[i]; i++) {
        el[i].onclick = function(e) {
            e = e || event;
            YAHOO.util.Event.preventDefault(e);
            var IframeBody = SKIDOO.globals.iFrames.newsletterPanel.replace(/%href%/g, this.href);
            parent.SKIDOO.globals.renderPanelIframe(parent.SKIDOO.globals.bigModalGetNewsletter, IframeBody);
        };
    	el[i].style.visibility = "visible";
    }
    
    SKIDOO.globals.NewsletterRegisterOpenPopup = function(href) {
        parent.scrollTo(0, 0);
        try {
            var IframeBody = SKIDOO.globals.iFrames.newsletterPanel.replace(/%href%/g, href);
            parent.SKIDOO.globals.renderPanelIframe(parent.SKIDOO.globals.bigModalGetNewsletter, IframeBody);
            return true;
        } catch (e) { return false; }
    }; //-ModalPopUpNewsletter---------*/
    

    //  IFRAME POPUP SETUP
    //  Setup for full page redirect (all forms)
    /*--- DEPRECATED
    var el = YAHOO.util.Dom.getElementsByClassName('yui-redirect', 'a');
    for (var i = 0; el[i]; i++) {
        el[i].onclick = function(e) {
            e = e || event;
            YAHOO.util.Event.preventDefault(e);
            top.location.href = this.href;
        }
        el[i].style.visibility = "visible";
    }
    */

    /**
    * Initialize Send to a Friend Pop up page
    */
    /*--- DEPRECATED    
    SKIDOO.globals.sendEmail = new YAHOO.widget.Panel(
		"sendtofriend",
		{
		    width: "600px",
		    height: "300px",
		    constraintoviewport: true,
		    underlay: "none",
		    close: true,
		    visible: false,
		    fixedcenter: true,
		    draggable: false,
		    zIndex: 5,
		    modal: false
		}
	);
    //Render the panel for screen
    SKIDOO.globals.sendEmail.render(document.body);

    //Create an array with all anchor with the classname "sendfriend"
    var el = YAHOO.util.Dom.getElementsByClassName('sendfriend', 'a');

    for (var i = 0; el[i]; i++) {
        el[i].onclick = function() {
            var pnl = SKIDOO.globals.sendEmail;
            pnl.setBody("<iframe width='600' marginwidth='0' marginheight='0' scrolling='no' frameborder='0' height='300' src='" + this.href + "'></iframe>");
            pnl.render();
            pnl.show();
            return false;
        }
        el[i].style.visibility = "visible";
    }
    */

};
// ------[ Generic Popup Window ]------------------------------------------------- //
function popWin(url, w, h, scroll, tools, name, center) {
    var str = "height=" + h + ",innerHeight=" + h;
    str += ",width=" + w + ",innerWidth=" + w;
    if (!center) center = true;
    if (!scroll) scroll = 0;
    if (!tools) tools = 0;
    if (!name) name = "pop";

    if ((window.screen) && (center)) {
        var ah = screen.availHeight - 30;
        var aw = screen.availWidth - 10;

        var xc = (aw - w) / 2;
        var yc = (ah - h) / 2;

        str += ",left=" + xc + ",screenX=" + xc;
        str += ",top=" + yc + ",screenY=" + yc;
    }
    window.name = "main";
    pop = window.open(url, name, 'toolbar=' + tools + ',location=0,directories=0,status=0,menubar=0,scrollbars=' + scroll + ',resizable=0,' + str).focus();
}

// ------[ Pull-down menu Faq Template ]------------------------------------------------- //

function setFaqCategory(newAddress) {
    if (newAddress != "") {
        window.top.location.href = newAddress;
    }
}

// ------[ Home - Find a dealer button and textField ]--------------------------------------------- //

BRP.FindADealer = {

    TextBoxInstance: null,
    ButtonInstance: null,
    Culture: null,
    //initialisation function that must called on page load to enable functionality
    HookEvents: function(culture, textBoxId, buttonId) {
        this.TextBoxInstance = document.getElementById(textBoxId);
        this.ButtonInstance = document.getElementById(buttonId);
        this.Culture = culture;
        YAHOO.util.Event.on(this.TextBoxInstance, 'keypress', this.LocationKeyPressed);
        YAHOO.util.Event.on(this.TextBoxInstance, 'focus', this.Focused);
        YAHOO.util.Event.on(this.ButtonInstance, 'click', this.ButtonPressed);
    },
    //if the user pressed enter while typing in the search box open the pop up.
    LocationKeyPressed: function(e, params) {
        e = e || event;

        if ((e.keyCode === 13)) {
            YAHOO.util.Event.preventDefault(e);
            BRP.FindADealer.OpenFindADealerPopup();
        }
    },
    //if the user set focuses on the textbox pre-filled with the hint default value text (ex: "Address & City") 
    //clear the box 
    Focused: function(e, params) {
        if (this.getAttribute('initialValue') == this.value) {
            this.value = '';
        }
    },
    //the user has clicked on the search button triggers the pop up opening
    ButtonPressed: function(e, params) {
        e = e || event;
        YAHOO.util.Event.preventDefault(e);
        BRP.FindADealer.OpenFindADealerPopup();
    },

    OpenFindADealerPopup: function() {
        var requestedLocation = BRP.FindADealer.TextBoxInstance.value;
        //if the user has clicked on find a dealer without entering any information in the textbox it stills contains the default hint text
        //so we open the popup with an empty location as parameter.
        if (BRP.FindADealer.TextBoxInstance.getAttribute('initialValue') == BRP.FindADealer.TextBoxInstance.value) {
            requestedLocation = '';
        }
        popWin('http://www.brp.com/' + BRP.FindADealer.Culture + '/Dealer.Locator/Ski-Doo?location=' + escape(requestedLocation), 850, 615, 1, 0);
    }
};

// ------[ Main Navigation ]------------------------------------------------- //

/***
 * Adds a delay on the mouse actions on the menu, so the user dont have to be extremely precise
 * when hovering the menu.
 */
SKIDOO.widgets.navigation = {
	
	MenuDelayer: function() {
		
		//console.log("MenuDelayer");
		//console.log(this.elems);
		var delay = 200;
		var hideTimer;
		
		var hide = function() {
			$("#main-nav ul > li > .level-2").css("left", "-8000px");
		};

		$("#main-nav > ul > li").each(function(e, index) {

			var that, target, targetPosition;
			that = $(this);
			target = $(".level-2", that);
			//Find the left position to keep the data in render (show)
			targetPosition = target.css("left");
			
			/*
			    Display 'block' the element to allow IE to render css3PIE correctly.
			    After, move out the element at left (hide)
			*/
			target.css("display", "block").css("left","-8000px");
            
			//IE exception to render css3Pie (fixed IE8)
			var css3PieContainer = target.parent("li").find("css3-container");
			if(css3PieContainer) {
			    css3PieContainer.css("left","-8000px");
			}
		
		    //Activated the Current Sub Menu
		    that.hoverIntent(function(e) {
			    $("#main-nav ul > li > .level-2").not(this).css("left","-8000px");
	            target.css("left", targetPosition);
	        }, function(){});
		});

		$("#main-nav").mouseleave(function() {
			clearTimeout(hideTimer);
			hideTimer = setTimeout(hide, delay);
		});
	}
	
};

// ------[ Tips Animation ]------------------------------------------------- //

SKIDOO.widgets.tips = {
	
	HoverAnim: function() {
		
		//console.log("HoverAnim");
		//console.log(this.elems);

		/**
		*   data-hover-color = Hover anchor text color
		*/
		$.each(this.elems, function(key, value) {
			
		    //console.warn(key);
		    //console.log(value);
		    //$("#main-nav li#showroom ul.level-2").css("display", "block");//Removed this element after the animation function....
		    var container, ul, ulPosition, li, liPosition, liHeight, liWidth, hoverTip, defaultColor, hoverColor, animateColor=false, dataColor, dataInfo;
    		
			//Used global var to updated the current click element
            var currentIndex = 0;
			
		    container = $(value);

            if(container) {
            	
            	//We will need to remove the element if it's already in DOM (to reactivated the binding event)
    		    if($(".tool-tip-hover", container)) {
    		    	$(".tool-tip-hover", container).remove();
    		    }
            	
            	/**
                *   Create 'Hover Tip' bar element and attached in DOM
                */
		        //Find the y position to set the top position to the HoverTip.
		        ul = $("ul:first", container);
		        ulPosition = ul.position();
        	    //Find the first 'li' to set the 'height' and 'width' to the HoverTip.
		        li = $("li:first", ul);
		        liHeight = li.innerHeight();
		        liWidth = li.innerWidth();
            	
        	    //Created and appended the HoverTip to the container element and move it to the first 'li'.
            	var dataPage = container.data("page");
            	if(dataPage=="byos") {
            		if(li.length > 0) {
            			//Set higher size because we need to set the tip outside the container.
		        	    liWidth = Math.round(li.innerWidth()+30);
            		}
		        }
            	hoverTip = "<div class='tool-tip-hover' style='top:"+ ulPosition.top +"px;'><div class='tool-tip-container'><div class='arrow-corner bottom-left'></div><div class='tool-tip-content' style='width:"+ liWidth +"px;height:"+ liHeight +"px;'></div></div></div>";
            	container.append(hoverTip);
                
            	
            	/**
                *   Showroom: Initialized hover anchor text color
                */
            	dataColor = container.data("hover-color");
            	if(dataColor){
            		//Verified if the string as '#' symbol (ex: #fff)
            	    //if(dataColor.indexOf("#") != '-1'){
            		if(dataColor.match(/^#/)){
            	    	
            	    	//Activate hover anchor text color animation in the hoverIntent function
            	    	animateColor = true;
            	    	
            	    	//Store the default anchor color
        	            defaultColor = li.find("a").css('color');
            	    	
            	    	//Set the hover text color in the first 'li'
            	    	hoverColor = dataColor;
        	            li.children("a").css("color",hoverColor);
                        
            			//Regroup all 'li' object
            			var allTarget = ul.find("li");
            	    }
            	}
            	
            	//TODO : Fucktop condition... not enough time to render properly the code to classified the methot depend to current page...
            	if(dataPage!="byos") {
            	    /**
                    *   Showroom - SerieOverview & AllSeries : Initialized model info box
                    */
            	    dataInfo = container.data("container");
                	
            	    //Show only the first model info box
    			    if(dataColor){
    				    var arrayInfo = $(dataInfo);
        	            $(arrayInfo).each(function(index) {
        		            //$(this).hide().css("opacity","0");
        	            	$(this).hide();
		                });//div model each
    			    }
            	}
            	
            	/**
            	*   Animation
            	*/
                var hoverAnim = function(els) {
                    var targetPosition, that, setHeight, hoverColorAnimation, toolTipHover, toolTipContent;

	                that = $(els);
    	            toolTipHover= $(".tool-tip-hover", container);
    	            toolTipContent= $(".tool-tip-content", toolTipHover);
	        	    
        	        if(that && toolTipHover && toolTipContent) {
		        	        
	    	            //Removed all hover class on all 'li'
    	                if(animateColor){
    	    	            allTarget.find("a").stop().css("color",defaultColor);
    	                }
		        	
	                    // Retrieve the current position of an element relative to the document
                        targetPosition = Math.round(that.position().top + ulPosition.top);
    				    
    	                // Set the 'height' of the current target
                        setHeight = function(el) {
    	                    var height = $(el).innerHeight();
    	                    height = Math.round(height);
    	                    return height;
                        };
		        	    
    	                // Animate the anchor text color
    	                hoverColorAnimation = function(){
    	                    that.children("a").stop().animate({"color":hoverColor},300);
                        };
		        	
	                    // Animate the Y-Postion
                        toolTipHover.stop().animate(
    	                    {'top':targetPosition},
    	                    {duration:500,easing:'easeOutExpo'}
                        );

	                    // Animate the height size
                        toolTipContent.stop().animate(
                            {'height':setHeight(that)},
                            {
                	            duration:100,
                	            easing:'linear',
                	            complete:function() {
                		            if(animateColor) {
                                        hoverColorAnimation();
                		            }
                		            //that.addClass("hover");
                                }
                            }
                        );
        				
        	        }//if vars
                };
            	
            	/**
            	*   Updated Background
            	*/
            	var background = function(index, arrayInfo) {
            		//Change background image if it's skandic or expedition model.
            		//var currentTarget = $(arrayInfo[index]).find("img").attr("alt").toLowerCase();
            		var currentTarget = $(arrayInfo[index]).attr("id");
            		var background = $("body").css("background-image").indexOf('No360') >= 0;

            		if (currentTarget.indexOf('skandic-wt') != -1
	            		|| currentTarget.indexOf('skandic-swt') != -1
            			|| currentTarget.indexOf('expedition-se') != -1
            			|| currentTarget.indexOf('expedition-le') != -1) {
            			//to prevent background wewrite if the beackground already the No360 header
            			if (!background) {
            			    $("body").css("background-image", "url('/Files/Neutral/Images/Headers/header_showroom_No360.jpg')");
            			}
            		}
            		else
            		{
            			//to prevent background rewrite if the beackground already the standard header
            			if (background) {
            				$("body").css("background-image", "url('/Files/Neutral/Images/Headers/header_showroom.jpg')");
            			}
            		}
            	};
            	
            	/**
            	*   Showroom - AllSeries + SerieOverview : Show the current image model
            	*/
            	var modelsAnim = function(index, that) {
            		
            		var targets = $(that);
            		
            		//Updated background
            		background(index, arrayInfo);

            		//Show current selected model
            		if ($.browser.msie && $.browser.version < "9.0") {
            			//IE7-8 : Without the animation opacity
            			$(targets).each(function(index) {
            			    $(this).hide();
            		    });
            		    $(targets[index]).stop().show();
            		}else {
            			$(targets).each(function(index) {
            			    $(this).hide();
            		    });//div model each
            		    $(targets[index]).stop().show(500);
            		}
            		
            	};
            	
            	/**
                *   Showroom - AllSeries : Initialized automatic animate timer scroll
                */
    	        var dataTimer = container.data("timer");
            	
            	if(dataTimer == true) {

            		var listLi = new Array();
            		
            		//Checked where the tooltip is
        			$("li", container).each(function(index) {
        			    var that = $(this);
        				
        				//Added el + position top
        				listLi.push([this,that.position().top]);
        				
        			});//li each
            		
            		var toolTipHover= $(".tool-tip-hover", container);
    	        		
    	        	if(toolTipHover) {

    	        		var setTimer, timer, whereToolTip, liPosTop, listLiLength, currentPos;
                        
    	        		//Need this fonction to restart the timer if the user click on list
    	        		setTimer = function() {
                            
    	        			//specific intervals
    	        			timer = window.setInterval(function() {
                                
    	        				// Retrieve the current toolTip position
    	        				whereToolTip = toolTipHover.position().top - ulPosition.top;
    	        				
    	        				// Retrieve the position we need to go
    	        				listLiLength = listLi.length - 1;
    	        				for (var i = 0; i <= listLiLength; i++) {

    	        					/**
    	        					*   Find the LI position top
    	        					*   [i] = LI element
    	        					*   [1] = LI position top value
    	        					*/
    	        					liPosTop = listLi[i][1];

    	        					if (liPosTop == whereToolTip) {
    	        						//Set the target position (LI)
    	        						currentPos = i + 1;
    	        						if (currentPos > listLiLength) {
    	        							currentPos = 0;
    	        						}
    	        						break;
    	        					}
    	        				}
    	        				
    	        				//Updated this value because we don't want to loose the info if the user click on list
    	        				currentIndex = currentPos;
    	        				
    	        				//Activated animation
    	        				hoverAnim(listLi[currentPos][0]);
    	        				if (dataInfo) {
    	        					modelsAnim(currentPos, arrayInfo);
    	        				}
    	        				//clearTimeout(timer);
    	        			}, 6000);
    	        			
    	        		};
            		    //Init Interval
    	        		setTimer();
    	        	}
    	        }
			
            	/**
                *   Set event
                */
	            $("li", container).each(function(index) {
        	        if(!dataColor){
        	        	
        	        	toolTipHover = $(".tool-tip-hover", container);
        	        	toolTipHover.hide();
        	        	
                        //MOUSEHOVER : Main navigation
        	        	$(this).hoverIntent(function(e) {
        	        		toolTipHover.show();
        	        		hoverAnim(this);
	                    }, function(e) {
	                    	//Hide the tooltip
	                    	//console.log("e = ",e);
	                    	//console.log("this = ",this);
                            //console.warn("---------------------------------------------------------------------------------");
	                    	//var that = this;
	                    	
	                    	var relatedTarget = e.relatedTarget;
	                    	//console.log("relatedTarget = ",relatedTarget);
	                    	//console.log("ul = ",ul);
	                    	//console.log("ul[0] = ",ul[0]);
	                    	
                            
	                    	if (typeof relatedTarget === "undefined") {/*If Outside ViewPort*/
                            	toolTipHover.hide();
                            } else {
                            	//console.warn("relatedTarget ELSE");
                                /*Look if we are inside the Parent Element*/
                                //var isInside = YAHOO.util.Dom.getAncestorBy(relatedTarget, function(el) {
                            	
                                function isInside() {
                            		//console.log("Fn isInside = ",$(that));
                                	
                                	//var parent = $(relatedTarget).parent(ul)[0];
                            		
                                	//console.log("parent = ",parent);
                            		//console.log("ul = ",ul[0]);
                                	/*Look if we are inside the Parent Element*/
                                	//if(parent == ul[0] || parent == $(".tool-tip-container")) {
                                	if($.contains(ul[0], relatedTarget) == true) {
                            		    //console.warn("return true;");
                            			return true;
                            	    }
                            		
                                	return false;
                                };

                            	/*var isInside = YAHOO.util.Dom.getAncestorBy(relatedTarget, function(el) {
                                    if (el.id === container.id) {
                                        return true;
                                    }
                                    return false;
                                });*/
                            	
                            	//console.log("isInside() = ", isInside());
                                if (!isInside()) {
                                	/*console.log("----------------------------");
                                	console.log("!isInside");
                                	console.log("----------------------------");*/
                                    toolTipHover.hide();
                                }
                            }
	                    	
	                    	
	                    	
	                    });
                    }
	            	else
        	        {
        	        	if(dataPage=="byos") {
        	        		//CLICK : BYOS
        	        	    $(this).click(function(e) {
	    	                    e.preventDefault();
        	        		    //If we are already on specific element, do nothing
        	        		    if(index !== currentIndex) {
        	        		    	currentIndex = index;
        	        		        hoverAnim(this);
        	        		    }
        	        	    });
        	        	}else {
        	        	    //CLICK : Showroom - SerieOverview & AllSeries
        	        	    $(this).click(function(e) {
	    	                    e.preventDefault();
        	        		    //If we are already on specific element, do nothing
        	        		    if(index !== currentIndex) {
            	        			
        	        			    if(dataTimer == true) clearTimeout(timer);
            	        			
        	        			    currentIndex = index;
        	        		        hoverAnim(this);
        	        		        if(dataInfo) {
        	        			        modelsAnim(index, arrayInfo);
        	        		        	//Updated the background
        	        		        	background(index, arrayInfo);
        	        		        }
            	        			
        	        			    if(dataTimer == true) setTimer();
        	        		    }
        	        	    });
        	        	}
        	        }
	            });//li each
            	
            }//If container
			
		});//each
		
	}//HoverAnim
};

// ------[ Dealer ]------------------------------------------------- /

function DealerCaptureKey(evt, LocateDealerUrl, tbFindID) {
    var c = document.layers ? evt.which
            : document.all ? event.keyCode
            : evt.keyCode;

    if (c == 13)  //return /enter key
    {
        DealerSearch(LocateDealerUrl, tbFindID);
        return false;
    }
    return true;
}

function DealerSearch(LocateDealerUrl, tbFindID) {
    document.location = LocateDealerUrl + '?search=' + escape(document.getElementById(tbFindID).value);
    return false;
}

/*  The script below uses the YouTube JavaScript Player API and not the The YouTube Iframe API (it's still at an experimental stage)
/*
 * @author       Rob W (http://stackoverflow.com/questions/7443578/youtube-iframe-api-how-do-i-control-a-iframe-player-thats-already-in-the-html/7513356#7513356)
 * @description  Executes function on a framed YouTube video (see previous link)
 *               For a full list of possible functions, see:
 *               http://code.google.com/apis/youtube/js_api_reference.html
 * @param String frame_id The id of the div containing the frame
 * @param String func     Desired function to call, eg. "playVideo"
 * @param Array  args     (optional) List of arguments to pass to function func*/

    function callPlayer(frame_id, func, args){
        /*func: playVideo, pauseVideo, stopVideo, ... Full list at:
         * http://code.google.com/apis/youtube/js_api_reference.html#Overview */

        if(window.frames[frame_id]){
            window.frames[frame_id].postMessage(JSON.stringify({
                        "event": "command",
                        "func": func,
                        "args": args,
                        "id": 0/*Can be omitted.*/
                    }), "*");
        }
      
    }

// ------[ Video Gallery ]------------------------------------------------- /
SKIDOO.pages.videos = {
    init: function() {
        
    	$.each(this.elems, function(key, value) {

    	    var $that = $(value);
    	    //console.log("$that = ", $that);
            var videoModule = $('.video-gallery-box', $that);
    	    //console.log("videoModule = ", videoModule);
    	    var $trackAction = $that.data("trackaction");
    	    //console.log("$trackAction = ", $trackAction);
        	
            videoModule.each(function(i){
                
                /* Axis can be 'x' or 'y', this will defines all behaviour below */ 
                var $self = $(this); 
                var category =  $self.find('h2').text();   
                var $videoplayer = $self.find('.video-player, .viewer');        
                var currentIndex = 0;
                var $list = $self.find('.video-player-nav ul.thumbs');
                var $thumbs = $self.find('.video-player-nav ul.thumbs li');
                var increment = $thumbs.outerHeight();
                var targetPosition = 0;
                var _this = this;
                var $content = $self.find('.text-content');
                var $prevArrow = $self.find("a.prev-arrow");
                var $nextArrow = $self.find("a.next-arrow");
                var index = i;
                var culture = SKIDOO.globals.cultureId;
                var playerSize = new Array(873,474);
                var findSize = $self.attr("class").split(" ");
                var $trackingClick = $('<div class="tracking-click"></div>');
                
                for(i=0;i<findSize.length;i++){
                    if(findSize[i].indexOf("player")!=-1){
                        var size = findSize[i].split("_");
                            size = size[1].split("x");
                            playerSize = size;
                    }  
                }

        	    $videoplayer.each(function() {
        		    $(this).append($trackingClick);
        	    });
               
            	if($trackAction == "Sleds") {
            		$trackingClick.css('display','none');
            	}else {
            		bindTrackingClick($trackingClick);
            	}

            	function bindTrackingClick($trackingClick) {
                    $trackingClick.click(function(){
                        var ytPlayerName = $(this).parent().find('iframe').attr('name');
                        callPlayer(ytPlayerName,"playVideo");
                        $.tracking.track("ga-allVideoClick", $(this),{'section':$trackAction, 'videoname': $content.find('.title').text(), 'trackerId':"old_."});
                        $.tracking.track("ga-allVideoClick", $(this),{'section':$trackAction, 'videoname': $content.find('.title').text(), 'trackerId':""});
                       
                        $(this).unbind('click');
                        $(this).css('display','none');
                    });
                }
                /* On click previous *//*
                $prevArrow.click(function(){
                    if($(this).hasClass('disabled') !== true){
                        currentIndex = (currentIndex > 0) ? currentIndex-1 : 0;            
                        targetPosition = parseInt(currentIndex * increment * -1);
                        _this.animate();
                        _this.updateArrows();
                    }
                });*/
                
                /* On click next *//*
                $nextArrow.click(function(){
                     if($(this).hasClass('disabled') !== true){
                        currentIndex = (currentIndex < $thumbs.length-1) ? currentIndex+1 : $thumbs.length-1;            
                        targetPosition = parseInt(currentIndex * increment * -1);
                        _this.animate();
                        _this.updateArrows();
                    }
                   
                });*/
            	
                /* On click thumnails */        
                $thumbs.click(function(e){
                    e.preventDefault();
                    var $videoLink = $(this).find('a');
                        //$videoLink.click(function(){return false;});
                    var videoURL = $videoLink.attr('href');
                    var videoTitle = $videoLink.find('strong.title').html();
                    var videoDescription = $(this).find('span.description').html();
                    var isVideo = videoURL.split(".");
                        isVideo = isVideo[isVideo.length-1];
                        isVideo = (isVideo!="jpg" && isVideo!="jpeg" && isVideo!="gif" && isVideo!="png");
                                            
                    try {
                        var sectionID = $(this).parents(".video-gallery-box").find("h2").eq(0).attr("id");
                        var videoID = (isVideo) ? videoURL.split('?v=')[1].split('&')[0] : "";
                        //var embedObj = '<object style="height: '+playerSize[1]+'px; width: '+playerSize[0]+'px"><param name="movie" value="http://www.youtube.com/v/'+ videoID +'?version=3&theme=light&showinfo=0&enablejsapi=1"><param name="allowFullScreen" value="true"><param name="wmode" value="opaque"><param name="allowScriptAccess" value="always"><embed id="ytvideoplayer'+index+'" src="http://www.youtube.com/v/'+ videoID +'?version=3&theme=light&showinfo=0&enablejsapi=1" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" width="'+playerSize[0]+'" height="'+playerSize[1]+'" wmode="opaque"></object>';
                        //var embedObj = '<div id="ytPlayerHolder'+index+'" style="width:'+playerSize[0]+'px; height:'+playerSize[1]+'px;"></div>';
                       // var embedObj = "<object id='ytPlayerHolder"+index+"' style='height: "+playerSize[1]+"px; width: "+playerSize[0]+"px'><param name='movie' value='http://www.youtube.com/v/"+ videoID +"?version=3&theme=light&showinfo=0&rel=0&enablejsapi=1&autoplay=1'><param name='allowFullScreen' value='true'><param name='allowScriptAccess' value='always'><param name='wmode' value='opaque'><embed src='http://www.youtube.com/v/"+ videoID +"?version=3&theme=light&showinfo=0&rel=0&enablejsapi=1&autoplay=1' type='application/x-shockwave-flash' allowfullscreen='true' allowScriptAccess='always' width='"+playerSize[0]+"' height='"+playerSize[1]+"' wmode='opaque'></object>";
                        var embedObj = (isVideo) ? "<iframe id='ytPlayerHolder"+index+"' name='ytPlayerHolder" +index+"' width='"+playerSize[0]+"' height='"+playerSize[1]+"' src='http://www.youtube.com/embed/"+ videoID +"?version=3&theme=light&showinfo=0&rel=0&enablejsapi=1&wmode=transparent' frameborder='0' allowfullscreen></iframe>" : "<img id='ytPlayerHolder"+index+"' width='"+playerSize[0]+"' src='"+videoURL+"' alt='' />";
                        var mediaContainer = $videoplayer.find('.media');
                        mediaContainer.empty().append(embedObj);
                       
                        if(isVideo){
                    	    if($trackAction == "Sleds") {
                    		    //CategoryOverview.aspx
                    	    	var $videoName = $(this).find('.multimedia-name').data("trackinglabel");//.text();
                                trackPageEvent('Video', $trackAction, culture + "/" + category + "/" + $videoName);
                    	    }else {
                    	    	//VideoGallery.aspx
                    		    var $trackingClick = $videoplayer.find('.tracking-click');
                                $trackingClick.css('display','block');
                                bindTrackingClick($trackingClick);
                    	    }
                        }else {
                    	    var $pictureName = $(this).find('img').attr('src');
                    	    $pictureName = $pictureName.substring($pictureName.lastIndexOf("/")+1);
                            trackPageEvent('Pictures', 'View', culture + "/" + category + "/" + $pictureName);
                        }
                    
                        $content.find('.title').html(videoTitle);
                        $content.find('.description').html(videoDescription);
                        
                        if(typeof sectionID != "undefined") document.location = "#"+sectionID;
                        
                    } catch (err) { } 
                });
                
                /* Animate function :: called on the click of next & prev arrows *//*
                this.animate = function(){           
                    $list.stop().animate({'top':targetPosition}, {duration:800, easing:'easeOutExpo'});            
                }; /* If there's less than 4 videos, hide arrows and place thumbs *//*
                if($thumbs.length < 4){
                    $self.find('.video-player-nav').addClass('no-arrows');
                }
                
                this.updateArrows = function(){
                    
                    if(currentIndex === 0){
                      $prevArrow.addClass('disabled');  
                    }else{
                      $prevArrow.removeClass('disabled');  
                    }
                    
                    
                    if(currentIndex >= $thumbs.length-2){
                      $nextArrow.addClass('disabled');  
                    }else{
                      $nextArrow.removeClass('disabled'); 
                    }
                    
                };
        	    this.updateArrows();*/
                      
            });       
        });//each
    }//init
};
// ------[ Previous Years ]------------------------------------------------- /
SKIDOO.pages.previousYears = {
    init: function() {
    	for (var i = 0; i < this.elems.length; i++) {
    		var divContainerId = this.elems[i].getAttribute("data-container");
    		if (divContainerId) {
    		    var containerList = YAHOO.util.Dom.get(divContainerId);
    		    if (containerList) {
    			    //Create an array with all anchor in the "divContainerId"
    			    var previousLink = containerList.getElementsByTagName("a");
    			    if (previousLink) {
    				    for (i = 0; i < previousLink.length; i++) {
    					    YAHOO.util.Event.addListener(previousLink[i], "click",
    						    function() {
    							    return function(e) {
    								    YAHOO.util.Event.preventDefault(e);
    								    //Tracking Google
    								    //var eventPath = document.location.pathname;
    								    var aParams = this.getAttribute('trackEvent');
    								    aParams = aParams.split(",");
    								    //Exemple : 'Outgoing links &ndash; en-US', 'Previous models', '2010'
    								    trackPageEvent('Outgoing Links &ndash; ' + SKIDOO.globals.cultureId, 'Previous models', aParams[0]);
    								    //Open
    							    	if(aParams[0] == "2011" || aParams[0] == "2012") {
    							    	    popWin(this.href, 1024, 700, 1, 0);
    							    	}else {
    							    		popWin(this.href, 900, 700, 1, 0);
    							    	}
    							    };
    						    }());
    				    }
    			    } //IF previousLink
    		    } //IF containerList
    		} //IF divContainerId
    	};
    } //Init
};
// ------[ Cufon ]------------------------------------------------- /

/*
    Possible function value :
    
    //----------Array value only ----------//
    SKIDOO.pages.cufon.replace(['h1', 'h2', '.cufon', '#footer h2.cufon']).replace(['.title'], '#footer');
    SKIDOO.pages.cufon.replace(['h1', 'h2', '.cufon', '#subscribe-footer-form span']);
    SKIDOO.pages.cufon.replace(['h1', 'h2', '.cufon', '#footer-generic ul.footer-link']);
    SKIDOO.pages.cufon.replace([ '.cufon']);
    SKIDOO.pages.cufon.replace(['#main-content h1']);
    SKIDOO.pages.cufon.replace([ 'h4.cufon']);
    
    //----------Array value only + Specific Root -------//
    SKIDOO.pages.cufon.replace(['#discover-brand li'], document.getElementById('footer-generic'));
    SKIDOO.pages.cufon.replace(['.footer-link'], document.getElementById('footer-generic'));
    SKIDOO.pages.cufon.replace(['.footer-link'], '#footer-generic');
*/
/*
SKIDOO.pages.fontReplace = function (){
    SKIDOO.pages.cufon.replace(['#main-content h2']);
    SKIDOO.pages.cufon.replace(['#main-content h3']);
    SKIDOO.pages.cufon.replace(['#header h1']);
    SKIDOO.pages.cufon.replace(['#header h2']);
    SKIDOO.pages.cufon.replace(['#header p']);
};
SKIDOO.pages.cufon = {
    fonts: {n: 'Forza Medium', b: 'Forza Bold'},
    
    //Recupere les elements correspondant a un selector css
    getSelector: function(sel){
        var r = {root: null, tag: null, className: null}, els = sel.split(' ');
        for(var i = 0; i < els.length; i++){
            if(els[i].indexOf('#') > -1){
                r.root = document.getElementById(els[i].substr(1, els[i].length - 1));
            }
            
            if(els[i].indexOf('.') > -1){
                var e = els[i].split('.');
                r.tag = (e[0].length)? e[0] : null;
                r.className = (e[1].length)? e[1] : null;
            }
            
            if(els[i].indexOf('#') == -1 && els[i].indexOf('.') == -1){
                r.tag = els[i];
            }
        }
        
        return r;
    },
    
    //Get l'element root d'une recherche
    getRootElement: function(){
        var root = arguments[0] || document; 
        if(typeof root == 'string'){
            root = (root.indexOf('#') > -1)? document.getElementById(root.substr(1, root.length - 1)) : document;
        }
        
        return root;
    },
    
    //Check si un élément est contenu dans un tableau
    inArray: function(el, t){
        var r = false;
        for (var i = 0; i < t.length; i++) {
            if (t[i] == el) {
                r = true;
                break;
            }
        }

        return r;
    },
    
    //Sépare les éléments font-weight (normal|bold)
    filterByStyle: function(els){
        var r = { n: [], b: [] }, YDom = YAHOO.util.Dom;
        for (var i = 0; i < els.length; i++) {
            var el = els[i], style = YDom.getStyle(el, 'fontWeight'), p = null;
            p = (style == 'bold' || style == 700) ? r.b : r.n;
            p.push(el);
        }

        return r;
    },
    
    //Recherche des elements à transformer
    getElements: function(elements, root){
        var els = [], root = root || document, YDom = YAHOO.util.Dom;
        for (var i = 0; i < elements.length; i++) {
            var target = elements[i], e = [];
            if (target.indexOf('.') > -1 || target.indexOf('#') > -1) {
                var selector = this.getSelector(target);
                if(!selector.className && selector.root){
                    if(selector.tag){
                        e = selector.root.getElementsByTagName(selector.tag);
                    }
                    else e = [selector.root];
                }
                else e = YDom.getElementsByClassName(selector.className, selector.tag, selector.root || root);
            } else e = root.getElementsByTagName(target);

            if (e.length) {
                for (var j = 0; j < e.length; j++) {
                    if (!this.inArray(e[j], els)) {
                        els.push(e[j]);
                    }
                }
            }
        }

        return this.filterByStyle(els);
    },
    
    //Transformation Cufon
    //
    // @arguments {Object} : liste des elements à transformer compris dans un objet {n: [], b: []}
    // @arguments {String} : nom de la methode à utiliser (replace|refresh)
    //
    _cufon: function(els, fn){
        for(var p in els){
            if(els[p].length){
                Cufon.set('fontFamily', this.fonts[p]);
                Cufon[fn](els[p]);
                for (var e in els[p]){
                    if (YAHOO.env.ua.ie < 8 || YAHOO.env.ua.ie == 0){
                        els[p][e].style.visibility ="visible";
                    }
                }
            }
        }
        
        return this;
    },
    
    // Cufon replace exec.
    //
    // @arguments {Array} : liste des elements (tag|classe)
    // @arguments {HTMLElement} : HTML root cible du remplacement (optionnel)
    //
    replace: function(elements){
        var root = this.getRootElement(arguments[1]), els = this.getElements(elements, root);
        
        return this._cufon(els, 'replace');
    },
    
    // Cufon refresh exec.
    //
    // @arguments {Array} : liste des elements (tag|classe)
    // @arguments {HTMLElement} : HTML root cible du remplacement (optionnel)
    //
    refresh: function(elements){
        var root = this.getRootElement(arguments[1]), els = this.getElements(elements, root);
        
        return this._cufon(els, 'refresh');
    }
};
/*
// ------[ TextArea ]---------------------------------- //

/***********************************************
* Textarea Maxlength script- © Dynamic Drive (www.dynamicdrive.com)
* This notice must stay intact for legal use.
* Visit http://www.dynamicdrive.com/ for full source code
* Example of use
* <asp:TextBox id="txtComment" Runat="server" Width="508px" Rows="10" TextMode="MultiLine" onkeyup="return ismaxlength(this, 50)"></asp:TextBox>
***********************************************/
function ismaxlength(obj, mlength) {
    if (obj.value.length > mlength)
        obj.value = obj.value.substring(0, mlength);
}

// ------[ Page Tracking ]------------------------------------------------- /

SKIDOO.globals.initPageTracking = function (){
    /**
    * SETS pageTrackView on custom element (most likely from Resources
    * @param el HTMLDomElement | Array Array or single dom element to bind the event on
    ***/
    var customViewTracker = function (el, action, oldAction){
        if (checkExisting(el) !== false){
            YAHOO.util.Event.on(el, "click", function(){
                trackPageview(action, oldAction);
                return true;
            });
        };
    };
    /*
    * Set pageTrackEvent on custom element (most likely from Resources
    * @param el HTMLDomElement | Array Array or single dom element to bind the event on
    */
    var customEventTracker = function (el, category, action, path){
        if (checkExisting(el)){
            YAHOO.util.Event.on(el, "click", function(){
                trackPageEvent(category, action, path);
                return true;
            });
        };
    };
    /*
    * Checks if the parameter contains an index after calling a YAHOO.util.Dom.getElementsByClassName
    * and returns the first index. If not existing, returns false.
    */
    var checkExisting = function(el){
        if (typeof el == "object" && typeof el[0] != "undefined"){
            return el[0];
        }else if (typeof el != "undefined" && el.tagName == "A") {
            return el;
        }
        return false;
    }; /**
    * Adds event tracking on different news post lists
    * @param sectionName - will be happended at the end of the event category
    * @param wrapperId - Id of a HTMLDomElement to restrict the scope of the news post research
    ***/
    var newsEventTracking = function(sectionName, wrapperId){
        /*  if cufon is loaded while this function is executing, we must get the content of all <cufontext> tags
            to get the article name */
        if (document.documentElement.className.indexOf("cufon-active") != -1){
            el = YAHOO.util.Dom.getElementsByClassName("fn-link-title","a",wrapperId);
            
            if (checkExisting(el) !== false){
                for(var i in el){
                    var articleNameParts = "";
                    articleNameParts = el[i].getElementsByTagName("cufontext");
                    for(var k in articleNameParts){
                        articleName += " " + articleNameParts[k];
                    }
                    //clicking on the article title
                    customEventTracker(el[i],"News","Read more - " + sectionName,SKIDOO.globals.cultureId +"/"+articleName);
                    elReadMore = YAHOO.util.Dom.getElementsByClassName("link","a",YAHOO.util.Dom.getAncestorByClassName(el[i],"post"));
                    //clicking on readmore
                    customEventTracker(elReadMore,"News","Read more - "+ sectionName,SKIDOO.globals.cultureId +"/"+articleName);
                }
            }
        }else{
            el = YAHOO.util.Dom.getElementsByClassName("fn-link-title","a",wrapperId);
            if (checkExisting(el)){
                for(var i in el){
                    //clicking on the article title
                    customEventTracker(el[i],"News","Read more - " + sectionName,SKIDOO.globals.cultureId +"/"+ el[i].innerHTML);
                    elReadMore = YAHOO.util.Dom.getElementsByClassName("link","a",YAHOO.util.Dom.getAncestorByClassName(el[i],"post"));
                    //clicking on readmore
                    customEventTracker(elReadMore,"News","Read more - " + sectionName,SKIDOO.globals.cultureId +"/"+el[i].innerHTML);
                }
            }
        }
    };
    
    /***
    * @params rootEl String Id of the root UL element
    ****/
     String.prototype.capitalize = function() {
        var s = this.split(' '), l = new String();
        for (var i = 0; i < s.length; i++) {
            var d = s[i].substr(0, 1).toUpperCase();
            s[i] = d + s[i].substr(1);
        }
        return l = s.join(' ');
    };
    //Removes tags and apostrophes so we can pass any innerHTML to tracking
    String.prototype.stripTags = function(){
        return this.replace(/\<.*?\>|\r|\n|\'|\"/g,"");
    };
	var navTracking = function(rootEl){
        var nav = document.getElementById(rootEl);
		var external = false;
        if (nav != null){
            items = nav.getElementsByTagName("li");
            for (var i = 0 ; i < items.length; i++){
                YAHOO.util.Event.on(items[i],"click",function(e, li){
                    if(li.parentNode == li){ // ??? witch case ?
                        firstLevel = secondLevel = li.getElementsByTagName("A")[0].innerHTML.stripTags().capitalize();//(YAHOO.util.Dom.getElementsByClassName("title","span",items[i])[0]).innerHTML.captialize();
                    }else{
                        YAHOO.util.Event.stopPropagation(e);
                        var ancestor = YAHOO.util.Dom.getAncestorByClassName(li, "level-2");
                        if(ancestor){
                            firstLevel = YAHOO.util.Dom.getPreviousSibling(ancestor).innerHTML.stripTags().capitalize();
                            secondLevel = (YAHOO.util.Dom.getElementsByClassName("title","span",li)[0]).innerHTML.stripTags().capitalize();
                        	if(li.id == "gear-riding-gear" ||
	                        	li.id == "gear-accessories" ||
	                        	li.id == "gear-licensed_products" ||
	                        	li.id == "gear-maintenance") {
                        		external = true;
                        	}
                        }
                        else {
                            firstLevel = secondLevel = li.getElementsByTagName("A")[0].innerHTML.stripTags().capitalize();
                        }
                    }
                	
                	if(external) {
                	    trackPageEvent("External Link","BRP Product Site",SKIDOO.globals.cultureId + "/" + secondLevel);
                		}else {
                		trackPageEvent('Top Navigation Click',firstLevel,secondLevel);
                	    }
                },items[i]);
            }
        }
    };
    
    navTracking("main-nav-container");
    
    //BRP Corporate Brochure
    var el = YAHOO.util.Dom.getElementsByClassName("ga-downloadBrochure","div","about-us-landing");
    if (el = checkExisting(el)){
        el = el.getElementsByTagName("a");
        customViewTracker(el,"download_corporate-brochure","download_corporate-brochure");
    }
    
    //CategoryOverview specsheet
    var el = YAHOO.util.Dom.getElementsByClassName("ga-downloadSpecSheet", "a", "pnlTools");
    customViewTracker(el,"download_specifications","download_specifications");
    
    //Extended service brochure download
    var el = YAHOO.util.Dom.getElementsByClassName("ga-bestService", "a", "content-generic");
    customEventTracker(el,"Download","BEST Brochure",SKIDOO.globals.cultureId);
    
    //Brochure download - PAC
    var el = YAHOO.util.Dom.getElementsByClassName("ga-pacBrochure", "a", "content-generic");
    customEventTracker(el,"Download","Parts and Accessories Brochure",SKIDOO.globals.cultureId);
    
    //Homepage news tracking
    newsEventTracking("Homepage","home-news");
    
    //Newsroom news tracking
    newsEventTracking("Newsroom","newsroom");
    
    //footer external link
    /*var otherProducts = document.getElementById("other-brp-products");
    
    if (otherProducts != null){
        var sitemapLinks = otherProducts.getElementsByTagName("A");
        for (var i in sitemapLinks){
             customEventTracker(sitemapLinks[i],"External Link","BRP Product Site",SKIDOO.globals.cultureId + "/" + sitemapLinks[i].innerHTML);
        }
    }*/
    
    /*var store = document.getElementById("gear-accesssories");
    if (store != null){
        var sitemapLinks = store.getElementsByTagName("A");
        for (var i= 0 ; i < sitemapLinks.length;i++){
            
            var title = YAHOO.util.Dom.getElementsByClassName("title", "span", sitemapLinks[i])[0];
            if (typeof title == "undefined"){
                title = sitemapLinks[i].innerHTML;
            }else{
                title = title.innerHTML;
            }    
            customEventTracker(sitemapLinks[i],"External Link","BRP Product Site",SKIDOO.globals.cultureId + "/" + title);
        }
    }*/
};

// ------[ Facebook ]------------------------------------------------- /
/*DEPRECIATED*/
SKIDOO.facebook = {};
SKIDOO.facebook.fbAsyncInit = function() {
    FB.init({ appId: '106191732791694', status: true, cookie: true, xfbml: true });
    /*
    * Analytics trackPageEvent :
    *      Facebook Event function 
    */
    FB.Event.subscribe('edge.create', function(href, widget) {
                                        if (typeof widget.dom.getAttribute("trackingScript") != "undefined"){
                                             
                                            var likeClick = widget.dom.getAttribute("trackingScript");
                                            likeClick = likeClick.split(",");
                                            
                                            if (likeClick.length > 1) {
                                                if (likeClick[0] == "FaceBook Like Package detailed") {
                                                    // Exemple = trackPageEvent('Social', 'FaceBook Like Package detailed', 'en-us/MXZ/XRS');
                                                    likeClick = trackPageEvent('Social', likeClick[0], SKIDOO.globals.cultureId + "/" + likeClick[1]);
                                                } else {
                                                    /*
                                                    *   Find facebookLike element
                                                    */
                                                    var facebookLike = YAHOO.util.Dom.get('facebook-like');
                                                    /*
                                                    *   Find facebookLike HREF value
                                                    */
                                                    facebookLikeHref = facebookLike.getAttribute('href');
                                                    /*
                                                    *   Get the Querystring "showVideo" value if it's available in the Facebook Like Href button
                                                    */
                                                    var GetShowVideo = SKIDOO.facebook.GetParam(facebookLikeHref, "showVideo");
                                                    if (GetShowVideo != "undefined") {
                                                        //Model Exemple =       trackPageEvent('Social', 'FaceBook Like Video', 'en-us/MXZ/XRS/REV-X_EN')
                                                        //Home Exemple =        trackPageEvent('Social', 'FaceBook Like Video', 'en-us/home/LineUp_EN');
                                                        //Technology Exemple =  trackPageEvent('Social', 'FaceBook Like Video', 'en-us/technologies/suspensions/rMotion_EN');
                                                        likeClick = trackPageEvent('Social', likeClick[0], SKIDOO.globals.cultureId + "/" + likeClick[1] + "/" + GetShowVideo);
                                                    }
                                                }
                                            } else {
                                                likeClick = trackPageEvent('Social', 'FaceBook Like', SKIDOO.globals.cultureId);
                                            }
                                            window.eval('(' + likeClick + ')');                                
                                         }
                                     });
                                         
};

SKIDOO.facebook.GetParam = function(path, key) {
    var page = new BRP.QueryUrl.Search(path);
    return unescape(page.getValue(key));
};
SKIDOO.facebook.init = function() {

	for (var i = 0; i < this.elems.length; i++) {

		window.fbAsyncInit = SKIDOO.facebook.fbAsyncInit;

		YAHOO.util.Event.onDOMReady(function() {
			var e = document.createElement('script');
			e.type = 'text/javascript';

			var cultureSplit = SKIDOO.globals.cultureId.split("-");
			if (SKIDOO.globals.cultureId == "fr-ca") {
				SKIDOO.facebook.cultureId = cultureSplit[0] + "_CA";
			}
			else {
				//Facebook don't have en_CA culture so , we need to send US.
				SKIDOO.facebook.cultureId = cultureSplit[0] + "_US";
			}
			//SKIDOO.facebook.cultureId = cultureSplit[0] + "_" + cultureSplit[1].toUpperCase();

			e.src = document.location.protocol +
				'//connect.facebook.net/' + SKIDOO.facebook.cultureId + '/all.js';
			e.async = true;

			fbroot = document.createElement("div");
			fbroot.id = 'fb-root';
			fbroot.appendChild(e);
			window.document.body.appendChild(fbroot);

		});
	};//FOR
};

// ------[ Facebook Like (Deep Linking with Flash) ]------------------------------------------------- /
/*
*   Added the deep Linking with Flash : Call video by javascript link
*/
SKIDOO.widgets.video = {

    el: null,
    elObject: null,
    showVideo: null,
    showLikeTimeout: null,
    playVideoTimeout: null,

    Init: function() {

    	for (var i = 0; i < this.elems.length; i++) {
    		var object = this.elems[i].getAttribute("data-container");
    		if (object) {
    			
                this.el = YAHOO.util.Dom.get(object);

                if (this.el) {
                    /*
                    *   Animation Attributes
                    */
                    this.elObject = new YAHOO.widget.Overlay(this.el,
                    {
                        visible: false,
                        effect: { effect: YAHOO.widget.ContainerEffect.FADE, duration: 0.5 }
                    });
                }

                /*
                *   Deep Linking with Flash : Call video by javascript link
                *       Added class name : "select-video"
                *       Added href : "#" + "multimedia Name"
                *       Render exemple : <a href="#rMotion_EN" class="select-video">Click to launch video</a>
                *       Video available exemple : #rMotion_EN, #SC-5_EN
                */
                function SelectVideo(videoName) {
                    var flashMovie = YAHOO.util.Dom.get("flashHeader");
                    if (flashMovie) {
                        flashMovie.playVideoById(videoName);
                    }
                }

                var elSelectVideoContent = YAHOO.util.Dom.get("content");
                var elSelectVideo = YAHOO.util.Dom.getElementsByClassName("select-video", "a", elSelectVideoContent);

                if (elSelectVideo) {
                    for (i = 0; i < elSelectVideo.length; i++) {
                        YAHOO.util.Event.addListener(elSelectVideo[i], "click",
                       function(e, that) {
                           YAHOO.util.Event.preventDefault(e);
                           SelectVideo(this.href.substring(this.href.indexOf('#') + 1));
                           //We need to see if it's will be the flash or the HTML call the update facebook button function.
                           //that.Update(this.href.substring(this.href.indexOf('#') + 1));
                       }, this);
                    }
                }

                /*
                *   Deep Linking with Flash : Call video in Page Load
                *   Exemple: http://en-us.ski-doo.local.nurun.com/technologies/suspensions.aspx?showVideo=SC-5_EN
                */
                this.showVideo = BRP.QueryUrl.Get("showVideo");
                if (this.showVideo != "undefined") {
                    //Need this condition (timer) to be sure that the flash is ready.
                    var videoName = this.showVideo;
                    this.playVideoTimeout = window.setTimeout(function() {
                        SelectVideo(videoName);
                        window.clearTimeout(this.playVideoTimeout);
                    }, 5000);
                }
    		}
        }
    },

    Action: function() {
        if (this.el) {
            //Create Fade : Object element
            if (YAHOO.util.Dom.getStyle(this.el, 'visibility') == "hidden")
                this.elObject.show();
            else
                this.elObject.hide();
        }
    },

    Show: function() {
        if (this.el) {
            //Show Object element
            this.elObject.show();
        }
    },

    Hide: function() {
        if (this.el) {
            //Hide Object element
            window.clearTimeout(this.showLikeTimeout);
            this.elObject.hide();
        }
    },

    Update: function(videoName, section) {
        //Need this object verification if the "Application.ActivateFacebook" in the Web.Config is "false"
        if (window.FB) {
            if (videoName) {
                /*
                *   Find facebookLike element
                */
                var facebookLike = YAHOO.util.Dom.get('facebook-like');

                /*
                *   Find facebookLike HREF value
                */
                facebookLikeHref = facebookLike.getAttribute('href');

                /*
                *   Set the CSS Position Style in the "socialplugin" element
                */
                var elSocialplugin = YAHOO.util.Dom.getAncestorByClassName(facebookLike, 'socialplugin');
                //if (section != "undefined") {
                if (section) {
                    if (section.toLowerCase() == "sledvideos") {
                        elSocialplugin.style.right = "45px";
                        elSocialplugin.style.top = "400px";
                    } else if (section.toLowerCase() == "features") {
                        elSocialplugin.style.right = "80px";
                        elSocialplugin.style.top = "412px";
                    }
                }
                /*
                *   Get showVideo value if it's available in the Facebook Like Href button
                *       Need this condition to see if we have already this querystring in the location.href
                *           this.showVideo : Set in the Initialize function
                */
                if (this.showVideo != "undefined") {
                    GetShowVideo = this.Get(facebookLikeHref, "showVideo");
                }
                /*
                *   Hide element until the new href is build
                */
                this.elObject.hide();

                /*
                *   Find the href only without the querystring
                */
                facebookLikeHrefWithoutQuerystring = facebookLikeHref.split("?")[0];

                /*
                *   Construct + Set the new href value
                */
                facebookLikeHrefNew = facebookLikeHref.replace(facebookLikeHref, facebookLikeHrefWithoutQuerystring + "?showVideo=" + videoName);
                YAHOO.util.Dom.setAttribute(facebookLike, "href", facebookLikeHrefNew);

                /** Replace the current fb:like tag by a new one containing the new href **/
                var parent = YAHOO.util.Dom.getAncestorByClassName(facebookLike, "like");
                var facebookLikeClone = parent.innerHTML.match(/\<fb\:like.*?>/i) + "</fb:like>";
                parent.innerHTML = facebookLikeClone;
                parent.innerHTML.replace(/href=.*(\s|\>)/, "href='" + facebookLikeHrefNew + "'");
                
                //Show Facebook Like button after the process
                var objFbLike = this.elObject;
                this.showLikeTimeout = window.setTimeout(function() {
                    FB.XFBML.parse();
                    objFbLike.show();
                    window.clearTimeout(this.showLikeTimeout);
                }, 2000);
            }
        }
    },

    Get: function(path, key) {
        var page = new BRP.QueryUrl.Search(path);
        return unescape(page.getValue(key));
    }
};

// ------[ Culture Selection ]------------------------------------------------- /
SKIDOO.pages.cultureSelection = {

    culture: null,
    selectBox: null,
    eventSelector: null,

	Init: function() {
		
    	var eventSelectorID = this.elems[0].getAttribute("data-eventselectorid");
    	var selectBoxID = "select-box";
		/* UserLangage = Browser Language Detection (en or fr) */
		var cultureID = this.elems[0].getAttribute("data-userlangage");
    	
        this.culture = cultureID;
        this.eventSelector = YAHOO.util.Dom.get(eventSelectorID);
        this.selectBox = YAHOO.util.Dom.get(selectBoxID);

        if (this.eventSelector && this.selectBox) {
            var Height = this.selectBox.offsetHeight;
            YAHOO.util.Dom.addClass(this.selectBox, "closed");            

            /*
            *   Added Open/Close BOX Click Event with the Select button
            *   method <Fonction> replaceClass ( el , oldClassName , newClassName )
            */                        
            var easing = YAHOO.util.Easing;
            var duration = 0.5;
            
            var attributesIn = {
               height: { from: 0, to: Height }
            };
            var attributesOut = {
               height: { from: Height, to: 0 }
            };           
            YAHOO.util.Event.addListener(this.eventSelector, "click",
               function(e, that) {
                   YAHOO.util.Event.preventDefault(e);                   
                   var state = (that.selectBox.className.indexOf("opened") != -1) ? false : true;
                   if (state) {
                       var anim = new YAHOO.util.Anim(that.selectBox, attributesIn, duration, easing.easeIn);
                       anim.onStart.subscribe(function() {
                           //Removed the starting flicker...
                           YAHOO.util.Dom.setStyle(that.selectBox, 'height', '0px');
                           YAHOO.util.Dom.replaceClass(that.selectBox, 'closed', 'opened');
                           YAHOO.util.Dom.addClass(that.eventSelector, "selected");
                           return;
                       });
                   } else {
                       anim = new YAHOO.util.Anim(that.selectBox, attributesOut, duration, easing.easeOut);
                       anim.onStart.subscribe(function() {
                           YAHOO.util.Dom.removeClass(that.eventSelector, "selected");
                           return;
                       });
                       anim.onComplete.subscribe(function() {
                           //Can reset the check status of the variable "state".
                           YAHOO.util.Dom.replaceClass(that.selectBox, 'opened', 'closed');
                           return;
                       });
                   }
                   anim.animate();
               }, this);

            /*
            *   Added Analytics Event in link
            */
            /*var a = this.selectBox.getElementsByTagName("a");
            for (var i = 0; i < a.length; i++) {
            	//YAHOO.util.Dom.setAttribute(a, "data-tracking-tag", "ga-cultureSelection");
            	$(a).attr("data-tracking-tag", "ga-cultureSelection");
                YAHOO.util.Event.addListener(a[i], "click",
                   function(e, that) {
                       that.TrackEvent(this);
                   }, this);
            }*/

        } //IF

    }//,

//    TrackEvent: function(element) {
//        /*
//        *   These parameters are set in the back-end web page (.aspx)
//        */
//        var aParams = element.getAttribute('trackEvent');
//        aParams = aParams.split(";");
//        //Exemple : 'Redirections', 'Ski-Doo', 'en-us'
//        try {
//            trackPageEvent(aParams[0], aParams[1], aParams[2]);
//        } catch (err) { }
//    }

};

// ------[ Promotional Season ]------------------------------------------------- /
SKIDOO.pages.promotionalSeason = {
    init: function() {
        
    	for (var i = 0; i < this.elems.length; i++) {
    		var divContainerId = this.elems[i].getAttribute("data-container");
    		if (divContainerId) {
    	
    	        var containerList = YAHOO.util.Dom.get(divContainerId);
                if (containerList) {
                    //Create an array with all anchor in the "divContainerId"
                    var promoLink = containerList.getElementsByTagName("a");
                    if (promoLink) {
                        for (i = 0; i < promoLink.length; i++) {
                            YAHOO.util.Event.addListener(promoLink[i], "click",
                                function() {
                                    return function(e) {
                                        YAHOO.util.Event.preventDefault(e);
                                        //Tracking Google
                                        var aParams = this.getAttribute('trackEvent');
                                        aParams = aParams.split(",");
                                        //Exemple : 'Lightbox', 'Tour Schedule', 'en-US'
                                        trackPageEvent('Lightbox', aParams[0], SKIDOO.globals.cultureId);
                                        if (aParams.length > 1 ) {
                                            var param = aParams[1].replace(/^\s*|\s*$/g,'');
                                            if (param == "pdf") {
                                                window.open(this.href, 'PDF').focus();
                                            } else {
                                                //Go To
                                                parent.location.href = this.href;
                                                //Closed Popup
                                                parent.SKIDOO.globals.bigModalGetPromotionalSeason.hide();
                                            }
                                        } else {
                                            //Go To
                                            parent.location.href = this.href;
                                            //Closed Popup
                                            parent.SKIDOO.globals.bigModalGetPromotionalSeason.hide();
                                        }
                                    };
                                } ());
                        }
                    } //IF promoLink
                } //IF containerList
    		} //IF divContainerId
    	};

        var containerListPopup = parent.YAHOO.util.Dom.get('yui-bigmodalpopup-promotional-season');
        if (containerListPopup) {
            var closeButtonLink = containerListPopup.getElementsByTagName("a")[0];
            if (closeButtonLink) {
                YAHOO.util.Event.addListener(closeButtonLink, "click",
                    function() {
                        return function(e) {
                            YAHOO.util.Event.preventDefault(e);
                            //Tracking Google
                            trackPageEvent('Lightbox', 'Close', SKIDOO.globals.cultureId);
                        };
                    } ());
            }
        } //IF containerList

    } //Init
};

// ------[ Showroom - Vehicle Overview - Video ]------------------------------------------------- /
/*
    Possiblility Value:
    http://www.youtube.com/watch?v=tAqQqNZnkT8&feature=topvideos_music
    http://www.youtube.com/watch?v=z_6JFnAZJDg
    http://www.youtube.com/embed/tAqQqNZnkT8
    http://youtu.be/tAqQqNZnkT8
*/
/*SKIDOO.widgets.multimedia = {
    videoInit: function () {	
                var $videoHolder = $('div.video-holder',$(".pp_pic_holder"));
                if ($videoHolder.length > 0 ){
                    var videoWidth = parseInt($videoHolder.css("width"));
                    var videoHeight = parseInt($videoHolder.css("height"));
                    $videoHolder.ytchromeless({videoWidth:videoWidth, videoHeight:videoHeight});
                }
    },
    /*GalleryLinks: function(holderName){
        $(holderName).find("a[rel^='prettyPhoto']").each(function(){
            var nHref = $(holderName).find(".galleryLink").eq(0).attr("href");
                nHref += "#!"+$(this).attr("rel")+"/0/";
            $(this).attr("href",nHref);
        });
    },
    Init: function(){
            $("#multimedia a[rel^='prettyPhoto']").prettyPhoto({
                    template:'pp_default',
                    animation_speed:'fast',
                    auto_height: 1,
                    custom_markup: ".prettyPhotoContent",
                    changepicturecallback: SKIDOO.widgets.multimedia.videoInit
            });
   
    } //init
};*/

// ------[ Showroom - Vehicle Overview - 360 ]------------------------------------------------- /
/***
Activate the 360 and the "Build Your Own" button in the header. Also swap the background
****/
SKIDOO.widgets.viewMode360 = function() {

	$.each(this.elems, function(key, value) {

		var rotationEngine = $("#header .rotation-engine");
		var buttonsContainer = $("#header .switch-view");
		var button360 = $(".view-360", buttonsContainer);
		var buttonGEQ = $(".view_getaquote", buttonsContainer);
		
		buttonsContainer.click(function() {

			// clone title element in the header to solve z-index problem 
			// THIS DOESN'T SEEM TO WORK IN IE 9 - Solving z-index issue by implemeting the right CSS instead of playing with the dom
			//$("#header-title-canvas").clone(true,true).after($("#page-title")).clone(true,true).appendTo("#header-title-clone");

			// show the Build your own button instead of the 360
			button360.css("display","none");
			buttonGEQ.css("display","block");
			//$("#header .switch-view .view-360,#header .switch-view > .view_getaquote").toggle();
			
			// show the grey/white background behind the 360
			// remove the model picture and show the 360
			//$("#header-360").css("visibility", "visible").show();
			//$("body").css("background","url('/files/neutral/images/headers/header_showroom.jpg') no-repeat center 46px");

			rotationEngine.css("visibility", "visible");

			rotationEngine.show();
			rotationEngine.Engine360({ numAngles: 4, animated: true });

			// avoid any further call to this function. Once the 360 is activated, we cannot go back
			$(this).unbind("click");
		});
		
		//if deep linking is present in the url, show up the 360 on page load
		if (document.location.hash.match( /\/features\// ) != null) {
			buttonsContainer.trigger("click");
		}
		
		/*
            Exeption : 
                SKANDIX WT, SKANDIC SWT, EXPEDITION SE and EXPEDITION LE does'nt have 360 Engine so, we will need to show the
                "Build And price" button instead of "View 360° Features" button.
        */
		var vehicleDisplayName = $(value).data("title");
		var vehicleDisplayNameWhitoutWhiteSpace = vehicleDisplayName.replace( / /g , '');
		
		if (vehicleDisplayNameWhitoutWhiteSpace == "SKANDICWT" ||
			vehicleDisplayNameWhitoutWhiteSpace == "SKANDICSWT" ||
			vehicleDisplayNameWhitoutWhiteSpace == "EXPEDITIONSE" ||
			vehicleDisplayNameWhitoutWhiteSpace == "EXPEDITIONLE") {

				//Delay to activated the 360 after the header title animation
				var enginesTimeout = window.setTimeout(function() {
				    
					//Activated the features angle 0 only.
				    buttonsContainer.trigger("click");
				    
					//Hide the slider bar
				    $(".sliderContainer", rotationEngine).css("display", "none");
				    
					window.clearTimeout(enginesTimeout);
				}, 3000);
			    
		}else {
			// show the 360 button
			button360.css("display","block");
		}

	});
};

// ------[ AddThis SocialMedia Plugin ]------------------------------------------------- /

//DOC ADDTHIS : https://www.addthis.com/help/client-api
SKIDOO.widgets.addThisSocialMedia = function() {
    
	//Google account ID
    var account = $('meta[name=ga-account]').attr("content") || "";
	var elems = this.elems;
	
	/*
    * This meta is in the IncludeMetaCss.ascx
    * Find the page url send by .Net (ex: /home.aspx) 
    */
    //var url = $('meta[name=ga-page-url]').attr("content") || "";
	
    //We "setInterval" to make sure that the "_gaq" is in the DOM to prevent error.
    var timerGaq = window.setInterval(function() {
    	
	    if(window._gat){
		    window.clearInterval(timerGaq);
	
            //Set Analytics
            var pageTracker = [];
            if (window._gat._getTrackerByName) {
                pageTracker = window._gat._getTrackerByName('');
            }
            
            //Set the culture
            var twoLetterIsoLanguageName = SKIDOO.globals.cultureId;
            twoLetterIsoLanguageName = twoLetterIsoLanguageName.substring(0,2);
            
	    	/**
		    *   Set AddThis Config
		    *
		    *       This will allow you to receive AddThis share data in your Google Analytics dashboard as a custom event.
		    *           - data_ga_property
		    *           - data_ga_social
		    *
		    *       Social Interaction Analytics :
		    *       http://code.google.com/intl/fr/apis/analytics/docs/tracking/gaTrackingSocial.html
		    *       http://code.google.com/intl/fr/apis/analytics/docs/gaJS/gaJSApiSocialTracking.html
		    */
            window.addthis_config = {
	            pubid: "xa-4f0c856e74b59bf7",
	            ui_language: twoLetterIsoLanguageName,
	            data_ga_tracker: pageTracker//,
	            /* your GA property ID */
        	    //data_ga_property: account,
	            /* set to true to enable social tracking */
                //data_ga_social: true,
	            //data_track_clickback: true,
        	    //ui_click:true
            };
            //console.log(addthis_config);
	    	
	    	(function() {
			    var ad = document.createElement('script');
			    ad.type = 'text/javascript';
			    ad.src = 'http://s7.addthis.com/js/250/addthis_widget.js#async=1';
			    var $s = $('form script:last').after(ad);
	        })();
	    	
            //If there are more than 1 Sharethis in the page, used this loop around code.
            $.each(elems, function(key, value) {
		    	
            	//Title
		    	var dataTitle = $(value).data("title");
            	if(dataTitle != "") {
            		dataTitle = dataTitle;
            	} else {
                    var metaTitle = document.title;
            		dataTitle = metaTitle;
            	}
            	
            	//Description
            	var dataDescription = $(value).data("description");
            	if(dataDescription != "") {
            		dataDescription = dataDescription;
            	} else {
                    var metaDescription = $('meta[name=description]').attr("content") || "";
            		dataDescription = metaDescription;
            	}
            	
            	//Anchor
            	var dataAnchor = $(value).data("anchor");
            	if(dataAnchor != "") {
            		dataAnchor = "#" + dataAnchor;
            	}
            	
            	//Url
            	var dataUrl = $(value).data("url");
            	if(dataUrl != "") {
            		dataUrl = dataUrl + dataAnchor;
            	} else {
            		var url = window.location.href;
            		//removes the # character
            		if(window.location.hash) {
            			url = url.replace( /#.*/, "");
            		}
            		dataUrl = url + dataAnchor;
            	}
            	
            	$(".addthis_toolbox", value)
                	.attr("addthis:url", dataUrl)
            	    .attr("addthis:title", dataTitle)
            		.attr("addthis:description", dataDescription);
            	
//	    	    var addthis_share = {
//	    	    	dataUrl: dataUrl,
//                  description: dataDescription
//	            };
            	
            });//each
	    	
	    	//We "setInterval" to make sure that the "addthis" object is in the DOM to initialized the plugin.
	        var timerAddthis = window.setInterval(function() {
                if(window.addthis){
	                window.clearInterval(timerAddthis);
                    window.addthis.init();
    	            }
            },50);
	    	
        }//if(window._gat){
    	
    },50);
};
// ------[ Animate Header Plugins : Raphael ]------------------------------------------------- //
SKIDOO.widgets.animateHeaderTitle = {
	
    //$this: $(this),
	$header: $(".animated-header"),
	timer:null,
	$loader:null,
	$visible:null,
	
	onAnimationCompleted: function(){
        //console.log("onAnimationCompleted");
    },
	
	onAnimationHide: function(item) {
    	if($header) {
    		$header.hide();
    	}
	},
	
	onAnimationShowBYOS: function(header, layout) {
		$loader = $("#BYO_loader");
		$(header).hide();
	    if($loader.length>0){
	        timer = window.setInterval(function() {
		        $visible = $loader.css("display") == "none";
		        if ($visible) {
		            $(header).show();
		            header.AnimatedHeader({
				            offsetTop: 0,
				            textWidth: 320,
		            		svgHeight: 140,
		            		svgWidth: 400,
				            layout: layout
			            });
			        window.clearInterval(timer);
			        }
	        }, 100);
        }else{
           $(header).eq(0).show();
        }
	},
	
	onAnimationShowShowroom: function(header, layout) {
		timer = window.setInterval(function() {
			window.clearInterval(timer);
		    $(header).show();
		    header.AnimatedHeader({
                offsetTop: 17,
                textWidth: 275,
                layout: layout
            });
		}, 100);
	},
	
	onAnimationShowDefault: function(header, layout, value) {
		$(header).addClass("default");
			
		timer = window.setInterval(function() {
			window.clearInterval(timer);
            
			$(header).show();
			
			//Calculated the total width of the text;
			var totalWidth,paddingWidth;
			if($(header).data("size")) {
				totalWidth = $(header).data("size");
				paddingWidth = 50;
				totalWidth = Math.round(totalWidth-paddingWidth);
			}else {
			    var $text =  $("h1", header);
		        var textWidth = Math.round($($text).outerWidth());
		        //paddingWidth = 40;
		        //totalWidth = Math.round(textWidth+paddingWidth);
				totalWidth = Math.round(textWidth);
			}
		    header.AnimatedHeader({
                offsetTop: 20,
                textWidth: totalWidth,
                layout: layout
            });
			
			//Call the showroom visibility animation
			SKIDOO.pages.showroom.animate(value);
			
		}, 1000);
	},
	
	onAnimationStart: function(layout, value) {
		//var header, timer, $loader, $visible;
		
		//When the animation of the header is completed
	    this.$header.bind('animationCompleted.AnimatedHeader', this.onAnimationCompleted());
    	
	    //Init Animation Header
		var header = this.$header;

		//Activated the animation when the onProcessHandler BYO is done.
		if(layout == "byos") {
			this.onAnimationShowBYOS(header, layout);
		}
		else if(layout == "showroom") {
			this.onAnimationShowShowroom(header, layout, value);
		} else {
			this.onAnimationShowDefault(header, layout);
		}
	},
	
	init: function() {
		
		//console.log("animateHeaderTitle fn init");
		
		$.each(this.elems, function(key, value) {
			var layout, $layout, animate = true;
			
		    $layout = $(value).data("layout");
			//console.log("$layout = " + $layout);
			if($layout) {
				switch($layout) {
		            case "billboard"://Do Nothing : This animation is start up by "SlideshowBanners.js"
		    	        layout = "billboard";
			            animate = false;
		            break;
	    	        case "byos":
	    		        layout = "byos";
	    	        break;
	    	        case "showroom":
	    		        layout = "showroom";
	    	        break;
		            default:
		    	        layout = "default";
			        break;
				}
			}else {
				layout = "default";
			}
			
			if(animate) {
				SKIDOO.widgets.animateHeaderTitle.onAnimationStart(layout, value);
			}

		});
	}

};
// ------[ Header Width Animation ]------------------------------------------------- //

SKIDOO.pages.showroom = {
	
	//Showroom Header Block Animation
	animate: function(that) {
		var arrayInfo = $(".all-model", that);
		if(arrayInfo) {
		    //Anim Model list
			/*
			*   In InitialState.css file, we put the element outside the window (left: -8000px;) to allow IE8 to render the css3PIE.
			*   Here we need to reposition the element ("left") to it's default place before animation.
			*/
			if ($.browser.msie && $.browser.version < "9.0") {
				var listsTimeout = window.setTimeout(function() {
                        $(".lists", that).css("left", 0).css("visibility", 'visible').show();
                        window.clearTimeout(listsTimeout);
                    }, 1000);
				
				var modelTimeout = window.setTimeout(function() {
                        //Anim Model Image + Specs
				        $(arrayInfo[0]).css("visibility", 'visible').show();
                        window.clearTimeout(modelTimeout);
                    }, 1250);
			}else {
				$(".lists", that).css("left", 0).css("opacity", 0).css("visibility", 'visible').delay(1000).animate(
                    {opacity: 1},
                    {duration: 500});
		        //Anim Model Image + Specs
		        $(arrayInfo[0]).css("opacity", 0).css("display", 'block').css("visibility", 'visible').delay(1250).animate(
                    {opacity: 1},
                    {duration: 250});
			}
		}
	}

};

// ------[ Footer Newsletter ]------------------------------------------------- //
SKIDOO.widgets.footerNewsletter = function() {
    var subscribe = YAHOO.util.Dom.get('subscribe-footer-form');
    
	if (subscribe) {
        var children = YAHOO.util.Dom.getElementsBy(function(el) {
            if (el.tagName.toLowerCase() == 'input') {
                return true;
            }
        }, 'input', subscribe);
		
        var hidden = null, email = null, submit = null, emailValue = null;
        hidden = (children[0])? children[0] : hidden;
        email = (children[1])? children[1] : email;
		submit = (YAHOO.util.Dom.getElementsByClassName("subscribe", "a", subscribe)) ? YAHOO.util.Dom.getElementsByClassName("subscribe", "a", subscribe) : submit;
        emailValue = email.value;
    }

    if(submit) {
        /**
        * Ouverture du popup register newsletter avec envoi
        * De l'adresse email enregistrée dans le champ email
        * En parametre d'url (baseUrl contenu dans input type hidden)
        */
        var submitHandlerNewsletterRegister = function() {
            if (email.value == emailValue) { email.value = ''; }
            var url = hidden.value + email.value;
            if (SKIDOO.globals.NewsletterRegisterOpenPopup(url)) {
                email.value = '';
                }
            return true;
        };

        var EU = YAHOO.util.Event;
        /**
        * Fermeture du popup register newsletter
        * Remettre la valeur par default dans le champ email
        * Besoin de cette intervalle sous IE sinon l'object n'est pas créer.
        * Quand l'object est créer et trouver, l'intervalle est enlevé.
        */
        EU.addListener(window, "load", function() {
            var interval = window.setInterval(function() {
                if (SKIDOO.globals.bigModalGetNewsletter && interval) {                        
                    SKIDOO.globals.bigModalGetNewsletter.beforeHideEvent.subscribe(function() {
                        email.value = emailValue;
                    });                        
                    window.clearInterval(interval);
                    interval = null;
                }
            }, 300);
        });
        
        /**
        * Event listener le onFocus (focusin) and onBlur (focusout) dans le champ email
        * Si contient "@" réinitialise pas le champ.
        */
        EU.addListener(email, "focusin", function(e) {
            e = e || event;
            YAHOO.util.Event.preventDefault(e);
            if (email.value.indexOf("@") == -1)
                email.value = '';
            return false;
        });
        EU.addListener(email, "focusout", function(e) {
            e = e || event;
            YAHOO.util.Event.preventDefault(e);
            if (email.value.indexOf("@") == -1)
                email.value = emailValue;
            return false;
        });            
        
        /**
        * Event listener sur l'entree de donnees dans le champ email
        * Et le keypress == enter -> ouverture popup register newsletter
        */
        EU.addListener(email, "keypress", function(e) {
            e = e || event;
            if (SKIDOO.globals.isEnterKeyPress(e)) {
                YAHOO.util.Event.preventDefault(e);
                submitHandlerNewsletterRegister();
                return false;
            }
            else return true;
        });

        /**
        * Event listener le click du bouton submit
        */
        EU.addListener(submit, "click", function(e) {
            e = e || event;
            YAHOO.util.Event.preventDefault(e);
            submitHandlerNewsletterRegister();
            return false;
        });
    }
};

// ------[ Compare Vehicles ]------------------------------------------------- //

SKIDOO.pages.compareVehicles = {
	init: function() {
		var compareDiv = document.getElementById("compare");
		var allSpans = compareDiv.getElementsByTagName("span");

		for (var x = 0; x < allSpans.length; ++x) {
			if ((allSpans[x].id).indexOf("specs1") != -1) {
				for (var y = 0; y < allSpans.length; ++y)
					if (allSpans[y].id == (allSpans[x].id).replace("specs1", "specs2")) {
						var cell1 = allSpans[y].innerText || allSpans[y].textContent;
						var cell2 = allSpans[x].innerText || allSpans[x].textContent;
						if (cell1 != cell2)
							allSpans[y].style.color = "#6f6f6f";
						break;
					}
			}
		}
	}
};

// ------[ The Ski-Doo Advantage Fall Event ]------------------------------------------------- //
/*
SKIDOO.widgets.specificPrettyPhotoFallEvent = function() {
    $("a.dummyClick").prettyPhoto({
            template:'pp_default',
            animation_speed:'fast',
            default_width: 788,
	        default_height: 593,
    		markup: '<div id="open-house-popup" class="pp_pic_holder"><div class="ppt">&nbsp;</div><div class="pp_content_container"><div class="pp_content"><div class="pp_loaderIcon"></div><div class="pp_fade"><div class="pp_nav"><a href="#" class="pp_arrow_previous">Previous</a><a href="#" class="pp_arrow_next">Next</a></div><a class="pp_close" href="#">Close</a><div id="pp_full_res"></div><div class="pp_details"><p class="pp_description"></p>{pp_social}</div></div></div></div></div><div class="pp_overlay"></div>',
//		    markup: '<div id="open-house-popup" class="pp_pic_holder"> \
//		            <div class="ppt">&nbsp;</div> \
//				    <div class="pp_content_container"> \
//					    <div class="pp_content"> \
//						    <div class="pp_loaderIcon"></div> \
//						    <div class="pp_fade"> \
//						    <div class="pp_nav"> \
//								    <a href="#" class="pp_arrow_previous">Previous</a> \
//								    <a href="#" class="pp_arrow_next">Next</a> \
//						    </div> \
//						    <a class="pp_close" href="#">Close</a> \
//							    <div id="pp_full_res"> \
//							    </div> \
//							    <div class="pp_details"> \
//								    <p class="pp_description"></p> \
//								    {pp_social} \
//							    </div> \
//						    </div> \
//					    </div> \
//				    </div> \
//			    </div> \
//			    <div class="pp_overlay"></div>',
		    social_tools: '',
    		callback: function(){trackPageEvent('Lightbox', 'Open House', 'Close');}
    		
    });
    $("#popup .details a span").each(function(){
        var nspan = $(this).clone();
            $(nspan).addClass("hover");
            $(this).after(nspan);
    });
    $("a.dummyClick").click();
    /*$("#popup h3, #popup h4, #popup h5, #popup h6, ul #popup li, #popup .btn").css({visibility: 'visible'});*//*
    $("#popup div.details div.left a").click(function(){
        trackPageEvent('Lightbox', 'Open House', 'More details');
    });
    $("#popup div.details div.right a").click(function(){
        trackPageEvent('Lightbox', 'Open House', 'Promotion');
    });
};*/

// ------[ OpenHouse/default ]------------------------------------------------- //
SKIDOO.pages.openHouseDefault.init = function() {
    $(".submitlink").click(function(){
        var objlink = $(this).attr("href").replace("javascript:","");
        if($(objlink)) eval(objlink);
        return true;
    });
    $(".submitbox").keypress(function(event){
        if(event.which==13){
            $(".submitlink").click();
            return false;
        }
    });
    if($(".submiterror").length>0) trackPageEvent('Open house','Postal Code','Error');
};
// ------[ OpenHouse/Detail ]------------------------------------------------- //
SKIDOO.pages.openHouseDetail.init = function() {
    var maxSize = 0;
    $("div.ohPanel").each(function(index){
        if($(this).height()>maxSize) maxSize=$(this).height();
    });
    $("div.ohPanel").height(maxSize);

	var entityViewID = $(this.elems[0]).data("eventView");//'<asp:Literal runat="server" ID="litEventView"></asp:Literal>';
    $("h1, h2").each(function(){
        var el = $(this).clone();
        $(this).addClass("screen");
        $(el).addClass("printme");
        $(this).after($(el));
    });
    
    $(window).load(function(){
        $("div.ohPanel").removeClass("load");
        trackPageview('Open house','Event view',entityViewID);
        $(".print").click(function(){
            trackPageEvent('Open house','Event print',entityViewID);
            window.print();
            return false;
        });
        $("ul.ohPanel a").click(function(){
            $("ul.ohPanel a").removeClass("selected");
            $("div.ohPanel").addClass("hidden");
            trackPageEvent('Open house','Event '+$(this).attr("href").replace("#",""),entityViewID);
            $($(this).attr("href")).removeClass("hidden");
            $(this).addClass("selected");
            return false;
        });
        $("ul.ohPanel a").eq(0).click();
        $("h2, h3").css("visibility","visible");
    });
};
// ------[ OpenHouse/default ]------------------------------------------------- //
SKIDOO.pages.openHouseList.init = function() {
    trackPageEvent('Open house','Postal Code','Success');
    $("#eventList table tr").hover(
        function(){
            $(this).addClass("hover");
        },function(){
            $(this).removeClass("hover");
        }
    );
    $("#eventList table tr td").click(function(){
        var href = $(this).parent("tr").find("a").eq(0).attr("href");
        window.location = href;
        return false;
    });
};

// ------[ Event List ]------------------------------------------------- //
/* Callback JS - Call after Backend Update Panel is done to rebind overlay event click */
var bindEventListAfterUpdate = function(){
    SKIDOO.globals.bindYUIBigModalPopUp();
};

// ------[ Get A Quote ]------------------------------------------------- //
SKIDOO.pages.getAQuote = {

	checkValidatorCallouts: function(){
    	var i;
    	var elementsInError = Array();
    	// if (typeof Page_Validators != "undefined"){
    	//Page_Validators = send by .Net directly in the current page.
    	for (i = 0; i < Page_Validators.length; i++)
    	{
    		var inputControl = document.getElementById(Page_Validators[i].controltovalidate);
    		if (inputControl != null) {
    			if (!Page_Validators[i].isvalid)
    			{
    				/**
                        add class is done afterwards using this array because one control can have multiple validators 
                        and we may remove the classname if the last validator for this field is valid
                    **/
    				elementsInError.push(inputControl);
    			} else {
    				YAHOO.util.Dom.removeClass(inputControl, 'error');
    			}
    		}
    	}
    	for (var i in elementsInError) {
    		YAHOO.util.Dom.addClass(elementsInError[i], 'error');
    	}
    	// }
    }
};
//We need to exclude this global function outside the "SKIDOO.pages.getAQuote" method because is call by the .Net sender.
function pageLoad(sender, args){
    YAHOO.util.Event.onDOMReady(function(){
        YAHOO.util.Event.on( document.getElementById("content-generic").getElementsByTagName("input"),"focus",SKIDOO.pages.getAQuote.checkValidatorCallouts);
        YAHOO.util.Event.on( document.getElementById("content-generic").getElementsByTagName("select"),"focus",SKIDOO.pages.getAQuote.checkValidatorCallouts);
    });
    if (args.get_isPartialLoad()){
        SKIDOO.globals.bindYUIModalPopUp();
        //SKIDOO.pages.fontReplace();
        SKIDOO.pages.getAQuote.checkValidatorCallouts();
    }
 };

 // ------[ SheffieldFinancing.aspx ]------------------------------------------------- //
SKIDOO.pages.sheffieldFinancing = {

	checkValidatorCallouts: function(){
    	var i;
    	var elementsInError = Array();
		//console.log(Page_Validators);
    	for (i = 0; i < Page_Validators.length; i++)
    	{
    		var inputControl = document.getElementById(Page_Validators[i].controltovalidate);
    		if (inputControl != null) {
    			if (!Page_Validators[i].isvalid)
    			{
    				/**
                        add class is done afterwards using this array because one control can have multiple validators 
                        and we may remove the classname if the last validator for this field is valid
                    **/
    				elementsInError.push(inputControl);
    			} else {
    				$(inputControl).removeClass('error');
    			}
    		}
    	}
		for (var i in elementsInError) {
			$(elementsInError[i]).addClass('error');
		}
	}
};
//We need to exclude this global function outside the "SKIDOO.pages.sheffieldFinancing" method because is call by the .Net sender.
function pageLoad(sender, args){
    $(document).ready(function(){
    	var container = document.getElementById("content-generic");
    	if(container){
    	    YAHOO.util.Event.on( container.getElementsByTagName("input"),"focus",SKIDOO.pages.getAQuote.checkValidatorCallouts);
    	}
    	
        $("input, select","#content-generic").focus(SKIDOO.pages.sheffieldFinancing.checkValidatorCallouts);
    });
    /*$("#subnav a[rel^='prettyPhoto']").prettyPhoto({
        template:'pp_default',
        animation_speed:'fast',
        social_tools:''
    });*/
}

// ------[ Ski-Doo Ice Block Reveal ]--------------------------------------------- //

// ------[ FB Share de chacun des tabs - Le contenu est défini dans le html  ]--------------------------------------------- //
$(function () {
    $(".share").click(function (e) {
        var message = $(this).parent().parent().parent().find(".share-content span.message").html();
        var name = $(this).parent().parent().parent().find(".share-content span.name").html();
        var caption = $(this).parent().parent().parent().find(".share-content span.caption").html();
        var description = $(this).parent().parent().parent().find(".share-content span.description").html();
        var share_url = $(this).parent().parent().parent().find(".share-content span.share_url").html();
        var picture = $(this).parent().parent().parent().find(".share-content span.picture").html();
        var box_title = $(this).parent().parent().parent().find(".share-content span.box_title").html();
        $(this).easyfb().share({
            message: message,
            name: name,
            caption: caption,
            //{*actor*} is only available in caption param
            description: description,
            link: share_url,
            picture: picture,
            media: [{
                type: 'image',
                src: picture,
                href: share_url
            }]
        });
    });

});

/******* PUBLIC VARS *******/

var $images;
var $container;
var $overlay;
var numImages;
var $preloader;
var targetAnimationFrame;
var user;
var siteLocalisation;


SKIDOO.pages.enginetechnologies.init = function() {

	SKIDOO.widgets.videoYTIframeTracking(".video", true);
};

SKIDOO.widgets.videoYTIframeTracking = function(className, replaceObjectTag) {

	var $videos = $($.find(className));
	if (replaceObjectTag) {
		//console.log("=================");

		$videos.each(function(index) {
			//console.log($(this).find('object'));
		});


	}
};


SKIDOO.pages.iceblockreveal.init = function () { 
	if(!window.console){
		window.console = {
			log: function(){
				return true;
				}
		};
	}
    /* Set Deeplinkg on feature tabs */
    new SKIDOO.widgets.IceBlockDeeplinking();
    new SKIDOO.widgets.IceBlockIntroAnimationCompleted();
};

SKIDOO.widgets.IceBlockIntroAnimationCompleted = function () {

    $(".header_title").animate({
        top: -55
    }, 0, "easeOutExpo");
    $(".header_title").delay(600).animate({
        top: 0
    }, duration, "easeOutExpo");
    
    var duration = 500;
    var timout = 0;
    //********** REAVEAL OPPACITY FB LOGIN + SCROLL TO VIDEO + HIDE THE ANIM  ***********/
    $(".reveal-scroll-feature").css("opacity", "0").delay(timout).css("opacity", "1");
    $(".reveal-login-feature").css("opacity", "0").delay(timout).css("opacity", "1");
    $(".rotation-engine").css("display", "none");
    $(".loader").parent().css("opacity", "1").fadeOut(0);

    if($(".rotation-engine-images").children().length > 2){
        $(".loader").parent().delay(timout).fadeIn(duration);
        try{
            var rotationEngine = $(".rotation-engine");
        	//console.log(" rotationEngine l: " + rotationEngine);
            rotationEngine.Engine360_iceblock({
               numAngles: 5,
               rotationSpeed: 1200,
               rotationEasing: "easeOutExpo"
            });
            rotationEngine.bind('ready.engine360', function(e) {
            	//console.log("360 engine is ready");
                $(".rotation-engine").css("display", "block");
                $(".loader").parent().fadeIn(0).delay(timout).fadeOut(duration);
            });
        }
        catch(err){
            //console.log("Error trying to instantiate Engine 360.");
        }
    }else{

    }
};
SKIDOO.widgets.IceBlockDeeplinking = function () {
    var $tabs = $('.nav ul li');
    var $tabsLink = $('.nav ul li a');
    var $content = $('.features .content-wrapper');
    var currentTabID = $('.nav ul li a:first').attr('href'); /* Address handler */
    $.address.init(function (event) {
        var targetDeeplink = currentTabID.replace("#", "");
        $.address.value(targetDeeplink);
    }).change(function (event) { /* If there's no deeplinking, activate the first tab */
        if ($.address.value() == '/' || $.address.value() == '') {
            currentTabID = $('.nav ul li:first a').attr('href').split("/")[1];
        } else { /* Get the current tab id from the query string */
            currentTabID = $.address.value().split("/")[2];
        } /* Remove selected class from all tabs */
        $tabs.removeClass('selected'); /* Set the current tab */
        $currentTab = $tabs.find('a[href="#tab/' + currentTabID + '"]').parent(); /* Add selected class to the active tab */
        $currentTab.addClass('selected');

        var $hiddenContent = $('.features .content-wrapper:not(#' + currentTabID + ')');
        var $content = $('.features .content-wrapper[id="' + currentTabID + '"]');
        $content.css({
            'display': 'block'
        });
        $hiddenContent.css('display', 'none'); /* Append the video player based on the video url href */
        $rightContent = $content.find('.right-content');
        $leftContent = $content.find('.left-content');
        $videoLink = $rightContent.find("span.video");
        if ($videoLink.css('display') != "none") {
            var videoID = ytExtractId($videoLink.text());
            $rightContent.append('<iframe width="467" height="297" src="http://www.youtube.com/embed/' + videoID + '?wmode=opaque&version=3&theme=light&autohide=0&showinfo=0" frameborder="0" allowfullscreen></iframe>');
            $videoLink.css('display', 'none');
        }
    }).externalChange(function (event) {}).history(true);

    function ytExtractId(youtubeUrl) {
        var origUrl = youtubeUrl;
        try {
            youtubeUrl = youtubeUrl.replace(/(http\:\/\/www.youtube.com\/watch.*?(&|\?)v\=(.*)?(&|$)?)|(http\:\/\/www.youtube.com\/embed\/(.*))|(http:\/\/youtu.be\/(.*))/, "$3$6$8");
            if (youtubeUrl != origUrl) {
                //filter the extra parameters that can be found in the id                        
                youtubeUrl = youtubeUrl.replace(/(.*)?&.*/, "$1");
                return youtubeUrl;
            } else {
                return false;
            }
        } catch (e) {
            return false;
        }
    }
};

// ------[ Enhancements ]------------------------------------------------- //

SKIDOO.brpProducts = function() {
	//Creating Expandable Menu for BRP Products
    BRPTools.clickableMenus.register("#BRPProducts", []);
    BRPTools.clickableMenus.register("#BRPProducts", $('#menu-overlay'));
};
SKIDOO.changeCountry = function() {
	//Creating Expandable Menu for Country Selector
    BRPTools.clickableMenus.register("#footer-language .change-country");
    BRPTools.clickableMenus.register("#pnl_optiongroups");
};

/*SKIDOO.initPrettyPhoto = function() {
	//console.warn("prettyPhoto");
	//console.warn(this.elems);
	$.each(this.elems, function(key, value) {
		//console.warn(this);
		/*
		    Available elements
		       SlideshowBanners.ascx - Billboard :      #header a[rel^='prettyPhoto']
		       ScrollerPromotion.ascx - Promotion box : #promotion-box a[rel^='prettyPhoto']
		*//*
		$(" a[rel^='prettyPhoto']", this).prettyPhoto({
            template:'pp_default',
            animation_speed:'fast',
            auto_height: 1,
            custom_markup: ".prettyPhotoContent",
			social_tools:false,
            changepicturecallback: SKIDOO.widgets.multimedia.videoInit
        });
		
	});
};*/

/*
    ScrollerPromotion.ascx
*/
SKIDOO.initScrollerPromotion = function() {
	//console.warn("scrollerPromotion");
	//console.warn(this.elems);
	$.each(this.elems, function(key, value) {
	    $("#tabs").tabs();
        // Promobox with Google Analytic Tracking
        // ( you absolutely need to pass a trackingName + googleAccount otherwise nothing will be tracked)
        $('.promobox').Promobox({ numSlideOnScreen: 3, animated: true, tracking: true, easingType: "easeInOutExpo", delayTime: 50 }).bind('promobox_change', function(e) {});
	});
};

/*
    VideoGallery.aspx
    Ou partout ou il y a un overlay video ou photo
*/
SKIDOO.initScrollerVideo = function() {
    $.each(this.elems, function(key, value) {
        var slideCount = ($(value).attr("data-slide-count")) ? parseInt($(value).attr("data-slide-count")) : 4;
        //console.log(value);
        $(value).Promobox({ numSlideOnScreen: slideCount, animated: true, tracking: true, easingType: "easeInOutExpo", delayTime: 50 }).bind('video-player-nav_change', function(e) {});
    });
};

//Showroom
SKIDOO.initGalleryOverlays = function() {
    var firstItem = new Array();
    $.each(this.elems, function(key, value) {
        firstItem.push(null);
        $(value).find("a").click(function(){
            var galleryID = $(this).attr("href").split("#");
                galleryID = "#"+galleryID[1];

            var itemCount = $(galleryID+" .thumbs div>li>div").length;
            if(itemCount>0){ 
                $.fancybox({
                    'padding'		: 0,
                    'href'          : galleryID,
                    'type'			: 'inline'
                });

                firstItem[key] = (firstItem[key]) ? firstItem[key] : $(galleryID+" .thumbs div>li>div").eq(0);
            
                var firstIndex = $(galleryID+" .thumbs div>li>div").index(firstItem[key]);
                var items = $(galleryID+" .thumbs div>li>div");
                
                if(firstIndex!=0){
                    $(galleryID+" .thumbs div>li").each(function(index){              
                        $(this).find(">div").remove();
                        $(this).append($(items).eq(firstIndex));
                        firstIndex++;
                        if(firstIndex>=itemCount) firstIndex=0;
                    });
                }
                $(firstItem[key]).click();
            	
                //Removes tags and apostrophes so we can pass any innerHTML to tracking
                String.prototype.stripTags = function(){
                    return this.replace(/\<.*?\>|\r|\n|\'|\"/g,"");
                };
            	
            	//Initialise Analytics on Resolution List
	            var elems = $(".resolutions-list a");
	            $.each(elems, function(key, value) {
                    $(value).click(function(e)
                    {
	                    var $self = $(this);
	                    var category =  $self.parents(".video-gallery-box").find('h2').text();
	                    var $pictureName = $self.attr('href');
	                    $pictureName = $pictureName.substring($pictureName.lastIndexOf("/")+1);
	                    //Exemple: (Pictures*Download*en-us/MXZ X RS/MXZ_XRS_01_wallpaper.jpg)
                        trackPageEvent('Pictures', 'Download', SKIDOO.globals.cultureId + "/" + category.stripTags() + "/" + $pictureName);
                    });
                });
            	
            }
            return false;
        });
    	
    });
	
    $(window).load(function(){
        $("#overlays").hide();
    });
};

//Wallpaper
SKIDOO.initResolutionList = function() {
    if(typeof lblOtherResolutions == "undefined") lblOtherResolutions = "Other Resolutions";
    $.each(this.elems, function(key, value) {
        $(value).picDownloadResolutionDetect({dectectedText : ""});
        $(value).each(function(){
            var $that = $(this);
        	$that.append("<li class='otherResolutionsList'><span style='display:block'>" + lblOtherResolutions + "</span><ul class='show-on-hover'></ul></li>");
            var items = $(".otherResolutions",this).detach().appendTo($(".otherResolutionsList ul",this));
        });
    });  
};

//Gallery Vidéo : Deep linking (Hash)
SKIDOO.initVideoAutoLoad = function() {
    var popVideo = window.location.href.split("#");
        popVideo = popVideo[popVideo.length-1];
        popVideo = $(this.elems).find('a[href*="watch?v='+popVideo+'&"]');
        popVideo = popVideo.clone();
            
    $(popVideo).click(function() {
        $.fancybox({
            'padding'		: 27,
            'width'		    : 873,
            'height'		: 474,
            'href'			: this.href.replace(new RegExp("watch\\?v=", "i"), 'v/')+"&theme=light",
            'type'			: 'swf',
            'swf'			: {
                 'wmode'		    : 'transparent',
                'allowfullscreen'	: 'true'
            }
        });
        
        return false;
    });
    $(popVideo).eq(0).click();
};

//Home : Billboard
SKIDOO.initVideoPopup = function() {
   $.each(this.elems, function(key, value) {
        $(value).find("a[href*='www.youtube.com']").click(function() {
            $.fancybox({
                'padding'		: 27,
                'width'		    : 873,
                'height'		: 474,
                'href'			: this.href.replace(new RegExp("watch\\?v=", "i"), 'v/')+"&theme=light",
                'type'			: 'swf',
                'swf'			: {
                     'wmode'		    : 'transparent',
                    'allowfullscreen'	: 'true'
                }
            });
            
            return false;
        });
    });
};
/*
    Technologies : Suspensions
*/
SKIDOO.initSuspensionVideo = function() {
	$.each(this.elems, function(key, value) {
	    $(value).find(".videobox-content .panel-content a").click(function(){
	        var index = $(value).find(".videobox-content .panel-content a").index(this);
	        var videoID = $(this).attr("href").split('?v=')[1].split('&')[0];
	        var embedObj = "<object id='ytPlayerHolder"+index+"' style='height: 578px; width: 908px'><param name='movie' value='http://www.youtube.com/v/"+ videoID +"?version=3&theme=light&showinfo=0&rel=0&enablejsapi=1&autoplay=1'><param name='allowFullScreen' value='true'><param name='allowScriptAccess' value='always'><param name='wmode' value='opaque'><embed src='http://www.youtube.com/v/"+ videoID +"?version=3&theme=light&showinfo=0&rel=0&enablejsapi=1&autoplay=1' type='application/x-shockwave-flash' allowfullscreen='true' allowScriptAccess='always' width='908' height='578' wmode='opaque'></object>";

	    	var videoName = $(this).parents('.videobox-content').data("tracking-label");
	    	trackPageEvent('Video', 'Play', SKIDOO.globals.cultureId + "/Suspension/" + videoName);
	        
	    	$("#videoHolder").html(embedObj);
	        return false;
	    });
	});
	/*$.each(this.elems, function(key, value) {
        $(value).Promobox({ numSlideOnScreen: 4, animated: true, tracking: true, easingType: "easeInOutExpo", delayTime: 50 }).bind('video-player-nav_change', function(e) {});
	});*/
};

/*
    EngineTechnologies2Strokes.aspx et EngineTechnologies4Strokes.aspx
*/
SKIDOO.initExpander = function() {
	$("#EngineTechnologies .expander a").click(function(){
        var thisID = $(this).parents("li:first").attr("id");
        var opened = $(this).parents("li:first").hasClass("selected");
        $(this).parents("div:first").find(".selected div:first").slideUp();
        if(!opened) window.location = "#"+thisID;
        $(this).parents("div:first").find("li").removeClass("selected");
        if(!opened){
            $(this).parents("li:first").addClass("selected");
            $(this).next("div:first").slideDown(function(){
                window.location = "#"+thisID;
            });
        }
        return false;
    });
    $("#EngineTechnologies .expander").each(function(){
        $(this).find("li:first").addClass("selected");
        $(this).find("div:first").css("display","block");
    });
    $(window).load(function(){
        $("#EngineTechnologies .expander a[href="+window.location.hash+"]").click();
    });
};

SKIDOO.initAnalytics = function(enhancementRoot) {
	$(this.elems).each(function() {
		
		/**
		*   The implements analytics plugin, using one ga account.
		*   NEW ACCOUNT : Master profile tracking ID
		*/
		/*
		window._gaq = window._gaq || [];
		//These meta are in the IncludeMetaCss.ascx
		var account = $('meta[name=ga-account]').attr("content") || "";
		var domain = $('meta[name=ga-domain]').attr("content") || "";
		//_gaq.push(function() {var pageTracker = _gat._getTracker(account);});
		_gaq.push(['_setAccount', account]);
		_gaq.push(['_setDomainName', domain]);
        _gaq.push(['_setAllowLinker', true]);
        _gaq.push(['_setAllowHash', false]);
        _gaq.push(['_setDetectFlash', false]);
        _gaq.push(['_setDetectTitle', false]);
        _gaq.push(['_trackPageview']);
		*/
		
		/**
		*   The implements analytics plugin, using two ga account.
		*   DOC : http://code.google.com/intl/fr-FR/apis/analytics/docs/tracking/asyncUsageGuide.html#MultipleCommands
		*/
		window._gaq = window._gaq || [];
		//These meta are in the IncludeMetaCss.ascx
		var account = $('meta[name=ga-account]').attr("content") || "";
		var domain = $('meta[name=ga-domain]').attr("content") || "";
		var accountOld = $('meta[name=ga-account-old]').attr("content") || "";
        
		//Set Analytics
		_gaq.push(
            /**
	        *   NEW ACCOUNT : Master profile tracking ID
	        */
        	['_setAccount', account],
            ['_setDomainName', domain],
            ['_setAllowLinker', true],
            ['_setAllowHash', false],
            ['_setDetectFlash', false],
            ['_setDetectTitle', false],
            ['_trackPageview'],
        	
        	/**
	        *   OLD ACCOUNT : Subdirectory profile tracking ID
	        */
        	['old._setAccount', accountOld],
            ['old._setDomainName', domain],
            ['old._setAllowLinker', true],
            ['old._setAllowHash', false],
            ['old._setDetectFlash', false],
            ['old._setDetectTitle', false],
            ['old._trackPageview']
        );
		
		/*Set the data to debug mode*/
		var gaMode = ($('meta[name=ga-debug]').attr("content") == "true") ? "/u/ga_debug.js" : "ga.js";
		//var gaMode = ($(this).data("ga-debug") == "true") ? "/u/ga_debug.js" : "ga.js";
		
		(function() {
			var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
			ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/' + gaMode;
			var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
		})();

		/*initialising a plugin for each tracker*/
		//Default
		$("body").tracking();
        
        /* !important, the old account is initialized after because we want it to execute after the default account.
        * For example, trackEvent on an external link have some chances to be lost, which has more chance to occur
        * to the latest tracking call. by triggering the default account first, we are giving it priority.
        */
        $("body").tracking({trackerId:"old"});
		
	});
};

/*
*    Group : data-enhance="ajaxTabs"
*    ID : 	 Nom unique pour chaque appel. (Ne s'applique pas a élément du DOM)
*/

/* Culture Selection */
$.enhance(SKIDOO.pages.cultureSelection.Init,{title: "Added Open/Close BOX Click Event with the Select button", group:"cultureSelection", id:"CultureSelection"});

/*
SlideshowBanners.ascx
ScrollerPromotion.ascx
*/
//$.enhance(SKIDOO.initPrettyPhoto,{title: "Activating Media Gallery with PrettyPhoto", group:"prettyPhoto", id:"PrettyPhoto"});

/* ScrollerPromotion.ascx */
$.enhance(SKIDOO.initScrollerPromotion,{title: "Loading Promotion Box", group:"scrollerPromotion", id:"ScrollerPromotion"});

/* VideoGallery.aspx */
$.enhance(SKIDOO.initScrollerVideo,{title: "Loading Video List", group:"scrollerVideo", id:"ScrollerVideo"});

/* Suspensions.aspx */
$.enhance(SKIDOO.initSuspensionVideo,{title: "Loading Suspension Videos", group:"suspensionVideo", id:"SuspensionVideo"});

/* EngineTechnologies2Strokes.aspx et EngineTechnologies4Strokes.aspx */
$.enhance(SKIDOO.initExpander,{title: "Loading Engine Technologies Expander", group:"expander", id:"EngineTechnologies"});

/* Footer.ascx */
$.enhance(SKIDOO.widgets.footerNewsletter,{title: "Loading Footer Newsletter Subscribe", group:"footerNewsletter", id:"FooterNewsletter"});
//$.enhance(SKIDOO.widgets.specificPrettyPhotoFallEvent,{title: "Loading Specific PrettyPhoto Fall Event", group:"specificPrettyPhotoFallEvent", id:"SpecificPrettyPhotoFallEvent"});

/* Analytics */
$.enhance(SKIDOO.initAnalytics,{title: "Loading Google Analytics", group:"analytics", id:"Analytics"});

/* Previous Years */
$.enhance(SKIDOO.pages.previousYears.init,{title: "Loading Previous Years", group:"previousYears", id:"PreviousYears"});

/* Promotional Season */
$.enhance(SKIDOO.pages.promotionalSeason.init,{title: "Loading Promotional Season", group:"promotionalSeason", id:"PromotionalSeason"});

/*
*    Video Facebook Like :
*        SerieOverview.aspx
*        CategoryOverview.aspx
*/
$.enhance(SKIDOO.widgets.video.Init,{title: "Loading Facebook Button Count (video)", group:"videoFacebookLike", id:"VideoFacebookLike"});

/* Facebook Social Plugin */
//$.enhance(SKIDOO.facebook.init,{title: "Loading Facebook Social Plugin", group:"facebookSocialPlugin", id:"FacebookSocialPlugin"});

/* Product Compare Vehicles Colums */
$.enhance(SKIDOO.pages.compareVehicles.init,{title: "Loading Product Compare Vehicles Colums", group:"productCompare", id:"ProductCompare"});

/* OpenHouse/Default.aspx */
$.enhance(SKIDOO.pages.openHouseDefault.init,{title: "Loading Open House Default", group:"openHouseDefault", id:"OpenHouseDefault"});
/* OpenHouse/Detail.aspx */
$.enhance(SKIDOO.pages.openHouseDetail.init,{title: "Loading Open House Detail", group:"openHouseDetail", id:"OpenHouseDetail"});
/* OpenHouse/List.aspx */
$.enhance(SKIDOO.pages.openHouseList.init,{title: "Loading Open House List", group:"openHouseList", id:"OpenHouseList"});

/* GetAQuote.aspx */
$.enhance(SKIDOO.pages.getAQuote.checkValidatorCallouts,{title: "Loading Get A Quote Validator Form", group:"getAQuote", id:"GetAQuote"});

/* SheffieldFinancing.aspx */
$.enhance(SKIDOO.pages.sheffieldFinancing.checkValidatorCallouts,{title: "Loading Sheffield Financing Validator Form", group:"sheffieldFinancing", id:"SheffieldFinancing"});

/* Video Gallery */
$.enhance(SKIDOO.pages.videos.init,{title: "Loading Video Gallery List", group:"videoGallery", id:"VideoGallery"});
$.enhance(SKIDOO.initGalleryOverlays,{title: "Loading Gallery Overlays", group:"galleryOverlay", id:"GalleryOverlay"});
$.enhance(SKIDOO.initResolutionList,{title: "Loading Resolution List", group:"resolutionList", id:"ResolutionList"});
$.enhance(SKIDOO.initVideoAutoLoad,{title: "Detect Video Auto Load", group:"videoAutoLoad", id:"VideoAutoLoad"});
$.enhance(SKIDOO.initVideoPopup,{title: "Detect Video Popup", group:"videoPopup", id:"VideoPopup"});

/* BRP Products */
$.enhance(SKIDOO.brpProducts,{title: "Loading Header BRP Products", group:"brpProducts", id:"BRPProducts"});

/* Change Country */
$.enhance(SKIDOO.changeCountry,{title: "Loading Footer Change Country Drop Down list", group:"changeCountry", id:"ChangeCountry"});

/* Main navigation Delay */
$.enhance(SKIDOO.widgets.navigation.MenuDelayer,{title: "Loading Main navigation Delay", group:"mainNavigationDelay", id:"MainNavigationDelay"});

/* Hover Tips */
$.enhance(SKIDOO.widgets.tips.HoverAnim,{title: "Loading Hover Tips", group:"hoverTips", id:"HoverTips"});

/* Video Multimedia : for Key Features 
$.enhance(SKIDOO.widgets.multimedia.Init,{title: "Loading Video Multimedia - Adding youtube overview", group:"videoMultimedia", id:"VideoMultimedia"});*/

/* Header view mode for 360 */
$.enhance(SKIDOO.widgets.viewMode360,{title: "Loading Header view mode for 360", group:"viewMode360", id:"Engine360"});

/* AddThis */
$.enhance(SKIDOO.widgets.addThisSocialMedia,{title: "Loading AddThis", group:"addThisSocialMedia", id:"AddThisSocialMedia"});

/* Animate Header Plugins : Raphael */
$.enhance(SKIDOO.widgets.animateHeaderTitle.init,{title: "Loading Animate Header Plugins", group:"animateHeader", id:"AnimateHeaderPlugins"});

/* Ice Block Reveal : MXZ */
$.enhance(SKIDOO.pages.iceblockreveal.init,{title: "Loading Ice Block Reveal", group:"iceBlockReveal ", id:"IceBlockReveal "});

/* Enhance Tracking Video ENGINE TECHNOLOGIES */ 
//$.enhance(SKIDOO.pages.enginetechnologies.init,{title: "Loading Video YT Player Tracking", group:"videoYtPlayer", id:"videoYtPlayer "});

/*
* Init all method
*/
$(document).ready(function(){
	window.cultureID = document.documentElement.lang;
	SKIDOO.globals.cultureId = document.documentElement.lang;
	
	//Add these elements to allow the general enhance function call in all web page.
	$("body").addClass("enhance");
	$("body").attr("data-enhance", "culture mainNavigationDelay brpProducts analytics changeCountry animateHeader");
	
	//Exeption if we want to add another enhance tag if there is already tags el.
    //if($('meta[name=ga-page-url]').attr("content") == "/default.aspx"){
    //	var tag = $("body").attr("data-enhance");
    //	$("body").attr("data-enhance", tag + " cultureSelection");
    //}
	
	/*
        We force prettyPhoto to initialise to be able to call the API call of "Open".
        If we do not make this call and there is no prettyPhoto gallery, a direct call to $.prettyPhoto.open() fails
        Make fake init call for prettyPhoto initalization
	*/
    //$("#PPbluffTagInit").prettyPhoto();

	//Call Yahoo YUI Initialization Javascript
	SKIDOO.pages.all.init();
	
	//Call jQuery Initialization Javascript
	var isEnhanceEnabled = (typeof $.enhance !== "undefined") ;
    if (isEnhanceEnabled){
    	//console.log("isEnhanceEnabled");
	    $(document).enhance();
	 }

	//Enhance est déjà exécuté donc, les valeurs d'object seront vide.
	//$(document).enhance();
});

/*
*   Analytics Call - Inline :
*       We will keep this function just in case anothers events are bind like inline call inside some method.
*
*       We have "setInterval" to make sure that the "_gaq" is in the DOM to prevent error.
*/
function trackPageview(action, oldAction){
	try {
    	/*
    	* This meta is in the IncludeMetaCss.ascx
    	* Find the page url send by .Net (ex: /home.aspx) 
    	*/
    	var url = $('meta[name=ga-page-url]').attr("content") || "";
		/*var timerView = window.setInterval(function() {
    		if(window._gaq && window._gaqOld){
    			//_gaq.push(['_trackPageview', url+'/'+action]);
    			_gaq.push(
    				['_trackPageview', url+'/'+action],
    				['old._trackPageview', url+'/'+action]
    			);
    			window.clearInterval(timerView);
            }
        },50);*/
		//console.info("trackPageview");
		_gaq.push(
				['_trackPageview', url+'/'+action],
				['old._trackPageview', url+'/'+action]
			);
    } catch(err) {}
}
function trackPageEvent(category, action, label){
    try {
    	/*var timerEvent = window.setInterval(function() {
    		if(window._gaq && window._gaqOld){
    			//_gaq.push(['_trackEvent', category, action, label]);
    			_gaq.push(
    				['_trackEvent', category, action, label],
    				['old._trackEvent', category, action, label]
    			);
    			window.clearInterval(timerEvent);
            }
        },50);*/
    	//console.info("trackPageEvent");
    	_gaq.push(
				['_trackEvent', category, action, label],
				['old._trackEvent', category, action, label]
			);
    } catch(err) {}
}
