/***
 * Widgets and behaviors for the Hero Products pages.
 * @author Adam J. McIntyre -- adam.mcintyre@isobar.net.
 */
(RotatingPromos = function($){
    var $els;
    var ROTATE_INTVL = 4500;    // How long before we rotate promos, in milliseconds
    var intvl = null;
    var idx = 0;
    
    return{
        init : function(){
            var o = this;

            $(document).ready(function(){
                // Grab our LIs and hide them...
                $els = $('#rotating_teasers li').fadeOut(0);     
            });                
        },
        /***
         * Sets up the basic events/intervals necessary to rotate our promo elements.
         */
        rotatePromos : function(){
            var o = this;

            // Show initial promo
            this._animate(); 
            
            // ... set up our rotation events
            $els.parents('#rotating_teasers')
                .bind('mouseenter',function(){
                    clearInterval(intvl);
                })               
                .bind('mouseleave',function(){
                    o._rotate();   
                });
                
            this._rotate();
        },
        /***
         * Handles our auto-rotation.
         */
        _rotate : function(){
            var o = this;

            intvl = setInterval(function(){
                o._animate();    
            }, ROTATE_INTVL);
        },
        /***
         * Hides current promo and shows the promo at a given idx.
         */
        _animate : function(){
            $els.filter($els.filter('.selected').length > 0 ? '.selected' : ':last')
                .fadeOut('slow',function(){

                    $(this).removeClass('selected')

                    $els.filter(':eq(' + idx + ')')
                        .fadeIn('slow',function(){
                            idx++;
                            if(idx > $els.length - 1){
                                idx = 0;
                            }                                 
                        })
                        .addClass('selected');                        
                });   
        }
    }
}(jQuery)).init();

(PageTransitions = function($){
    var h3;
    var HEADER_DURATION = 2000;
    var allItemsIntvl = null;
    var VISITED_COOKIE = 'viewed-hero-intro';
    
    return {
        init : function(){
            var o = this;
            
            $(document).ready(function(){    
                if(MOLECULAR.browser.ie6){
                    setTimeout(function(){ DD_belatedPNG.fix('#hero_product h2.title'); $('#hero_product h2.moved').hide(); }, 100);                                   
                }

                h3 = $('#hero_product h3.subtitle').fadeOut();
                
                // Animate headers
                setTimeout(function(){
                    o._animateHeaders();                                
                }, HEADER_DURATION)                
                                    
                // Hide all items and set up a fade in/show on an interval...
                $('.initial_hide').fadeOut(0);
                
                allItemsIntvl = setTimeout(function(){
                    o._showAll();    
                }, 2 * HEADER_DURATION);
                
                // ... interval can be cancelled by mouseover.
                $('#hero_product').one('mouseenter', function(){
                    clearTimeout(allItemsIntvl);
                    o._showAll();    
                });                                        

                // Attach Buy Now button rollout
                o.initPAN(); 
                
                // Wire up any lightbox video clicks
                $('#hero_product a.videoplayer').each(function(){
                    var vidEl = $(this);
                    vidEl.nyroModal({
                        width : vidEl.attr('data-videowidth') || 400,
                        height : vidEl.attr('data-videoheight') || 300,
                        mediaPlayer : vidEl.attr('data-mediaplayer') || null,
                        videoPreview : vidEl.attr('data-preview') || null,
                        showIcon : vidEl.attr('data-showicon') || false,
                        showIconEnd : vidEl.attr('data-showiconend') || false,
                        showPreviewAtEnd : vidEl.attr('data-showpreviewatend') || false,
                        autoPlay : vidEl.attr('data-autoplay') || false, 
            			playText : vidEl.attr('data-playtext') || false,
            			playTextHover : vidEl.attr('data-playtexthover') || false,   
            			playTextColor : vidEl.attr ('data-playtextcolor') || false,
            			playIconY : vidEl.attr ('data-playicony') || false       
                    });
                });
            });    
        },
        _animateHeaders : function(){
            if(MOLECULAR.browser.ie7 || MOLECULAR.browser.ie6){
                $('#hero_product h2.title:not(.moved)').css({
                    filter : '',
                    display : 'none'
                });
                h3.css('filter','').show().filter('.moved').hide();                                 
            }
            else{
                $('#hero_product h2.title:not(.moved)').fadeOut('slow',function(){
                    h3.fadeIn('slow').filter('.moved').hide();
                });                 
            }           
        },
        /***
         * Moves the headers to their docked state after a user interacts with product shots.
         * 
         * @param {Number} idx Index of list-item whose click triggered this call.
         */
        moveHeaders : function(idx){
            // If click occurred on the first item (0th in list), revert headers.
            if(idx == 0){
                this.returnHeaders();    
            }
            // If the headers have already moved, we can bail out.
            else if($('#hero_product .moved').length > 0 && ! MOLECULAR.browser.ie6){
                $('#hero_product .moved').show();    // Make sure they're shown initially...
                return true;
            }
            else{                
                if(MOLECULAR.browser.ie6){
                    $headers = $('#hero_product .header').hide();
                
                    setTimeout(function(){                        
                        $('#hero_product .moved').fadeIn();
                    },1000);                                    
                }
                else{
                    $headers = $('#hero_product .header').fadeOut();
                
                    setTimeout(function(){
                        $headers.addClass('moved').fadeIn();    
                    },1000);                                    
                }
            }
        },
        /***
         * Revert the headers to their normal starting positions. Done after a click on the initial product image.
         */
        returnHeaders : function(){
            var o = this;
            
            // Hide the "moved" headers
            $('#hero_product .moved').hide(); 
            
            if(! MOLECULAR.browser.ie6){
                $('#hero_product .moved').removeClass('moved');
            }
            
            setTimeout(function(){
                o._animateHeaders();
            },1100);    // Little delay to make sure image loads.              
        },
        _showAll : function(){
            $('.initial_hide').fadeIn();
            $('#hero_product').unbind('mouseenter');   
            
            // Kick off our promo rotation, too.
            RotatingPromos.rotatePromos();
        },
        /***
         * Move PAN application elements in the DOM; bind their events, etc..
         */
        initPAN : function(){
            if($('#buyNowWithPanModule').length > 0){    // PAN application + preorder form
                $('#buy_now > div.button_container, #buy_now > strong').appendTo('#buy_now div.bd');
                $('#buyNowWithPanModule').wrap('<div id="pan_flyout" class="hidden"><div class="flyout_content gradient constrained no_top"></div></div>');
                $('#buy_now_promo button').bind('click',this._togglePAN);
            }
            else{
                $('#buy_now > div.button_container, #buy_now > strong').remove();    
            }                        
        },
        _togglePAN : function(e){
            e.preventDefault();
            var $self = $(this);
            
            if($('#buy_now_promo div.hero_layer').length == 0){
                var panApp = $('#pan_flyout');
                
                // For readability's sake, I have broken this out into separate steps. It could all be chained together
                // if need be. 
                
                // Format pan app form rows with appropriate CSS className
                panApp.find('.ppBnPANfieldItem')
                    .removeClass('ppBnPANfieldItem')
                    .addClass('form_row clearfix');                    
                
                // Update submit button if our markup is present
                var $bn = $('#buy_now_button button');
                if($bn.length > 0){
                    $('#pan_submit').wrap('<div class="form_row"></div>').replaceWith($('#buy_now_button button'));                    
                }
                
                // Call Nokia's set-up functions and show hidden layers.
                if(typeof ctrlBnDisplay === 'function'){
                    // Pulled from Nokia's ctrlBnDisplay function
                    if(typeof fixNSButton === 'function'){
                        fixNSButton();                        
                    }
                    if(typeof fixPrivacyPolicy === 'function'){
                        fixPrivacyPolicy();                         
                    }
                    if(typeof fixLocalization === 'function'){
                        fixLocalization();                              
                    }                                                       
                }
                
                $('#buyNowWithPanModule').show()                    

                // Add appropriate flyout markup and classes and show layer
                panApp.addClass('hero_layer')
                    .prepend('<div class="hero_layer_hd">' + $self.find('h3').html() + '</div>')
                    .append('<div class="hero_layer_ft"></div>')
                    .find('div.flyout_content')
                    .addClass('hero_layer_bd clearfix')
                    .end()  
                    .fadeOut(0)                              
                    .removeClass('hidden')
                    .appendTo('#buy_now_promo')
                    .fadeIn('slow');          
                    
                var hd = $('#buy_now_promo div.hero_layer div.hero_layer_hd').bind('click',function(){
                    $(this).parent().fadeOut('slow',function(){
                        $('#buy_now_promo > div:not(.hero_layer)').fadeIn();   
                    });    
                });      
                
                // Hook into form submission to monitor for a successful request.
                $().bind('ajaxComplete',function(e,xhr){                                
                    // If this is a successful "notify me" PAN request, we'll fade out the PAN layer after it posts
                    if(xhr && xhr.reponseXML && 
                        $(xhr.responseXML).find('Success').text().indexOf('pan_head') > -1){
                        setTimeout(function(){
                            hd.click();
                        },3000);
                    }
                });
            }
            else{
                $('#buy_now_promo div.hero_layer').fadeIn();
            }
            
            $('#buy_now_promo > div:not(.hero_layer)').fadeOut(0);                
        }      
    }
}(jQuery)).init();

(ImageManager = function($){
    var VISIBLE_SHOTS_INDEX = 2;    // Number of visible product shots on page load; zero-based.
    
    return{
        init : function(){
            var o = this;
            
            $(document).ready(function(){
                // Hide our initial product shots...
                $('#product_views li:gt(' + VISIBLE_SHOTS_INDEX + ')').fadeOut(100);
                $('#product_views li:eq(' + VISIBLE_SHOTS_INDEX + ')').addClass('last');
                o._bindProductViewEvents();                    
                o._toggleEmbed();
                
                // Should we preload a view?
                var color = window.location.search.match(/[\?&]?color=([^&]+)/);
                var image = window.location.search.match(/[\?&]?image=([^&]+)/);    
                if((color && color.length > 1) && (image && image.length > 1)){
                    o._loadHeroImage(color[1],image[1]); 
                }            
                
                 /***
                 * Display promo-linked videos directly in the lightbox...
                 */
                var vidEl = $('#hero_video');
                vidEl.nyroModal({
                    width : vidEl.attr('data-videowidth') || 400,
                    height : vidEl.attr('data-videoheight') || 300,
                    mediaPlayer : vidEl.attr('data-mediaplayer') || null,
                    videoPreview : vidEl.attr('data-preview') || null,
                    showIcon : vidEl.attr('data-showicon') || false,
                    showIconEnd : vidEl.attr('data-showiconend') || false,
                    showPreviewAtEnd : vidEl.attr('data-showpreviewatend') || false,
                    autoPlay : vidEl.attr('data-autoplay') || false, 
        			playText : vidEl.attr('data-playtext') || false,
        			playTextHover : vidEl.attr('data-playtexthover') || false,   
        			playTextColor : vidEl.attr ('data-playtextcolor') || false,
        			playIconY : vidEl.attr ('data-playicony') || false       
                });
            });     
        },
        _loadHeroImage : function(colorIndex,imageIndex){
            var $hb = $('#hero_background');
            
            // Show our loading image...
            MOLECULAR.ProductPage.swapper.showHeroLoading($hb);
            
            // Select the old color and the color passed in the URL parameter
            // Deselect old item; select new. 
            var $oldColor = $('#color_picker li.on').removeClass('on');
            var $color = $('#color_picker li:eq(' + colorIndex + ')').addClass('on');

            // Select the old image and the image passed in the URL parameter
            // Deselect old item; select new.   
            $('#product_shots li.selected').removeClass('selected');         
            var $newImage = $('#product_shots li:eq(' + imageIndex + ')').addClass('selected');
            var imgSrc = $newImage.find('a')
                            .attr('href')
                            .replace(/604x604/g,'755x497');
                            
            var newSrc = MOLECULAR.ProductPage.picker
                .getSrc($oldColor.attr('data-swatch'),$oldColor.attr('data-path'),
                    imgSrc, $color.attr('data-swatch'), $color.attr('data-path'));        

            setTimeout(function(){
                $hb.one('load',function(){
                    MOLECULAR.ProductPage.swapper.hideLoading($hb);

                    // Need to set this to largest dimensions by convention
                    $('#hero_link').attr('href',newSrc);  
                    
                    // If we aren't on the first image, move the headers.
                    if(imageIndex > 0){
                        PageTransitions.moveHeaders();
                    }     
                }).attr('src',newSrc);                
            },250);                
        },
        _bindProductViewEvents : function(){
            // Set up mouseover/mouseout on layer...
            $('#product_shots')                
                .bind('mouseenter',function(){
                    $('#product_views li:eq(' + VISIBLE_SHOTS_INDEX + ')').removeClass('last');
                    
                    $('#product_views')
                        .addClass('active')
                        .find('div.ft')
                        .show()
                        .end()
                        .find('li:gt(' + VISIBLE_SHOTS_INDEX + ')')
                        .fadeIn('fast');
                });

            $('#product_views')
                .bind('mouseleave',function(e){                    
                    $('#product_views li:eq(' + VISIBLE_SHOTS_INDEX + ')').addClass('last');

                    $(this)
                        .removeClass('active')
                        .find('div.ft')
                        .hide()
                        .end()
                        .find('li:gt(' + VISIBLE_SHOTS_INDEX + ')')
                        .fadeOut(100);                            
                })
                .find('div.ft')
                .hide();            
        },
        _toggleEmbed : function(){
            $('#embed_image').bind('click',function(e){
                e.preventDefault();
                
                if($('#embed_layer').hasClass('hidden')){
                    var $ps = $('#product_shots li');
                    var $active = $ps.filter('.selected');
                    var current_shot = $ps.index($ps.filter('.selected'));
                    
                    var $color = $('#color_picker li');
                    var current_color = $color.index($color.filter('.on'));
                    
                    var imageSrc = $active.find('a').attr('href').replace(/604x604/g, '302x302');
                    
                    var $ed = $('#embed_data');
                    $ed.val($ed.attr('data-linktemplate').replace(/\/"/g,'"').replace('{image}',current_shot)
                        .replace('{color}',current_color).replace('{src}',imageSrc));

                    $('#embed_layer')
                        .find('div.flyout_content')
                        .addClass('hero_layer_bd clearfix')
                        .end()  
                        .fadeOut(0)            
                        .css('left', $ps.parent().parent().position().left + $ps.filter(':eq(3)').position().left)                        
                        .removeClass('hidden')
                        .fadeIn('slow',function(){
                            var clip = new ZeroClipboard.Client();
                            clip.setHandCursor(true); 
                            clip.setCSSEffects(false);     
                            
                            clip.addEventListener('mouseDown',function(){
                                var $ed = $('#embed_data');
                                clip.setText($ed.val());
                            
                                $ed.css('backgroundColor','#FFFFCF')
                                    .animate({
                                        backgroundColor : '#FFF'
                                    },600);
                            });
                            
                            clip.addEventListener('complete',function(){ clip.destroy(); });
                            clip.setText('')
                                    
                            clip.glue('copy');                               
                        });          
                        
                    $('#embed_layer div.hero_layer_hd').bind('click',function(){
                        $('#embed_layer').fadeOut('slow').addClass('hidden');
                    }); 
                }
                else{
                    $('#embed_layer').fadeOut().addClass('hidden');
                }                     
            });
        }
    }    
}(jQuery)).init();

/*
 * 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);

