// Reverse a jquery collection (last first)
// USAGE: $("div").reverse().each(function(){ //reverse order each() });
(function($){$.fn.reverse = [].reverse;})(jQuery);

// detects IEs
// WHY: because everybody loves IE, don't you? well, me neither
(function($){
    $.browser.msieLTE7 = ($.browser.msie && parseInt($.browser.version)<7); //IE<7
    $.browser.msieLTE8 = ($.browser.msie && parseInt($.browser.version) < 8); //IE<8
    $.browser.msie7 = ($.browser.msie && parseInt($.browser.version) == 7); //IE8
    $.browser.msie8 = ($.browser.msie && parseInt($.browser.version) == 8); //IE8
})(jQuery);

//hover class plugin, ads a class on hover, removes it otherwise
//default class is "hover"
(function($){
    $.fn.hoverClass = function(c){
        return $(this).hover(function(){
            $(this).addClass(c || "hover");
        }, function(){
            $(this).removeClass(c || "hover");
        });
    }
})(jQuery);

//Adds a bit to z-index of the element and to every parent
//USAGE: 
//	$("#someDiv").flyHigh() //sets #someDiv and every parent to its current z-index plus the default altitude (25)
///	$("#someDiv").flyHigh({altitude:-25}) //sets back #someDivs and every parents z-index
$.fn.flyHigh = function(options){ 
	var conf = $.extend({
    	altitude: 25,
		stopAfter: false
    }, options);
    if(!this.length){return this;}
	$(this).each(function(){
		var remaining = conf.stopAfter? parseInt(conf.stopAfter) : false;
		$($.merge( [this], $.makeArray($(this).parents()) )).each(function(){
			if(remaining || remaining === false){
				var zi = (parseInt($(this).css("z-index")) || 0) + conf.altitude;
				$(this).css("z-index", zi < 0 ? "0" : zi);
				remaining = remaining? remaining-1 : false;
			}
		});
	});
	return this;
};

//jQuery plugin
//sets an equal height of a floating collection of elements per line
$.fn.syncHeightPerLine = function(options){
    var conf = $.extend({
        syncDescendant: false, // change this to a child-selector for the .find() method 
        resetHeight: false // useful for reinitializations
    }, options);
    var syncList = $(this);
    if (!syncList.length) {
        return syncList;
    }
    var toSync = [];
    if (conf.resetHeight) {
        syncList.each(function(i, val){
            $(conf.syncDescendant ? $(this).find(conf.syncDescendant) : this).css("height", "auto");
        });
    }
    syncList.each(function(i, val){
        $(conf.syncDescendant ? $(this).find(conf.syncDescendant) : this).each(function(){
            toSync.push(this);
        });
        if (($(this).next().length && $(this).position().top != $(this).next().position().top) ||
        !$(this).next().length) {
            $(toSync).height($(toSync).maxHeight());
            toSync = [];
        }
    });
	return this;
}

//jQuery plugin
//computes the maximal height of an array of elements
$.fn.maxHeight = function(){
    var max = 0;
    $(this).each(function(){
        var height = $.browser.msie && $.browser.version == 6.0 ? $(this).outerHeight() : $(this).height();
        max = height > max ? height : max;
    });
    return max;
}

//plugin to fix png issues on IE6
//from http://allinthehead.com/code/sleight/supersleight.plugin.js
jQuery.fn.supersleight = function(settings){
	settings = jQuery.extend({
		imgs: true,
		backgrounds: true,
		shim: '/images/blank.gif', /* relative to the document (not the JS file!) */
		apply_positioning: true
	}, settings);
	
	return this.each(function(){
		if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 7 && parseInt(jQuery.browser.version, 10) > 4) {
			jQuery(this).find('*').andSelf().each(function(i, obj){
				var self = jQuery(obj);
				// background pngs
				if (settings.backgrounds && self.css('background-image').match(/\.png/i) !== null) {
					var bg = self.css('background-image');
					var src = bg.substring(5, bg.length - 2);
					var mode = (self.css('background-repeat') == 'no-repeat' ? 'crop' : 'scale');
					var styles = {
						'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='" + mode + "')",
						'background-image': 'url(' + settings.shim + ')'
					};
					self.css(styles);
				};
				// image elements
				if (settings.imgs && self.is('img[src$=png]')) {
					var styles = {
						'width': self.width() + 'px',
						'height': self.height() + 'px',
						'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + self.attr('src') + "', sizingMethod='scale')"
					};
					self.css(styles).attr('src', settings.shim);
				};
				// apply position to 'active' elements
				if (settings.apply_positioning && self.is('a, input') && (self.css('position') === '' || self.css('position') == 'static')) {
					self.css('position', 'relative');
				};
			});
		};
	});
};

//jQuery plugin
//superslights on load of the image
//DEPENDS: supersleight
$.fn.supersleightload = function(){
    return $(this).each(function(){
		$(this)
			.load(function(){ 
				if(this.supersleightLoaded){return this;}
				$(this).supersleight();
				this.supersleightLoaded = true;
			})
			.attr("src", $(this).attr("src")) //caching probs IE6 to trigger load event; 
	});
}

//global init
$(function() {
    if (($(".showroom").length > 0) && ($('#product-gallery.showroom').length === 0)) {
        $("#meta-nav li a").each(function() {
            $(this).css("color", "#c9c9c9");
        });
    }

    if ($.browser.msieLTE7) {
        //showrom diagonal
        $(".diagonal").supersleight().addClass("diagonal-loaded");
        
        //product detail
        $("#product-detail").prepend("<div class='ie6pngfix'></div>");
        $("#product-detail .ie6pngfix")
			.css("visibility", "visible")
			.supersleight();

        //IE6 png fun
        $("#watch-carrousel").css("visibility", "visible");
        $(["#product-gallery .product-gallery-part:first img",
            ".variants-carrousel li a img",
			"#watch-carrousel img:first"
		    ].join(", ")).supersleight();

        $("#product-gallery .product-gallery-part img")
			.css("visibility", "visible")
			.supersleightload();

        $("#finder-reset").hide().show();

        //IE6 hover fail
        $("#spirit-history-content.news-all .related-reference").hoverClass()

        //IE6 zoom:1 fail
        $("#main-content .line").css("zoom", "1");
    };

    //webkit display problems
    if ($.browser.safari) {
        $("#product-hub")
			.not(".subhub")
			.find(".cross-reference")
			.css("display", "inline-block");
    }

    // equalize heights
	$(".collection-hub #t3_teaser>li")
	.syncHeightPerLine({
		syncDescendant: ".subtitle"
	})
	.syncHeightPerLine({
		syncDescendant: "h2"
	});
	
	
	$("#product-subhub .list>li")
		.syncHeightPerLine({
			syncDescendant: ".subtitle"
		})
		.syncHeightPerLine({
			syncDescendant: "h2"
		});
	
    /* small navigation */
    $("#main-nav .level-0>li, #main-nav>ul>li>ul>li").hoverClass();
	//bigger click area
	$("#main-nav .level-0>li").click(function(){
		//this is tecnically wrong, but works in all browsers
		//don't change it, because IE ignores the correct window.location.href
		window.location = $("a:first",this).attr("href");
	}).css("cursor","pointer");


    //home teasers
    $(".thumb-wide, .thumb-full, .thumb-small").hover(function() {
        $(this).addClass("hover");
    }, function() {
        $(this).removeClass("hover");
    });
});


$(function() {
    /* fixup image lists as typo inserts spans */
    $('#main-content.magazine .container .image-list span.image-list-link').each(function() {
        $(this).parent().attr('class', $(this).attr('class'));
    });

    $('#standard-content.press-release-hub .list li span.thumb-link').each(function() {
        $(this).parent().attr('class', $(this).attr('class'));
    });
});


$(document).ready(function() {
    /* fixup pager */
    var pagerElemSel = ['.search-paging span.first', '.search-paging span.last', '.search-paging span.back-link', '.search-paging span.cross-reference'];

    for (var i = 0; i < pagerElemSel.length; i++) {
        var pagerElem = $(pagerElemSel[i]);
        pagerElem.parent().attr('class', pagerElem.attr('class'));
        pagerElem.attr('class', '');
    }
});  


$(window).load(function() {
    if ($.browser.msie && !$.browser.msie8) {
        /*we are using $(window).load() here because we want the coding to take  
        effect when the image finishes loading. */
        $('a.image-list-link').each(function() {
            var parent_height = $(this).height();
            var image_height = $('img', this).height();
            var top_margin = (parent_height - image_height) / 2;
            if ($.browser.msie7) {
                top_margin -= 2;
            }

            $(this).children(':first').css('margin-top', top_margin);
        });
    }
});


