/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);     
 


    

var Coal = Coal || {};








/**
 * Coal.Homepage
 */
Coal.Homepage = {
	speed: 1750,
	current: null,
	slideshow: {
		id: null,
		reset: null,
		timeout: null,
		speed: 15000
	},
	init: function () {
	    if ($('.slide').length > 1) {
	        $('.carousel li.next a').click(this.nextLinkListener);
    		$('.carousel li.back a').click(this.backLinkListener);

    		this.startSlideshow();
	    } else {
	        $('.carousel li.next a').hide();
    		$('.carousel li.back a').hide();
	    };
	    
        // this.__adjustBackground(); // Need to resize the initial image
        var activeImg = $('img', '.slide_bg.active');
        if(activeImg.get(0).complete) {
            Coal.Homepage.__adjustBackground();
            activeImg.animate({
                opacity: 1
            });
        } else {
            activeImg.load(function () {
                Coal.Homepage.__adjustBackground();
                activeImg.animate({
                    opacity: 1
                });
            });
        }
        
        // 1337 HACK
        // setTimeout(function () {
        //     var correct = $('.slide_bg:eq(1)');
        //     $('.slide_bg:eq(0) img').css({
        //         width: parseInt(correct.css('width')),
        //         height: parseInt(correct.css('height')),
        //         top: correct.css('top')
        //     });
        // }, 10);
        $(window).resize(this.__adjustBackground);
        setTimeout(function () {
            $(window).resize();
        }, 10);
	},
	startSlideshow: function () {
		if (this.slideshow.id !== null) {
			window.clearInterval(this.slideshow.id);
		}
		
		this.slideshow.id = setInterval(function () {
			Coal.Homepage.switchSlides('next');
		}, this.slideshow.speed);
	},
	/**
	 * nextLinkListener -> (Event)
	 * it's in jQuery context so you must use Coal.Homepage
	 */
	nextLinkListener: function (e) {
		e.preventDefault();
		
		Coal.Homepage.switchSlides('next');
	},
	/**
	 * backLinkListener -> (Event)
	 * it's in jQuery context so you must use Coal.Homepage
	 */
	backLinkListener: function (e) {
		e.preventDefault();
		
		Coal.Homepage.switchSlides('back');
	},
	/**
	 * We need to find the next or previous slide, if it's the
	 * last one, loop all the way back to the next one so it's
	 * infinite.
	 */
	findNextSlide: function (direction) {
		var total 	= $('.slide', '.carousel').length,
			current = $('.slide.active', '.carousel'),
			selected;
		
		if (direction == 'next') {
			selected = (current.next('.slide').length == 0) ? $('.slide:eq(0)', '.carousel') : current.next('.slide');
		} else {
			selected = (current.prev('.slide').length == 0) ? $('.slide:eq('+ (total-1) +')', '.carousel') : current.prev('.slide');
		}
		
		return selected;
	},
	switchSlides: function (direction) {
        var self		= this,
            el			= this.findNextSlide(direction),
            nextId 	    = this.current = el.attr('id').substr(6),
            wHeight     = $(window).height(),
            text 		= el.attr('data-subtitle');
		
		var activeSlide = $('.slide_bg.active');
		activeSlide.removeClass('active');
		
        $('.slide_bg').removeClass('reset');
		
		var nextSlide = $('#slide_bg_'+ nextId);
		nextSlide.addClass('active');
		this.__adjustBackground();
		
		// If they support css, let the browser do the animation.
		if (this.__supportsCSS3()) {
		    if(direction == 'next') {
    		    activeSlide.css({
    		        height: wHeight,
    		        marginTop: -wHeight
    		    }, this.speed, 'linear');
                nextSlide.css({
                    height: wHeight,
                    marginTop: 0
                }, this.speed, 'linear');
            } else {
                nextSlide.removeClass('active').addClass('reset').css({
                    marginTop: -wHeight,
                    height: wHeight
                })
                
                setTimeout(function () {
                    nextSlide.removeClass('reset').addClass('active').css({
                        marginTop: 0
                    });
        		    activeSlide.css({
        		        height: wHeight,
        		        marginTop: wHeight
        		    });
                }, 1);
            }
		} else {
		    $('.slide_bg').css('z-index', '1');
			nextSlide.css('z-index', '2').animate({
				marginTop: 0
			}, this.speed, 'linear');
		}
			
        // Need to reset the backgrounds because CSS doesn't have callbacks
        if (this.slideshow.reset !== null) {
            window.clearTimeout(this.slideshow.reset);
        }
        this.slideshow.reset = window.setTimeout(this.__resetBackgrounds, this.speed);

        // Resets page text
        if (this.slideshow.timeout !== null) {
            window.clearTimeout(this.slideshow.timeout);
        }
        this.slideshow.timeout = window.setTimeout(function () {
            self.switchSlideText(el, text, direction);
        }, this.speed/2);
	},
	switchSlideText: function (el, text, direction) {
		$('.carousel ul .subtitle').fadeOut(function () {
			$(this).text(text).fadeIn();
		});
		
		$('.slide.active', '.carousel').fadeOut(function () {
		  $(this).removeClass('active');
		  
			el.fadeIn(function () {
			  $(this).addClass('active');
			});
		});
	},
	fadeInContent: function () {
	    var wrap = $('.wrap'),
	        preloader = $('#preloader'),
	        loader = $('#loader'),
	        cart = $('#cartTrackerWrapper'),
	        cartHidden = $('#cartTrackerWrapper').css('display') == 'none',
	        wrapHidden = $('.wrap').css('display') == 'none',
	        image = preloader.attr('data-load-image');
	    
	    $(new Image()).load(function () {
	        preloader.css({  
	            backgroundRepeat: 'no-repeat',
	            backgroundImage: 'url(' + image + ')',
	            backgroundAttachment: 'fixed'
	        });
    	    setTimeout(function () {
    	        preloader.fadeOut();  
    	        loader.fadeOut(); 
    	        wrap.fadeIn(500, function() {                          
    	                if (Coal.Products.initialProduct != '') {
    	                    var offset = $('.productNav').height() - $('header').height(); 
                            
    	                    var position = ($(Coal.Products.initialProduct).offset().top || 0) - offset;
            	            $(window).scrollTo(position, 500);
            	        };
    	            });
    	        cart.fadeIn(); 
    	        if (!$.browser.msie) {    
    	            $('.content .gallery img').lazyload(lazyloadOptions); 
    	        }  
    	    }, 2000);
        }).error(function () {
            // die?
        }).attr('src', image);
	},
	__resetBackgrounds: function () {
		// Starting the new interval after full transition is complete.
		Coal.Homepage.startSlideshow();
    
		$('.slide_bg:not(.active)').addClass('reset').css({
			marginTop: '100%',
			zIndex: 1
		});
	},
	__adjustBackground: function () {
		var image = $('img', '.slide_bg.active'),
			imgRatio = image.width() / image.height(),
			bgWidth = $(document).width(),
			bgHeight = bgWidth / imgRatio,
			windowHeight = $(document).height();
        // alert(imgRatio);
        // alert(bgHeight + " < " + windowHeight);
		if(bgHeight < windowHeight && !isNaN(bgHeight)) {
			bgHeight = windowHeight;
			bgWidth = bgHeight * imgRatio;
		}
        // alert(bgHeight);
        // if(isNaN(bgHeight)) bgHeight = windowHeight;

		var bgOffsetW = Math.round((bgWidth - windowHeight) / 2);
		var bgOffsetH = Math.round((bgHeight - windowHeight) / 2);
		
        // console.log('==============');
        // console.log("bgOffsetW:", bgOffsetW);
        // console.log("bgOffsetH:", bgOffsetH);
        // console.log("bgHeight:", bgHeight);
        // console.log("bgWidth:", bgWidth);
        
		image.width(bgWidth).height(bgHeight)
				 .css({ position: 'relative', top: '-' + bgOffsetH + 'px', left: '0px' });
	},
	__supportsCSS3: function () {
        return ($.browser.webkit && parseFloat($.browser.version) > 400);// || ($.browser.mozilla && parseFloat($.browser.version) >= 2);
        // return false;
	}
}





