$(document).ready(function() {
    $('#productPageTabs').tabs();
    SlideShow();
    lightBox();
    rotatingImagesHomePage();
    homePageBehavior();
    equalizeCols();
    $(".breadcrumb a:last").css("color", "#414a29");
    mainMenuResizing();
    $('#readReviews').click(function() { $('.tabReview a').trigger('click'); });
    $('#writeReview').click(function() { $('.tabReview a').trigger('click'); });
    adjustClassHoverSelected();
    adjustpaddingMarginBorder();
    slideShowProduct();
    slideshowYouMayAlsoLike();
    browsedList();
    slideShowStore();
    onglets();
    fixFacetWithoutImages();

    initPageTooltips();
    $('.productSizes').change(function() {
        toggleItemMask($(".detailProductRightCol .big_button").eq(0));
    });
    $('.jq_watermark').watermark();
    $('#searchBox label').click(function() { $('#searchBox .cell3 input').eq(0).trigger('click') });
    
    $('.topLinksTD button').click(function(e){ window.location.pathname = $(this).parent().attr('href'); });
});

function fixFacetWithoutImages() {
    $('.facetGroup li .facetImg').each(function() {
        if ($(this).find("img").size() === 0) {
            $(this).parent().addClass("facetGroupLiNoImg");
        }
    });
}

function initPageTooltips() {
    $('img.tooltip[data]').tooltip({
        delay: 0,
        showURL: false,
        bodyHandler: function() {
            return $(this).attr('data');
        }
    });
}

function toggleItemMask(target) {
    if ($('#mask').size() < 1) {
        $('body').append('<div id="mask" style="border: none; background-color: #FFF; display: none; left: 0; -moz-opacity:.50; filter:alpha(opacity=50); margin: -2px 0 0 -2px; opacity:.50; padding: 4px; position: absolute; top: 0;"></div>');
    }
    if (target) {
        var offset = $(target).offset();
        $('#mask').css({ left: offset.left + 'px', top: offset.top + 'px', width: $(target).innerWidth() + 'px', height: $(target).innerHeight() + 'px' });
    }
    $('#mask').toggle();
    return false;
}

function togglePageMask() {
    if ($('#pageMask').size() < 1) {
        $('body').append('<div id="pageMask" style="z-index:99; background-color: #fff; display: none; left: 0; -moz-opacity:.50; filter:alpha(opacity=50); opacity:.50; position: fixed; top: 0; text-align: center; height: 100%; width: 100%"><img src="/Templates/Tilley/styles/images/loading.gif" style="margin-top: 220px" /></div>');
    }
    $('#pageMask').toggle();
    return false;
}

function onglets() {
    ongletsBehavior('.productListBoxOnglets li', '.productListBoxOngletsContent > li');
}

function infoPanierClick() {
    if ($('.infoPanier a').size() > 0) {
        window.location = $('.infoPanier a').eq(0).attr('href');
    }
}

function ongletsBehavior(FirstList, SecondList) {
    var selectedIndex = $('.productListBoxOnglets li.selected').index();
    if (selectedIndex === -1) {
        selectedIndex = 0;
        $(FirstList).eq(0).addClass("selected");
    }    
    ongletsSetup(SecondList, selectedIndex);

    /*if ($(FirstList).parent().find('.selected').size() == 0) {
        $(FirstList).eq(0).addClass("selected");
    }*/

    $(".allReviews").addClass("selected");
    ongletClickBehavior(FirstList, SecondList);
    $(SecondList).find("ul").addClass("listContent");
}

function ongletsSetup(listToSetUp, ongletToSetUp) {
    $(listToSetUp).each(function() {
        $(this).css("display", "none");
        $(listToSetUp).eq(ongletToSetUp).css("display", "block");
    });
}

function ongletClickBehavior(First, Second) {
    $(First).click(function() {
        var index = $(First).index(this);
        setUpFisrtList(First);
        $(First).eq(index).addClass("selected");
        $(Second).each(function() {
            $(this).css("display", "none");
        });
        $(Second).eq(index).css("display", "block");
        if (index == 2) {
            $(".allReviews").addClass("selected");
            $("#post-review-container").addClass("selected");
        }
        adjustPaddingText();
    });


}

function setUpFisrtList(FirstListToSetUp) {
    $(FirstListToSetUp).each(function() {
        $(this).removeClass("selected");
    });
}

function SlideShow(){
	SlideShowSelector(4,"#homePageSlideShow li","#homePageSlideShow");		
}



function SlideShowSelector(sizeRequired,sizeCycle,idCycle){
	$(idCycle).jCarouselLite({
		btnNext: ".nextProduct",
		btnPrev: ".prevProduct",
		vertical:false,
		visible:sizeRequired,
		circular:true
	});	
	if($(sizeCycle).size()<=sizeRequired){
        $(idCycle).parent().find($(".prevProduct")).toggle();
        $(idCycle).parent().find($(".nextProduct")).toggle();
	} 
}

function slideshowYouMayAlsoLike(){
    $("#catalogSlideShowAlso .catalogSlideShowSmallImage2").jcarousel({
        scroll: 1
    }); 
}

function slideShowStore(){
    slideShowStoresList("#storeList1");
    slideShowStoresList("#storeList2");
    slideShowStoresList("#storeList3");
    slideShowStoresList("#storeList4");
    slideShowStoresList("#storeList5");
    slideShowStoresList("#storeList6");  
}


function slideShowStoresList(slideShowStoreListIndex){
    $(slideShowStoreListIndex + " .catalogSlideShowSmallImage").jcarousel({
        scroll: 1
    }); 
    $(slideShowStoreListIndex + " .catalogSlideShowSmallImage li").each(function(){
        $(this).removeClass("selected");
    });
    $(slideShowStoreListIndex + " .catalogSlideShowSmallImage li a").click(function(){
        indexSelected = $(slideShowStoreListIndex + " .catalogSlideShowSmallImage li a").index($(this));
        $(slideShowStoreListIndex + " .catalogSlideShowSmallImage li a").each(function(){
            indexLi = $(slideShowStoreListIndex + " .catalogSlideShowSmallImage li a").index($(this));
            if(indexSelected == indexLi){
                $(slideShowStoreListIndex + " .catalogSlideShowSmallImage li").eq(indexLi).addClass("selected");
            } else{
                $(slideShowStoreListIndex + " .catalogSlideShowSmallImage li").eq(indexLi).removeClass("selected");
            }
        });
    });

}

function slideShowProduct(){
    $(".catalogSlideShowSmallImage").jcarousel({
        scroll: 1
    });
    
	$(".catalogSlideShowLargeImage li:first").css("display","block");
	
	$(".catalogSlideShowSmallImage li").click(function(){
		indexImg = $(".catalogSlideShowSmallImage li").index($(this));
		$(".catalogSlideShowLargeImage li").each(function(){
			indexImgLarge = $(".catalogSlideShowLargeImage li").index($(this));
			if(indexImg!=indexImgLarge){
				$(this).css("display","none");
			} else{
				$(this).css("display","block");
			}
		});
		$(".catalogSlideShowSmallImage li").each(function(){
		    indexSmallImg =  $(".catalogSlideShowSmallImage li").index($(this));
			if(indexImg!=indexSmallImg){
				$(this).removeClass("selected");
			} else{
				$(this).addClass("selected");
			}
		});
	});
	if($("#catalogSlideShow .catalogSlideShowSmallImage li").size()<5){
	    $("#catalogSlideShow .prevProduct").css("top","-1000px");
	    $("#catalogSlideShow .nextProduct").css("top","-1000px");
	}
	$(".catalogSlideShowSmallImage li.selected:last").trigger("click");
}

function lightBox(lightBoxIndex){
	 lightBoxList('#catalogSlideShow .catalogSlideShowLargeImage li a');	
	 lightBoxList('#storeList1 .catalogSlideShowSmallImage li a');
	 lightBoxList('#storeList2 .catalogSlideShowSmallImage li a');
	 lightBoxList('#storeList3 .catalogSlideShowSmallImage li a');
	 lightBoxList('#storeList4 .catalogSlideShowSmallImage li a');
	 lightBoxList('#storeList5 .catalogSlideShowSmallImage li a');
	 lightBoxList('#storeList6 .catalogSlideShowSmallImage li a');
}

function lightBoxList(lightBoxIndex){
	 $(lightBoxIndex).lightBox();	
}

function rotatingImagesHomePage(){
	$('#MainContentArea .homePageBanner').after('<div id="nav">').cycle({
		fx: 'none', /* probleme de transition sous IE quand image est transparente - ne pas mettre d'effet sur les images + mettre vitesse assez rapide */
		timeout: 6000,
		speed:2000,
		pager: '#nav'
	});
	$("#MainContentArea #nav a:first").css("margin-left","0");
}

function homePageBehavior(){
    $(".homePage #breadcrumbsWrapper").toggle();
}

function equalizeCols(){
    equalizeColClass(".productGrid");
}

function equalizeColClass(colToEqualize){
    if ( $(colToEqualize).eq(0).parents('TR').size() > 0)
    {
    	$(colToEqualize).each(function(){
	        if($(this).height() > parseInt( ($(this).parents('TR').eq(0).attr('data-h')|| 0),10)) {
	            $(this).parents('TR').eq(0).attr('data-h',$(this).height());
	        }   
	    });
	    $(colToEqualize).each(function(){
	    	
	        $(this).css("height", $(this).parents('TR').eq(0).attr('data-h')+'px');  
	    });
    }
    else {
    //legacy method	
	    var maxHeight = 0;
	    $(colToEqualize).each(function(){
	        if($(this).height()>maxHeight) {
	            maxHeight = $(this).height();
	        }   
	    });
	    $(colToEqualize).each(function(){
	        $(this).css("height",maxHeight+"px");  
	    });    
    }
}

function mainMenuResizing(){
    $("#topMenuWrapper ul li:last").css("border-right","none");
    if($('body').hasClass("fr-CA")){
        $("#topMenuWrapper ul li a").eq(0).css("width","146px");
        $("#topMenuWrapper ul li a").eq(1).css("width","128px");
        $("#topMenuWrapper ul li a").eq(2).css("width","126px");
        $("#topMenuWrapper ul li a").eq(3).css("width","184px");
        $("#topMenuWrapper ul li a").eq(4).css("width","237px");
        $("#topMenuWrapper ul li a").eq(5).css("width","154px");  
    } else{
        $("#topMenuWrapper ul li a").eq(0).css("width","122px");
        $("#topMenuWrapper ul li a").eq(1).css("width","122px");
        $("#topMenuWrapper ul li a").eq(2).css("width","142px");
        $("#topMenuWrapper ul li a").eq(3).css("width","176px");
        $("#topMenuWrapper ul li a").eq(4).css("width","241px");
        $("#topMenuWrapper ul li a").eq(5).css("width","172px");   
    }
}

function adjustClassHoverSelected(){
    $(".headlink li").hover(
        function(){
            $(this).addClass("selected");
        },
         function(){
         $(this).removeClass("selected");
    })
}

function adjustpaddingMarginBorder(){
    $(".retailers li:last").css("border","none");
    $(".facet").each(function(){
        if($(this).find(".facetImg img").attr("src")===null){
            $(this).find(".facetName").addClass("noImg");
        }
    });
}

function browsedList(){
    if ($(".browsed li").size() > 3) {
       $(".browsed li").slice(3).hide();  
       $(".browsedMore").show();
       //add beahvior
       $(".browsedMore").click(function() {
           $(".browsed li").show();
           $(".browsedMore").hide();
           $(".browsedLess").show();
       });
       //add beahvior
       $(".browsedLess").click(function() {
           $(".browsed li").slice(3).hide();
           $(".browsedMore").show();
           $(".browsedLess").hide();
       });
   }
}

function fakeStarInit(rating) {
    rating = (rating) ? rating : 0;
    $("#fake-stars-on").width(Math.round($("#fake-stars-off").width() / 5 * parseFloat(rating)));
}

/**
* Cookie plugin
*
* Copyright (c) 2006 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/

/**
* Create a cookie with the given name and value and other optional parameters.
*
* @example $.cookie('the_cookie', 'the_value');
* @desc Set the value of a cookie.
* @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
* @desc Create a cookie with all available options.
* @example $.cookie('the_cookie', 'the_value');
* @desc Create a session cookie.
* @example $.cookie('the_cookie', null);
* @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
*       used when the cookie was set.
*
* @param String name The name of the cookie.
* @param String value The value of the cookie.
* @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
* @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
*                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
*                             If set to null or omitted, the cookie will be a session cookie and will not be retained
*                             when the the browser exits.
* @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
* @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
* @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
*                        require a secure protocol (like HTTPS).
* @type undefined
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/

/**
* Get the value of a cookie with the given name.
*
* @example $.cookie('the_cookie');
* @desc Get the value of a cookie.
*
* @param String name The name of the cookie.
* @return The value of the cookie.
* @type String
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/*
 * jQuery Tooltip plugin 1.3
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/
 * http://docs.jquery.com/Plugins/Tooltip
 *
 * Copyright (c) 2006 - 2008 Jörn Zaefferer
 *
 * $Id: jquery.tooltip.js 5741 2008-06-21 15:22:16Z joern.zaefferer $
 * 
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
 
;(function($) {
	
		// the tooltip element
	var helper = {},
		// the current tooltipped element
		current,
		// the title of the current element, used for restoring
		title,
		// timeout id for delayed tooltips
		tID,
		// IE 5.5 or 6
		IE = $.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent),
		// flag for mouse tracking
		track = false;
	
	$.tooltip = {
		blocked: false,
		defaults: {
			delay: 200,
			fade: false,
			showURL: true,
			extraClass: "",
			top: 15,
			left: 15,
			id: "tooltip"
		},
		block: function() {
			$.tooltip.blocked = !$.tooltip.blocked;
		}
	};
	
	$.fn.extend({
		tooltip: function(settings) {
			settings = $.extend({}, $.tooltip.defaults, settings);
			createHelper(settings);
			return this.each(function() {
					$.data(this, "tooltip", settings);
					this.tOpacity = helper.parent.css("opacity");
					// copy tooltip into its own expando and remove the title
					this.tooltipText = this.title;
					$(this).removeAttr("title");
					// also remove alt attribute to prevent default tooltip in IE
					this.alt = "";
				})
				.mouseover(save)
				.mouseout(hide)
				.click(hide);
		},
		fixPNG: IE ? function() {
			return this.each(function () {
				var image = $(this).css('backgroundImage');
				if (image.match(/^url\(["']?(.*\.png)["']?\)$/i)) {
					image = RegExp.$1;
					$(this).css({
						'backgroundImage': 'none',
						'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')"
					}).each(function () {
						var position = $(this).css('position');
						if (position != 'absolute' && position != 'relative')
							$(this).css('position', 'relative');
					});
				}
			});
		} : function() { return this; },
		unfixPNG: IE ? function() {
			return this.each(function () {
				$(this).css({'filter': '', backgroundImage: ''});
			});
		} : function() { return this; },
		hideWhenEmpty: function() {
			return this.each(function() {
				$(this)[ $(this).html() ? "show" : "hide" ]();
			});
		},
		url: function() {
			return this.attr('href') || this.attr('src');
		}
	});
	
	function createHelper(settings) {
		// there can be only one tooltip helper
		if( helper.parent )
			return;
		// create the helper, h3 for title, div for url
		helper.parent = $('<div id="' + settings.id + '"><h3></h3><div class="body"></div><div class="url"></div></div>')
			// add to document
			.appendTo(document.body)
			// hide it at first
			.hide();
			
		// apply bgiframe if available
		if ( $.fn.bgiframe )
			helper.parent.bgiframe();
		
		// save references to title and url elements
		helper.title = $('h3', helper.parent);
		helper.body = $('div.body', helper.parent);
		helper.url = $('div.url', helper.parent);
	}
	
	function settings(element) {
		return $.data(element, "tooltip");
	}
	
	// main event handler to start showing tooltips
	function handle(event) {
		// show helper, either with timeout or on instant
		if( settings(this).delay )
			tID = setTimeout(show, settings(this).delay);
		else
			show();
		
		// if selected, update the helper position when the mouse moves
		track = !!settings(this).track;
		$(document.body).bind('mousemove', update);
			
		// update at least once
		update(event);
	}
	
	// save elements title before the tooltip is displayed
	function save() {
		// if this is the current source, or it has no title (occurs with click event), stop
		if ( $.tooltip.blocked || this == current || (!this.tooltipText && !settings(this).bodyHandler) )
			return;

		// save current
		current = this;
		title = this.tooltipText;
		
		if ( settings(this).bodyHandler ) {
			helper.title.hide();
			var bodyContent = settings(this).bodyHandler.call(this);
			if (bodyContent.nodeType || bodyContent.jquery) {
				helper.body.empty().append(bodyContent)
			} else {
				helper.body.html( bodyContent );
			}
			helper.body.show();
		} else if ( settings(this).showBody ) {
			var parts = title.split(settings(this).showBody);
			helper.title.html(parts.shift()).show();
			helper.body.empty();
			for(var i = 0, part; (part = parts[i]); i++) {
				if(i > 0)
					helper.body.append("<br/>");
				helper.body.append(part);
			}
			helper.body.hideWhenEmpty();
		} else {
			helper.title.html(title).show();
			helper.body.hide();
		}
		
		// if element has href or src, add and show it, otherwise hide it
		if( settings(this).showURL && $(this).url() )
			helper.url.html( $(this).url().replace('http://', '') ).show();
		else 
			helper.url.hide();
		
		// add an optional class for this tip
		helper.parent.addClass(settings(this).extraClass);

		// fix PNG background for IE
		if (settings(this).fixPNG )
			helper.parent.fixPNG();
			
		handle.apply(this, arguments);
	}
	
	// delete timeout and show helper
	function show() {
		tID = null;
		if ((!IE || !$.fn.bgiframe) && settings(current).fade) {
			if (helper.parent.is(":animated"))
				helper.parent.stop().show().fadeTo(settings(current).fade, current.tOpacity);
			else
				helper.parent.is(':visible') ? helper.parent.fadeTo(settings(current).fade, current.tOpacity) : helper.parent.fadeIn(settings(current).fade);
		} else {
			helper.parent.show();
		}
		update();
	}
	
	/**
	 * callback for mousemove
	 * updates the helper position
	 * removes itself when no current element
	 */
	function update(event)	{
		if($.tooltip.blocked)
			return;
		
		if (event && event.target.tagName == "OPTION") {
			return;
		}
		
		// stop updating when tracking is disabled and the tooltip is visible
		if ( !track && helper.parent.is(":visible")) {
			$(document.body).unbind('mousemove', update)
		}
		
		// if no current element is available, remove this listener
		if( current == null ) {
			$(document.body).unbind('mousemove', update);
			return;	
		}
		
		// remove position helper classes
		helper.parent.removeClass("viewport-right").removeClass("viewport-bottom");
		
		var left = helper.parent[0].offsetLeft;
		var top = helper.parent[0].offsetTop;
		if (event) {
			// position the helper 15 pixel to bottom right, starting from mouse position
			left = event.pageX + settings(current).left;
			top = event.pageY + settings(current).top;
			var right='auto';
			if (settings(current).positionLeft) {
				right = $(window).width() - left;
				left = 'auto';
			}
			helper.parent.css({
				left: left,
				right: right,
				top: top
			});
		}
		
		var v = viewport(),
			h = helper.parent[0];
		// check horizontal position
		if (v.x + v.cx < h.offsetLeft + h.offsetWidth) {
			left -= h.offsetWidth + 20 + settings(current).left;
			helper.parent.css({left: left + 'px'}).addClass("viewport-right");
		}
		// check vertical position
		if (v.y + v.cy < h.offsetTop + h.offsetHeight) {
			top -= h.offsetHeight + 20 + settings(current).top;
			helper.parent.css({top: top + 'px'}).addClass("viewport-bottom");
		}
	}
	
	function viewport() {
		return {
			x: $(window).scrollLeft(),
			y: $(window).scrollTop(),
			cx: $(window).width(),
			cy: $(window).height()
		};
	}
	
	// hide helper and restore added classes and the title
	function hide(event) {
		if($.tooltip.blocked)
			return;
		// clear timeout if possible
		if(tID)
			clearTimeout(tID);
		// no more current element
		current = null;
		
		var tsettings = settings(this);
		function complete() {
			helper.parent.removeClass( tsettings.extraClass ).hide().css("opacity", "");
		}
		if ((!IE || !$.fn.bgiframe) && tsettings.fade) {
			if (helper.parent.is(':animated'))
				helper.parent.stop().fadeTo(tsettings.fade, 0, complete);
			else
				helper.parent.stop().fadeOut(tsettings.fade, complete);
		} else
			complete();
		
		if( settings(this).fixPNG )
			helper.parent.unfixPNG();
	}
	
})(jQuery);


/*
* jQuery Color Animations
* Copyright 2007 John Resig
* Released under the MIT and GPL licenses.
*/

(function(jQuery) {

    // We override the animation for all of these color styles
    jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i, attr) {
        jQuery.fx.step[attr] = function(fx) {
            if (fx.state == 0) {
                fx.start = getColor(fx.elem, attr);
                fx.end = getRGB(fx.end);
            }

            fx.elem.style[attr] = "rgb(" + [
				Math.max(Math.min(parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
				Math.max(Math.min(parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
				Math.max(Math.min(parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
			].join(",") + ")";
        }
    });

    // Color Conversion functions from highlightFade
    // By Blair Mitchelmore
    // http://jquery.offput.ca/highlightFade/

    // Parse strings looking for color tuples [255,255,255]
    function getRGB(color) {
        var result;

        // Check if we're already dealing with an array of colors
        if (color && color.constructor == Array && color.length == 3)
            return color;

        // Look for rgb(num,num,num)
        if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
            return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

        // Look for rgb(num%,num%,num%)
        if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
            return [parseFloat(result[1]) * 2.55, parseFloat(result[2]) * 2.55, parseFloat(result[3]) * 2.55];

        // Look for #a0b1c2
        if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
            return [parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16)];

        // Look for #fff
        if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
            return [parseInt(result[1] + result[1], 16), parseInt(result[2] + result[2], 16), parseInt(result[3] + result[3], 16)];

        // Otherwise, we're most likely dealing with a named color
        return colors[jQuery.trim(color).toLowerCase()];
    }

    function getColor(elem, attr) {
        var color;

        do {
            color = jQuery.curCSS(elem, attr);

            // Keep going until we find an element that has color, or we hit the body
            if (color != '' && color != 'transparent' || jQuery.nodeName(elem, "body"))
                break;

            attr = "backgroundColor";
        } while (elem = elem.parentNode);

        return getRGB(color);
    };

    // Some named colors to work with
    // From Interface by Stefan Petre
    // http://interface.eyecon.ro/

    var colors = {
        aqua: [0, 255, 255],
        azure: [240, 255, 255],
        beige: [245, 245, 220],
        black: [0, 0, 0],
        blue: [0, 0, 255],
        brown: [165, 42, 42],
        cyan: [0, 255, 255],
        darkblue: [0, 0, 139],
        darkcyan: [0, 139, 139],
        darkgrey: [169, 169, 169],
        darkgreen: [0, 100, 0],
        darkkhaki: [189, 183, 107],
        darkmagenta: [139, 0, 139],
        darkolivegreen: [85, 107, 47],
        darkorange: [255, 140, 0],
        darkorchid: [153, 50, 204],
        darkred: [139, 0, 0],
        darksalmon: [233, 150, 122],
        darkviolet: [148, 0, 211],
        fuchsia: [255, 0, 255],
        gold: [255, 215, 0],
        green: [0, 128, 0],
        indigo: [75, 0, 130],
        khaki: [240, 230, 140],
        lightblue: [173, 216, 230],
        lightcyan: [224, 255, 255],
        lightgreen: [144, 238, 144],
        lightgrey: [211, 211, 211],
        lightpink: [255, 182, 193],
        lightyellow: [255, 255, 224],
        lime: [0, 255, 0],
        magenta: [255, 0, 255],
        maroon: [128, 0, 0],
        navy: [0, 0, 128],
        olive: [128, 128, 0],
        orange: [255, 165, 0],
        pink: [255, 192, 203],
        purple: [128, 0, 128],
        violet: [128, 0, 128],
        red: [255, 0, 0],
        silver: [192, 192, 192],
        white: [255, 255, 255],
        yellow: [255, 255, 0]
    };

})(jQuery);

/*
* jQuery Watermark plugin
* Version 1.2.1 (7-DEC-2010)
* @requires jQuery v1.3 or later
*
* Examples at: http://mario.ec/static/jq-watermark/
* Copyright (c) 2010 Mario Estrada
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
*/

(function($) {
    var old_ie = $.browser.msie && $.browser.version < 8;
    var hard_left = 4;
    $.watermarker = function() { };
    $.extend($.watermarker, {
        defaults: {
            color: '#E0C398',
            left: 0,
            top: 0,
            fallback: false,
            animDuration: 300,
            minOpacity: 0
        },
        setDefaults: function(settings) {
            $.extend($.watermarker.defaults, settings);
        },
        checkVal: function(val, label, event_blur) {
            if (val.length == 0)
                $(label).show();
            else
                $(label).hide();

            return val.length > 0;
        },
        html5_support: function() {
            var i = document.createElement('input');
            return 'placeholder' in i;
        }
    });

    $.fn.watermark = function(text, options) {
        var options, elems;
        options = $.extend($.watermarker.defaults, options);
        elems = this.filter('textarea, input:not(:checkbox,:radio,:file,:submit,:reset)');

        if (options.fallback && $.watermarker.html5_support())
            return;

        elems.each(function() {
            var $elem, attr_name, label_text, watermark_container, watermark_label;
            var e_margin_left, e_margin_top, pos, e_top = 0, height, line_height;

            $elem = $(this);
            if ($elem.attr('data-jq-watermark') == 'processed')
                return;

            attr_name = $elem.attr('placeholder') != undefined && $elem.attr('placeholder') != '' ? 'placeholder' : 'title';
            label_text = text === undefined || text === '' ? $(this).attr(attr_name) : text;
            watermark_container = $('<span class="watermark_container"></span>');
            watermark_label = $('<span class="watermark">' + label_text + '</span>');

            // If used, remove the placeholder attribute to prevent conflicts
            if (attr_name == 'placeholder')
                $elem.removeAttr('placeholder');

            watermark_container.css({
                display: 'inline-block',
                position: 'relative'
            });

            if (old_ie) {
                watermark_container.css({
                    zoom: 1,
                    display: 'inline'
                });
            }

            $elem.wrap(watermark_container).attr('data-jq-watermark', 'processed');
            if (this.nodeName.toLowerCase() == 'textarea') {
                e_height = $elem.css('line-height');
                e_height = e_height === 'normal' ? parseInt($elem.css('font-size')) : e_height;
                e_top = ($elem.css('padding-top') != 'auto' ? parseInt($elem.css('padding-top')) : 0);
            } else {
                e_height = $elem.outerHeight();
                if (e_height <= 0) {
                    e_height = ($elem.css('padding-top') != 'auto' ? parseInt($elem.css('padding-top')) : 0);
                    e_height += ($elem.css('padding-bottom') != 'auto' ? parseInt($elem.css('padding-bottom')) : 0);
                    e_height += ($elem.css('height') != 'auto' ? parseInt($elem.css('height')) : 0);
                }
            }

            e_top += ($elem.css('margin-top') != 'auto' ? parseInt($elem.css('margin-top')) : 0);

            e_margin_left = $elem.css('margin-left') != 'auto' ? parseInt($elem.css('margin-left')) : 0;
            e_margin_left += $elem.css('padding-left') != 'auto' ? parseInt($elem.css('padding-left')) : 0;

            watermark_label.css({
                position: 'absolute',
                display: 'block',
                fontFamily: $elem.css('font-family'),
                fontSize: $elem.css('font-size'),
                color: options.color,
                left: hard_left + options.left + e_margin_left,
                top: options.top + e_top,
                height: e_height,
                lineHeight: e_height + 'px',
                textAlign: 'left',
                pointerEvents: 'none'
            }).data('jq_watermark_element', $elem);

            $.watermarker.checkVal($elem.val(), watermark_label);

            watermark_label.click(function() {
                $($(this).data('jq_watermark_element')).trigger('click').trigger('focus');
            }
      );

            $elem.before(watermark_label)
			.bind('focus.jq_watermark', function() {
			    if (!$.watermarker.checkVal($(this).val(), watermark_label))
			        watermark_label.stop().fadeTo(options.animDuration, options.minOpacity);
			})
			.bind('blur.jq_watermark change.jq_watermark', function() {
			    if (!$.watermarker.checkVal($(this).val(), watermark_label))
			        watermark_label.stop().fadeTo(options.animDuration, 1);
			})
			.bind('keydown.jq_watermark, paste.jq_watermark', function(e) {
			    $(watermark_label).hide();
			})
			.bind('keyup.jq_watermark', function(e) {
			    $.watermarker.checkVal($(this).val(), watermark_label);
			});
        });

        return this;
    };

    $('.jq_watermark').watermark();
})(jQuery);


/* coming from dxSearchFilterModule*/
function initTabs() {

    // display the clear button is some items are selected
    if ($('.facet.on').size() > 0) {
        $('#searchClear').show();

    }
    else {
        $('#searchClear').hide();
    }

    adjustPaddingText();
    expandCollapse();

    // set facet list item events
    $('li.facet:not(.disabled)').click(function() {

        if ($('.facet.on').size() == 0) {
            $('#searchClear').fadeIn('slow');
        }

        $(this).toggleClass('on off');
        var count = $(this).parents('.facetGroup').find('.facet.on').size();

        if (count) {
            $(this).parents('.facetTab').find('.facetGroupCount').eq(0).html('(' + count + ')');
        }
        else {
            $(this).parents('.facetTab').find('.facetGroupCount').eq(0).html('');
        }

        setSelectedFacetCount($(this).parents('.facetTab'));


        if ($('.facet.on').size() == 0) {
            $('#searchClear').fadeOut('slow');
        }

        buildFacettedSearchUrl();
        $('.seach_filter_submit_button').trigger('click');

    });

    // build count of selected facets for each group
    $('.facetTab').each(function() { setSelectedFacetCount($(this)); });

    var showFacetSearch = $('#facetsSelector').eq(0).attr('data');
    if (showFacetSearch == 1) {
        $('#searchExpandCollapse').click();
    };

    tabList();
}

function tabList() {
    $('.productListBoxOnglets li').each(function(index) {
        if ($(this).hasClass('selected')) {
            $(".facetTab").eq(index).show();
        }
        else {
            $(".facetTab").eq(index).hide();
        }
    });

    $('.productListBoxOnglets li').click(function() {
        if ($("#searchExpandCollapse p").html() == '+') {
            $("#searchExpandCollapse p").html('-');

            var selector = $('#facetsSelector .facetGroups');
            selector.show();
            selector.attr('data', 1);
            $(".facetsSelector").css("margin-bottom", "20px");
        }
        adjustPaddingText();
    });
}

function adjustPaddingText() {
    $(".facetTab").each(function() {
        $(this).find(".facetName").each(function() {
            divHeight = $(this).height();
            facetLiHeight = $(this).parent().height();
            if (divHeight)
                $(this).css("padding-top", (facetLiHeight - divHeight) / 2 + "px")
        });
    })
}

function expandCollapse() {
    $('#searchExpandCollapse p').click(function() {
        if ($(this).html() == '+') {
            $(this).html('-');

            var selector = $('#facetsSelector .facetGroups');
            selector.show();
            selector.attr('data', 1);
        } else {
            $(this).html('+');
            var selector = $('#facetsSelector .facetGroups');
            selector.hide();
            selector.attr('data', 0);
        }
    });
}

function setSelectedFacetCount(facetTabElement) {
    var count = facetTabElement.find('.facet.on').size();
    var currentKey = facetTabElement.find('.facetGroup').eq(0).attr('data');

    if (count) {
        $('.productListBoxOnglets #' + currentKey + ' .facetGroupCount').eq(0).html('(' + count + ')');
    }
    else {
        $('.productListBoxOnglets #' + currentKey + ' .facetGroupCount').eq(0).html('');
    }
}

function clearSelection() {
    $('.facetGroup:has(.facet.on)').each(function() {
        var name = $(this).attr('data');
        $('#Hidden' + name).val('');
    });
    $('#st').val($('.productListBoxOnglets li.selected').eq(0).attr('id'));
    $('.seach_filter_submit_button').trigger('click');
    buildFacettedSearchUrl();
    return false;
}

function buildFacettedSearchUrl() {

    $('.facetGroup').each(function() {
        var name = $(this).attr('data');
        $('#Hidden' + name).val('');
    });

    $('.facetGroup:has(.facet.on)').each(function() {
        var name = $(this).attr('data');
        var values = '';

        $('.facet.on', $(this)).each(function() {
            values += $(this).attr('data') + "|";
        });

        if (values !== '') {
            values = values.substr(0, values.length - 1);
        }

        $('#Hidden' + name).val(values);
    });

    $('#st').val($('.productListBoxOnglets li.selected').eq(0).attr('id'));

    return true;
}
