var rf = new(function($){ //inside the 'rf' scope, $ means jQuery

    var me = this,
        getByTagName = function(n){ return document.getElementsByTagName(n); },
        getById = function(n){ return document.getElementById(n); },
        ie = $.browser.msie,
        ie6 = ie && parseInt($.browser.version) == 6,
        giftCardBalanceURL = "SVSGiftCards-CheckBalance",
        svstotal = 0,
        estimatedtotal = 0;
    /// end var block

    //add className-s to <html> indicating
    // 1. that javascript is enabled (jsEnabled)
    // 2. if we are in IE, that we are (ie)
    // 3. if we are in IE, what version (ie6 or ie7 or..)
    if($.browser.safari) $.browser.version = navigator.userAgent.replace(/.*?Version.([0-9]).*/,'$1');
    $('html').addClass( 'jsEnabled' + (($.browser.msie ? ' ie ie': $.browser.safari ? ' safari safari' : ' other') + parseInt($.browser.version)) );
    
    //preload.
    // do not preload images because we don't know yet from where. Further this does not make sense
    // for only one picture. Manuel Blechschmidt 23-04-2009
    //(function(imageSources){
    //    var img = new Image();
    //    img.src = imageSources.pop();
    //    (imageSources.length && arguments.callee(imageSources)); // if imageSources.length, then execute arguments.callee(imageSources)
    // })([window.staticImagePath+'images/backgrounds/mini-cart.png']);
    
    /**
     * imply
     * @description: Performs an action that is implied by the markup context.
     */
    me.imply = function(){
        
        // p = the parentNode of the scriptblock that calls rf.imply()
        var p = getByTagName('script');
        p = p[p.length-1].parentNode;
        
        var fixedHeights = false;
        
        if(/^header$/.test(p.id)){
        
            $('#nav>li').mouseover(function(){
                $('a.pnav',this).addClass('hover');
                $(this).addClass('hover');
                
                //ie6
                if(ie6){
                    // hide selects
                    $('select').css('visibility','hidden');
                }
                /**/
                if(ie){
                    //ie needs to get this reset every time the thing is opened .. 50% of a display:none object doesn't work well.
                    var _me = this;
                    var container = $('.subnav-container',_me);
                    var backgrounds = $('.bg1,.bg2',_me);
                    var fixSize = function(){
                        if(container.height()){
                            backgrounds.css({
                                'width':'50%'
                                ,'height':'600px'
                            });
                            container.css('overflow','hidden');
                            
                            //if(!fixedHeights){
                                //~ var maxHeight = 0;
                                //~ $('ul ul',container.get(0)).each(function(){
                                    //~ maxHeight = Math.max(maxHeight, $(this).height());
                                //~ }).each(function(){
                                    //~ $(this).css('height',maxHeight);
                                //~ });
                                //~ fixedHeights = true;
                            //}
                        } else {
                            setTimeout(fixSize, 30);
                        }
                    };
                    
                    fixSize();
                }
                /**/
            }).mouseout(function(){
                $('a.pnav',this).removeClass('hover');
                $(this).removeClass('hover');
                
                // ie6
                if(ie6){
                    // hide selects
                    $('select').css('visibility','visible');
                }
            });
            
            //drop-shadow on left/right edges in all backgrounds
            $('.subnav-container').prepend('<div class="bg1"><div class="left-side"></div></div><div class="bg2"><div class="right-side"></div></div>');
            
            // clearing element .. to produce rows which line up.
            //$('li.subnav5,li.subnav10,li.subnav15').after('<div style="height:1px;font-size:1px;overflow:hidden;width:100%;padding:0;margin:0;clear:left;"></div>'); //yeah, this is invalid markup .. but it works.
            
        }
    };
    
    /**
     * labelOver jQuery plugin
     * @description: simulates default-text existing inside of <input>s by overlaying them with their <label>s
     * @param overClass: the className to apply to the label
     */
    //plugin from
    //http://remysharp.com/2007/03/19/a-few-more-jquery-plugins-crop-labelover-and-pluck/#labelOver
    jQuery.fn.labelOver = function(overClass) {
        return this.each(function(){
            var label = jQuery(this);
            var f = label.attr('for');
            if (f) {
                var input = jQuery('#' + f);
                
                this.hide = function() {
                    label.css({ textIndent: -9999 });
                }
                
                this.show = function() {
                    if (input.val() == '') label.css({ textIndent: 0 });
                }

                // handlers
                input.focus(this.hide);
                input.blur(this.show);
                label.addClass(overClass).click(function(){ input.focus() });
                
                if (input.val() != ''){
                    this.hide();
                }
            }
        })
    }
    /// end plugin
    
    
    function onlyAlphaNumeric(s){
        
        var o = [], a = s.split();
        for(var i=0, l = a.length; i<l; i++){
            if(/[a-zA-Z0-9]/.test(a[i])){
                o.push(a[i]);
            } else {
                o.push('-');
            }
        }
        
        while( o.length && o[o.length-1] == '-' ) o.pop();
        return o.join('');
        
    }
    
    // MODALS
    $.ui.dialog.defaults.bgiframe = true;
    $.ui.dialog.defaults.modal = true;
    $.ui.dialog.defaults.width = 367;
    $.ui.dialog.defaults.draggable = false;
    $.ui.dialog.defaults.resizable = false;
    var modals = {};
    function modal(o){
        var dialog = modals[o.title];
        //~ if(dialog){
            //~ $(dialog).dialog({modal:true});
        //~ } else {
            dialog = document.createElement('div');
            dialog.title = o.title;
            dialog.innerHTML = o.body;
            getById('page').appendChild(dialog);
       
            dialog.id = buildPopupDivId( o.title );
            // dialog.id = ('modal-' + (onlyAlphaNumeric(o.title)).toLowerCase());
            modals[o.title] = $(dialog).dialog({modal:true,width:(o.width || $.ui.dialog.defaults.width)});
            return modals;
        //~ }
    }
    
    me.modal = modal;
    
    // inserted 2009-03-12 by JN:
    // when representing the content of the popup, we need to know which ID
    // was used for the popup in the first place.  RF generated the ID
    // on the inline.  This exports the funtionality to create the ID.
    function buildPopupDivId( title )
    {
    	return 'modal-' + onlyAlphaNumericOld( title ).toLowerCase();
    }
    // inserted 2009-03-12 by JN:
    // making the previous method public
    this.buildPopupDivId = buildPopupDivId;
    
    // re-inserted 2009-03-22 by JN:
    // this was the original method as delivered in batch 2.1
    // the newer version allowes for spaces in the name!!!!  This is NO good
    // re-inserted the old one and renamed it.  Only used in the method build PopupDivId 
	function onlyAlphaNumericOld(s){
		
		var o = [], a = s.split();
		for(var i=0, l = s.length; i<l; i++){
		    if(/[a-zA-Z0-9]/.test(s[i])){
		        o.push(s[i]);
		    } else {
		        o.push('-');
		    }
		}
		
		while( o.length && o[o.length-1] == '-' ) o.pop();
		
		return o.join('');
	}

    // playerHolder needs to be set each time a modal is opened.
    // it should be set to the current holder of the flash video player.
    // should be jQuery-ied-up.
	var $playerHolder;
    
    //this is the javascript side of the flash->js communication required
    //for the flash video player to resize the container that holds it, depending on the size of the video.
	me.resizeFlashArea = function(newHeight) {
        $playerHolder.height(newHeight);
		if ($('#video-error-message').size() > 0) $('#video-error-message').remove();
	};
    
    //this is the javascript side of the flash->js communication, for when
    //the flash video player can not load an external flv for any reason.
	me.videoLoadError = function() {
	    // check if user is on Videos page; if not, include link to videos page in markup
	    if ($('#videos').size() > 0) {
            $('.social-btns').after(
		        '<div id=\"video-error-message\">' +
		        '    <p class=\'head\'>We Apologize</p>' +
		        '    <p class=\'body\'>There was an error loading the video you selected.</p>' +
		        '</div>'
		    );
		} else {
            $('.social-btns').after(
		        '<div id=\"video-error-message\" class=\"in-modal\">' +
		        '    <p class=\'head\'>We Apologize</p>' +
		        '    <p class=\'body\'>There was an error loading the video you selected.</p>' +
				'    <p class=\'body\'>Take a look at the <a href=\"#\">Videos page</a>.</p>' +
		        '</div>'
		    );
		}
	};
	/*
	me.refreshSwatches = function() {
		$('.swatch').click(function(){
            if($('a', this.parentNode).hasClass('plus')) return;
            
            $('.innerswatch', $(this).parentNode).removeClass('selected');
            $('.innerswatch', $(this)).addClass('selected');
          
            this.parentNode.parentNode.getElementsByTagName('img')[0].src = $('a', $(this)).attr('rel');
            return false;
        });
	};*/
	
	me.bindGiftCardRemoves = function(){
		
        /* apply gift card balance .. found on step2 billing, elsewhere:[] */
       $('a.remove').click(function(){
           var giftCardRemoveURL = this.href;
           /// end var block
           jQuery('#giftcardpaymentinstruments').load(giftCardRemoveURL,function() {
				jQuery('#giftcardpaymentinstruments').fadeIn('normal');
				jQuery('#order-summary').load(shippingurl,function() {
					jQuery('#order-summary').fadeIn('normal');
				});
           	jQuery('#order-summary').fadeOut('normal');
			});
           jQuery('#giftcardpaymentinstruments').fadeOut('normal');
           		            
	        return false;
	    });
   };

    //onload...
    $(function(){
    	/*
    	$('.swatch').click(function(){
            if($('a', this.parentNode).hasClass('plus')) return;

            $('.innerswatch', $(this).parentNode).removeClass('selected');
            $('.innerswatch', $(this)).addClass('selected');
            
            this.parentNode.parentNode.getElementsByTagName('img')[0].src = $('a', $(this)).attr('rel');
            return false;
        });*/
    	
    	$('.menu_hdr').mouseenter(function(){
    		var parts = this.id.split('-');
    		var name = parts[0]+"-"+parts[1];
    		 ddMenu(name,1);
    	}).mouseleave(function(){
    		var parts = this.id.split('-');
    		var name = parts[0]+"-"+parts[1];
    		ddMenu(name, -1);
    	});
    	
        /* apply the labelOver plugin to all labels with rel="default-text" .. to simulate default-text existing inside the inputs */
        $('label[rel=default-text]').labelOver('default-text');
        
        /* prepare info-bubbles (tooltips) - found on checkout > 'secure' & 'easy returns', elsewhere:[] */
        $('dl.info-bubble-small').each(function(){
            if( getById('wrapper').offsetWidth - (this.offsetLeft - getById('wrapper').offsetLeft) < 188 ){
                //too far to the right for a right-falling bubble. needs to fall left.
                $('dd',this).addClass('righty'); //I chose to call the class righty because the background image's pointer is on the right side.
            }
            $('dd',this).append('<span/>');
        }).bind('mouseover mouseout',function(){
            $('dd',this).toggle();
        });


        /* prepare info-bubbles (tooltips) - found on checkout > 'secure' & 'easy returns', elsewhere:[] */
        $('dl.info-bubble-top').each(function(){
 			$('dd',this).append('<span/>');
		}).bind('mouseover mouseout',function(){
            $('dd',this).toggle();
        });
        
        initMiniCartMouseOvers(false);
        /* WIRE UP MODALS */
        
        /* wire up video overlay links */
        $('a.video-overlay-trigger').click(function(){
            
            var videoUrl = this.rel.substr(6);
            //console.log(videoUrl);
            
            modal({
                title: 'Video'
                ,body: (
                    '<div class="social-btns"><a href="#"><img class="social" src="images/video-player/social-email-link.gif"></a><a href="#"><img class="social" src="images/video-player/social-embed-link.gif"></a><img src="images/video-player/social-links-divider.gif"><a href="#"><img class="social" src="images/video-player/social-facebook-link.gif"></a><a href="#"><img class="social" src="images/video-player/social-delicious-link.gif"></a><a href="#"><img class="social" src="images/video-player/social-digg-link.gif"></a></div>'
                    +'<div id="video-player-holder" style="height:360px"><div id="video-player"></div></div>'
                    +'<div class="video-description"></div>'
                )
                ,width: 480
            });
            
            $('.ui-dialog').addClass('video-player-dialog');
            
            $playerHolder = $('#video-player-holder'); // based on the title!
            
            swfobject.embedSWF("../flash/player.swf", "video-player", "480", "360", "9.0.45", null, {vidToPlay:videoUrl}, {wmode:'opaque',quality:'high',menu:'false'}, {id:'videoPlayer',name:'videoPlayer'});
            
            return false;
        });
        
        /* check gift card balance .. found on step2 billing, elsewhere:[] */

        $('a.check-balance').click(function(){
            var cardnumber = $('#gift-card-number').val(),
                pin = $('#gift-card-pin').val(),
                title = 'Gift Card Balance',
                giftCardBalanceURL = this.href;
            /// end var block

            
            modal({
                title: title
                ,body: 'Retrieving balance...'
            });
        
            $.ajax({
                type: "POST",
                url: giftCardBalanceURL,
                data: 'cardnumber='+cardnumber+'&pin='+pin, //will this service need the pin? should we be sending the pin in the clear?
                success: function(response){
                    modals[title].html(
                        '<dl><dt>Gift Card</dt><dd>'+cardnumber+'</dd></dl>'
                        +'<span class="amount">'+response+'</span>'
                    );
                }
            });

            return false;
        });

         /* apply gift card balance .. found on step2 billing, elsewhere:[] */
        $('a.apply').click(function(){
            var cardnumber = $('#gift-card-number').val(),
                pin = $('#gift-card-pin').val(),
                giftCardApplyURL = this.href;
            /// end var block
           $('div.loader').show(); 
           $.ajax({
               type: "POST",
               url: giftCardApplyURL,
               data: 'cardnumber='+cardnumber+'&pin='+pin, //will this service need the pin? should we be sending the pin in the clear?
               success: function(response){
        	   		$('div.loader').hide();
        	   		$('#gift-card-number').val('');
        	   		$('#gift-card-pin').val('');
                    $('#giftcardpaymentinstruments').html(response);
                    jQuery('#order-summary').load(shippingurl,function() { 
                    	jQuery('#order-summary').fadeIn('normal');
					});
		            jQuery('#order-summary').fadeOut('normal');	            
               }
           });            
           return false;
        });

        me.bindGiftCardRemoves();
        //check for cc required
        
        //handler for shipping selector in checkout2
        $('.shippingmethod').click(function(){
        	jQuery('#order-summary').load(shippingurl+'?shipping='+this.id,function() {
				jQuery('#order-summary').fadeIn('normal');
			});
            jQuery('#order-summary').fadeOut('normal');	            
	        return true;
        });      
        
        /* modal for Forgot Password */
        var forgotHolder = $('#forgot-holder');
        $('a.forgot-password').click(function(){
            modal({
                title: 'Forgot Your Password?'
                ,body: forgotHolder.html()
            });
            return false;
        });

        /* modal for WhatIsThis */
        var whatisthisHolder = $('#whatisthis-holder');
        $('a.whatisthis').click(function(){
            modal({
                title: 'What Is This?'
                ,body: whatisthisHolder.html()
            });
            return false;
        });

        /* modal for technology */
        var technologyHolder = $('#technology-holder');
        $('a.technology-holder').click(function(){
            modal({
                title: 'Learn More About Technology'
                ,body: technologyHolder.html()
            });
            return false;
        });
               
        /* modal for newsletter */
        var newsletterSignupHolder = $('#newsletter-signup-holder');
        
        $('#footer-email-form').submit(function() {
        	if(validateEmail())
        		signupNewsletter();
        	return false;
        });
        
        var validateEmail = function() {
    		var __re_email = "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$";
    		var __re = new RegExp(__re_email, "i");
    		var $email = $('#footer-email');
    		if (!__re.test($email.val())) {
    			$email.val('Enter a valid email');
    			$email.css({color:'#7F0000'});
    			$email.blur();
    		} else {
    			$('#email').css({ color:'#868686' });
    			return true;
    		}
    		return false;	
        }
        
        var signupNewsletter = function () {

            modal({
                title: 'Email Sign-up'
                ,body: newsletterSignupHolder.html()
                ,width: 390
            });
            $(".loader").toggle();
			var form = $("#footer-email-form");
				
			if(form == null) return;
			this.loading = true;
			url = form.attr("action");
			
			var handlerFunc = function(req) {					
				
				$('#modal-' + onlyAlphaNumericOld( 'Email Sign-up' ).toLowerCase()).html( req, function() {
					$("div.loader").toggle();
				} );	

	            $('.ui-dialog-content .customize-prefs').click(function(){
	                // hide the link which triggered the extra fields and
	                // show the extra fields.
	                $('.ui-dialog-content .customization-closed,.ui-dialog-content .customization-open').toggle();
	                // thanks to the display of the extra fields, the dialog is taller - move it up a bit.
	                $('.ui-dialog').css('marginTop',-(document.body.clientHeight/10));
	                // now that it's visible, style the select.
	                rf.styleSelects('.ui-dialog select');
	                return false;
	            });
				
				$(".ui-dialog-content .select-all").click(function()
				{
					$(".ui-dialog input.newsletters-box").each(function()
					{
						this.checked = true;
					});
	                return false;
				});
				
				$(".ui-dialog-content .cancel-customization span").click(function()
				{
					$('#modal-' + onlyAlphaNumericOld( 'Email Sign-up' ).toLowerCase()).remove();
	                return false;
				});
								
			}				
			
			jQuery.post(url,{email: jQuery('#footer-email').val()},handlerFunc);

            return false;
        }

		/* DATE PICKER */
		Date.firstDayOfWeek = 7;
		Date.format = 'mm/dd/yyyy';
		$('.date-pick').datePicker({clickInput:true});
		/* end DATE PICKER */

		// credit card and addrese popup have been replaced
        if ( typeof dwReplaced == "undefined" )
        {
	        /* modals for address */
	        var editHolder = $('#edit-holder');
	        $('.account a.edit').click(function(){
	            modal({
	                title: 'Edit Address'
	                 ,body: editHolder.html()
	                ,width: 450
	            });
	            return false;
	        });
	        $('.account .create-new-address').click(function(){
	            modal({
	                title: 'Edit Address'
	                 ,body: editHolder.html()
	                ,width: 450
	            });
	            return false;
	        });
	        $('.account .add-new-address').click(function(){
	            modal({
	                title: 'Edit Address'
	                 ,body: editHolder.html()
	                ,width: 450
	            });
	            return false;
	        });
	
	
	        /* modals for address */
	        var editHolder = $('#edit-holder');
	        $('.account a.edit').click(function(){
	            modal({
	                title: 'Edit Address'
	                 ,body: editHolder.html()
	                ,width: 450
	            });
	            return false;
	        });
	        $('.account .create-new-address').click(function(){
	            modal({
	                title: 'Edit Address'
	                 ,body: editHolder.html()
	                ,width: 450
	            });
	            return false;
	        });
	        $('.account .add-new-address').click(function(){
	            modal({
	                title: 'Edit Address'
	                 ,body: editHolder.html()
	                ,width: 450
	            });
	            return false;
	        });
	
	
	        /* modals for cards */
	        var editCCHolder = $('#edit-cc-holder');        
	        $('a.edit-cc').click(function(){
	            modal({
	                title: 'Add/Edit Credit Card'
	                 ,body: editCCHolder.html()
	                ,width: 450
	            });
	            return false;
	        });
	        $('.account .add-new-card').click(function(){
	            modal({
	                title: 'Add/Edit Credit Card'
	                 ,body: editCCHolder.html()
	                ,width: 450
	            });
	            return false;
	        });
	        
	        
		}

        /* modals for product details */
        //var readBlogPostHolder = $('#read-blog-post-holder');        
        $('a.read-blog-link').click(function(){
        	
        	var __bpid = this.attributes['postuid'].value;
        	
            modal({
                    title: 'Inside Out'
                    ,body: 'Retrieving blog post...'
                    ,width: 565
                });

                $.ajax({
                    type: "POST",
                    url: 'BlogModal-GetPost',
                    data: 'bpid=' + __bpid, 
                    success: function(response){
                        modals['Inside Out'].html(response);
                    }
                    ,error:function(){
	                    modals['Inside Out'].html(
	                        '<div class="forgot-holder" id="confirmation-message">'
	                        +'<h3>Error</h3>'
	                        +'<p>There was a problem sending your request.</p>'
	                        +'</div>'
	                    );
	                }
                });
                
            return false;
        });

        /* WHAT IS THIS */
        $('a.load-content-asset-modal').click(function(){
        	
        	var __cid = this.attributes['contentasset'].value;
        	var __url = this.attributes['url'].value;
        	var __width = ((this.attributes["mwidth"] == null) ? 400 : parseInt(this.attributes["mwidth"].value));
        	var __title = ((this.attributes["mtitle"] == null) ? "Content Modal" : this.attributes["mtitle"].value);
        	
            modal({
                    title: __title
                    ,body: 'Loading...'
                    ,width: __width                
                });

                $.ajax({
                    type: "GET",
                    url: __url,
                    data: 'cid=' + __cid, 
                    success: function(response){
                        modals[__title].html(response);
                    }
                    ,error:function(){
	                    modals[__title].html(
	                        '<div class="forgot-holder" id="confirmation-message">'
	                        +'<h3>Error</h3>'
	                        +'<p>There was a problem sending your request.</p>'
	                        +'</div>'
	                    );
	                }
                });
            return false;
        });

        /* WHAT IS THIS */
        $('a.load-content-asset-modal-boxie').click(function(){
        	
        	var __cid = this.attributes['contentasset'].value;
        	var __url = this.attributes['url'].value;
        	
            modal({
                    title: 'A Box life'
                    ,body: 'Loading...'
                    ,width: 800
                    
                });

                $.ajax({
                    type: "GET",
                    url: __url,
                    data: 'cid=' + __cid, 
                    success: function(response){
                        modals['A Box life'].html(response);
                    }
                    ,error:function(){
	                    modals['A Box life'].html(
	                        '<div class="forgot-holder" id="confirmation-message">'
	                        +'<h3>Error</h3>'
	                        +'<p>There was a problem sending your request.</p>'
	                        +'</div>'
	                    );
	                }
                });
            return false;
        });
        
        /* 360 Spinner Modal */
        $('a.360spinner-modal').click(function(){
        	var __url = this.attributes['url'].value;
        	var __media = this.attributes['media'].value;
        	
            modal({
                    title: 'Spinner Window'
                    ,body: 'Loading...'
                    ,width: 790
                    ,height: 590
                });
				
                $.ajax({
                    type: "GET",
                    url: __url,
                    success: function(response){
                        modals['Spinner Window'].html(response);
                    }
                    ,error:function(){
	                    modals['Spinner Window'].html(
	                        '<div class="forgot-holder" id="confirmation-message">'
	                        +'<h3>Error</h3>'
	                        +'<p>There was a problem sending your request.</p>'
	                        +'</div>'
	                    );
	                }
                });
            return false;
        });
        
        /* Size Chart */
        $('a.size-chart').click(function(){
        	
        	var __cid = this.attributes['contentasset'].value;
        	var __url = this.attributes['url'].value;
        	
            modal({
                    title: 'Size Chart'
                    ,body: 'Loading...'
                    ,width: 790
                });
				
                $.ajax({
                    type: "GET",
                    url: __url,
                    data: 'cid=' + __cid, 
                    success: function(response){
                        modals['Size Chart'].html(response);
                    }
                    ,error:function(){
	                    modals['Size Chart'].html(
	                        '<div class="forgot-holder" id="confirmation-message">'
	                        +'<h3>Error</h3>'
	                        +'<p>There was a problem sending your request.</p>'
	                        +'</div>'
	                    );
	                }
                });
            return false;
        });
        
        /* Enlarge Image Modal */
        $('a.scene7enlarge-modal').click(function(){
        	var __url = this.attributes['url'].value;
        	var __media = this.attributes['media'].value;
        	
            modal({
                    title: 'Enlarge Window'
                    ,body: 'Loading...'
                    ,width: 790
                    ,height: 590
                });
				
                $.ajax({
                    type: "GET",
                    url: __url,
                    success: function(response){
                        modals['Enlarge Window'].html(response);
                    }
                    ,error:function(){
	                    modals['Enlarge Window'].html(
	                        '<div class="forgot-holder" id="confirmation-message">'
	                        +'<h3>Error</h3>'
	                        +'<p>There was a problem sending your request.</p>'
	                        +'</div>'
	                    );
	                }
                });
            return false;
        });
        
        
        /* Video player modal */
        $('a.video-player-modal').click(function(){
        	
        	var __url = this.attributes['url'].value;
        	var __media = this.attributes['media'].value;
        	var __title = ((this.attributes["title"] == null) ? "Featured Video" : this.attributes["title"].value);
        	
            modal({
                    title: __title
                    ,body: 'Loading Video...'
                    ,width: 530
                });
				
                $.ajax({
                    type: "POST",
                    url: __url,
                    data: 'media=' + __media,
                    success: function(response){
                        modals[__title].html(response);
                    }
                    ,error:function(){
	                    modals[__title].html(
	                        '<div class="forgot-holder" id="confirmation-message">'
	                        +'<h3>Error</h3>'
	                        +'<p>There was a problem sending your request.</p>'
	                        +'</div>'
	                    );
	                }
                });
            return false;
        });
     
     

                           

        /* modal for email a friend */
        var emailFriendHolder = $('.email-friend-holder');        
        $('.email-friend-btn').click(function(){
            modal({
                title: 'Share the product or article you discovered on Columbia.com.'
                 ,body: emailFriendHolder.html()
                ,width: 400
            });
            return false;
        });


        /* modal for remove account */
        var removeAccountHolder = $('#remove-account-holder');        
        $('a.remove-account').click(function(){
            modal({
                title: 'Unenroll In Greater Rewards?'
                 ,body: removeAccountHolder.html()
                ,width: 357
            });
            return false;
        });

        /* modal for remove account */
        var getDirectionsHolder = $('#get-directions-holder');        
        $('a.get-directions').click(function(){
            modal({
                title: 'Get Directions to Store'
                 ,body: getDirectionsHolder.html()
                ,width: 357
            });
            return false;
        });
		
		/* modal for enlarge */
        $('.s7-enlarge').click(function(){
        	var enlargeHolder = $(this).next();
            modal({
                title: $($('#page h1').get(0)).html()
                 ,body: enlargeHolder.html()
                ,width: 450
            });
            return false;
        });

        
        /* handle show/hide Change Password on Profile page */
        $('#pw-open,#pw-close').click(function(){
            $('#pw-open,#pw-close,#change-pw-fields').toggleClass('hidden');
        });		
		
        /* handle show/hide menu items on Videos page */
        $('.selections li .clicker').click(function(){
			$(this).toggle();
			$(this).next().toggle();
			return false;
        });
		
        $('.selections li .content p').click(function(){
			//console.log('title has been clicked');
			$(this).parent().parent().children().toggle();
			return false;
        });
		
        /* handle Select buttons on Gift Cards page */
        var giftCardForms = $('#standard-form,#egift-form');
        var giftCardButtons = $('#select-standard,#select-egift')
            .click(function(e){
                var which = (giftCardButtons.get(0) == e.target.parentNode) ? 0 : 1;
                var other = which == 0 ? 1 : 0;
                $(giftCardForms.get(which)).addClass('selected');
                $(giftCardForms.get(other)).removeClass('selected');
                return false;
            });
        ///
             
        /* limit textarea-s with the class of 'limited' to a max of 250 characters */
        $('textarea.limited').keyup(function(){
        	
        	var limit = 250,
                text = $(this).val(),
                textlength = text.length,
                charCountInfo = $('.char-count', this.parentNode);
            /// end var block;
        
        	/// Modified next section to fix Bug 2164   tschwartz 9-2-09
            if (textlength>limit) {  
            	$(this).val( text.substr(0, limit) );
            	this.scrollTop = this.scrollHeight;
        	}
       
            charCountInfo.html( (limit - $(this).val().length) + ' characters remaining' );
            return false;
            
        }).keyup();
        
        
        /* limit textarea-s with the class of 'limitedreview' to a max of 900 characters */
        $('textarea.limitedreview').keyup(function(){
        	
        	var limit = 900,
                text = $(this).val(),
                textlength = text.length,
                charCountInfo = $('.char-count', this.parentNode);
            /// end var block;
        
        	/// Modified next section to fix Bug 2164   tschwartz 9-2-09
            if (textlength>limit) {  
            	$(this).val( text.substr(0, limit) );
            	this.scrollTop = this.scrollHeight;
        	}
       
            charCountInfo.html( (limit - $(this).val().length) + ' characters remaining' );
            return false;
            
        }).keyup();
        
        
        /* limit textarea-s with the class of 'limited' to a max of 250 characters */
        $('textarea.limitedCO').keyup(function(){

            var limit = 230,
                text = $(this).val(),
                textlength = text.length,
                charCountInfo = $('.char-count', this.parentNode);
            /// end var block;
            
            $(this).val( text.substr(0, limit) );
            this.scrollTop = this.scrollHeight;
            
            charCountInfo.html( (limit - $(this).val().length) + ' characters remaining' );
            return false;
            
        }).keyup();
        
        me.forgotPassword = function(form){
            var inputDiv = $('.ui-dialog-content');
            var inputs = $('input',form);
            $.ajax({
                type: "POST"
                ,url: form.action
                ,data: inputs
                ,success:function(response){
                    /* need to update below if web service returns something else */
                    var myResponse = eval('(' + response + ')');
                    if(myResponse.isSuccess){
                        inputDiv.html(
                            '<div class="forgot-holder" id="confirmation-message">'
                            +'<h3>Password Sent</h3>'
                            +'<p>' + myResponse.message + '</p>'
                            +'</div>'
                        );
                    } else {
                        if($('.warning',form).size() == 0){
                            $('fieldset',form)
                                .addClass('error')
                                .prepend(
                                    '<p class="warning"></p><br/>'
                                ); 
                        } 
 						if (myResponse.isMissing) {
							$('.warning',form).html(myResponse.missing); 	
 						} else {
 							var message="We are sorry! No account was found for that email<br/>address. Please try again or ";
 							message += "<a href=" + myResponse.link + ">register now</a>";
							$('.warning',form).html(message);
 						}
                    }
                }
                ,error:function(){
                    inputDiv.html(
                        '<div class="forgot-holder" id="confirmation-message">'
                        +'<h3>Error</h3>'
                        +'<p>There was a problem sending your request.</p>'
                        +'</div>'
                    );
                }
            })
            return false;
        };
 
         me.emailFriend = function(form){
            var inputDiv = $('.ui-dialog-content');
            var inputs = $('input,textarea',form);
            $.ajax({
                type: "POST"
                ,url: form.action
                ,data: inputs
                ,success:function(response){
                    /* need to update below if web service returns something else */          	
            		var myResponse = eval('(' + response + ')');
                    if(myResponse.isSuccess){
                        inputDiv.html(
                            '<div class="email-friend-holder" id="confirmation-message">'
                            +'<h3>Product Shared</h3>'
                            +'<p>' + myResponse.message + '</p>'
                            +'</div>'
                        );
                    } else {
                    	if (myResponse.errorCode.indexOf('0') != -1) 
                    		$('.warning:eq(0)',form).html("Please fix the errors noted below.");
                    	
                    	var retCode = myResponse.errorCode.split(';');
                    	
                    	(retCode[0] == "0") ? $('.inputKey:eq(0)',form).css("color", "red") : $('.inputKey:eq(0)',form).css("color", "black");    	// sender FN
                    	(retCode[1] == "0") ? $('.inputKey:eq(1)',form).css("color", "red") : $('.inputKey:eq(1)',form).css("color", "black");		// sender's LN
                    	if (retCode[2] == "0") { 																									
                    		$('.inputKey:eq(2)',form).css("color", "red");
                    		$('.warning:eq(1)',form).html("");
                    	} else if (retCode[2] == "-1") {
                    		$('.inputKey:eq(2)',form).css("color", "red");
                    		$('.warning:eq(1)',form).html("Invalid email.");
                    	} else {
                    		$('.inputKey:eq(2)',form).css("color", "black");
                    		$('.warning:eq(1)',form).html("");
                    	}																															
                    	(retCode[3] == "0") ? $('.inputKey:eq(3)',form).css("color", "red") : $('.inputKey:eq(3)',form).css("color", "black");		// friend's FN
                    	(retCode[4] == "0") ? $('.inputKey:eq(4)',form).css("color", "red") : $('.inputKey:eq(4)',form).css("color", "black");		// friend's FN
                    	(retCode[5] == "0") ? $('.inputKey:eq(5)',form).css("color", "red") : $('.inputKey:eq(5)',form).css("color", "black");		
                    	if (retCode[5] == "0") { 																									
                    		$('.inputKey:eq(5)',form).css("color", "red");
                    		$('.warning:eq(2)',form).html("");
                    	} else if (retCode[5] == "-1") {
                    		$('.inputKey:eq(5)',form).css("color", "red");
                    		$('.warning:eq(2)',form).html("Invalid email.");
                    	} else {
                    		$('.inputKey:eq(5)',form).css("color", "black");
                    		$('.warning:eq(2)',form).html("");
                    	}
                    }
                }
                ,error:function(){
                    inputDiv.html(
                        '<div class="email-friend-holder" id="confirmation-message">'
                        +'<h3>Error</h3>'
                        +'<p>There was a problem sending your request.</p>'
                        +'</div>'
                    );
                }
            })
            return false;
        };
 
        $('#email-friend-cancel').click(function(){
        	alert('email friend cacncel clicked');
        });
 
        //hover utility for promos on activity landing page.
        $('.activity-landing .browse li').hover(function(){
               $(this).addClass('over');
        }, function() {
               $(this).removeClass('over');
        });
		//function for forms toggling
		$('input[class="request-type"]').click(function() {
			if (this.id == 'request-type1') {
				$('#giving-back-fields').hide();$('#promotional-fields').hide();$('#advertising-fields').show();
				rf.styleSelects('#promotional-fields select');
				$(".onoffradio1").children().attr("disabled","disabled");
				$(".onoffradio2").children().attr("disabled","disabled");
				$(".onoffradio3").children().attr("disabled","disabled");
			}
			if (this.id == 'request-type2') {
				$('#giving-back-fields').hide();$('#promotional-fields').show();$('#advertising-fields').hide();
				rf.styleSelects('#advertising-fields select');
			}
			if (this.id == 'request-type3') {
				$('#giving-back-fields').show();$('#advertising-fields').hide();$('#promotional-fields').hide();
				rf.styleSelects('#giving-back-fields select');
			}
		});
		//function for subforms toggling

		 $('input[class="onoffradio"]').click(function() {
			if (this.id == 'onoffradio1') {
				$(".onoffradio1").children().attr("disabled","");
				$(".onoffradio2").children().attr("disabled","disabled");
				$(".onoffradio3").children().attr("disabled","disabled");
				$(".onoffradio2").children().attr("checked","");
				$(".onoffradio3").children().attr("checked","");
			}
			if (this.id == 'onoffradio2') {
				$(".onoffradio1").children().attr("disabled","disabled");
				$(".onoffradio2").children().attr("disabled","");
				$(".onoffradio3").children().attr("disabled","disabled");
				$(".onoffradio1").children().attr("checked","");
				$(".onoffradio3").children().attr("checked","");
			}
			if (this.id == 'onoffradio3') {
				$(".onoffradio1").children().attr("disabled","disabled");
				$(".onoffradio2").children().attr("disabled","disabled");
				$(".onoffradio3").children().attr("disabled","");
				$(".onoffradio1").children().attr("checked","");
				$(".onoffradio2").children().attr("checked","");
			}
		});

		
		/**
         * Flagging of Products for Comparison
         */
        /*
        var productsFlaggedForComparison = [],
            maxProductsFlaggableForComparison = 3,
            flagForCompareSummary = $('#flag-for-compare-summary').click(function(){
                
                alert('Integration-point:\nProducts flagged for comparison = [ '+productsFlaggedForComparison.toString()+' ]');
                
            });
        ///
        
        // Enable/disable compare: (TODO: Button layout..)
        
        jQuery('#enableCompare').click(function(){
           jQuery('#enableCompare').hide();
           jQuery('#disableCompare').show();
           jQuery('.compare-product-flag').toggle();
           
        });
        
        jQuery('#disableCompare').click(function(){
           jQuery('#enableCompare').show();
           jQuery('#disableCompare').hide();
           jQuery('.compare-product-flag').toggle();
        });
        
        
        $('.compare-product-flag').click(function(){
            var $this = $(this),
                defaultText = 'flag for compare',
                toggledText = 'unflag for compare',
                toggledClass = 'compare-product-flag-toggled',
                productId = $this.attr('rel').substr(10),
                numProductsFlaggedForComparison = productsFlaggedForComparison.length;
            ///
            if($this.hasClass(toggledClass)){
                //already flagged for compare
                var t = [];
                for(var i=0; i<numProductsFlaggedForComparison; i++){
                    var currentId = productsFlaggedForComparison[i];
                    (currentId != productId && t.push(currentId));
                }
                productsFlaggedForComparison = t;
                --numProductsFlaggedForComparison;
                $this.removeClass(toggledClass).html(defaultText);
            } else {
                if(numProductsFlaggedForComparison != maxProductsFlaggableForComparison){
                    //NOT already flagged for compare and not already at the max number of comparables
                    ++numProductsFlaggedForComparison;
                    productsFlaggedForComparison.push(productId);
                    $this.addClass(toggledClass).html(toggledText);
                }
            }
            flagForCompareSummary
                .html(numProductsFlaggedForComparison + ' of ' + maxProductsFlaggableForComparison)
                .css({
                    'background-position': (numProductsFlaggedForComparison > 1 ? '0 -21px' : '0 0'),
                    'background-color': (numProductsFlaggedForComparison > 1 ? '#0093D1' : '#8C8C8C')
                });
            ///
            return false;
        });
        */
        //This function call initalizes the quick shop
        initializeQuickShop();

        $('.filterRemoved a').click(function(){
            var $this = $(this);
            $('.filter a').removeClass('on');
            $('.filter h6 a').removeClass('on');
 			$('.filter li').removeClass('open');
 			$this.addClass("on");

 			while (!$this.parent().hasClass('browse-grid')) { 				
 				$this = $this.parent();
 				if ($this.attr('tagName').toLowerCase()=='li') $this.addClass('open');
 				if ($this.attr('tagName').toLowerCase()=='ul') $this.prev('h6').find('a').addClass('on');
 				if ($this.attr('tagName').toLowerCase()=='ul') $this.prev('a').addClass('on'); 			
 			}

            me.filterResults(this.href);
            return false;
        });
        
        $('.filterNav a').click(function(){
            var $this = $(this);
            me.filterResults(this.href);
            return false;
        });        
        
        //update left nav by passing an a element and matching the href attr
        me.updateLeftNav = function(el) {

        	var $this = $(".filter a[href='"+el.href+"']");
        	$('.filter a').removeClass('on');
            $('.filter h6 a').removeClass('on');
 			$('.filter li').removeClass('open');
        	$this.addClass("on");
        	while (!$this.parent().hasClass('browse-grid')) { 				
 				$this = $this.parent();
 				if ($this.attr('tagName').toLowerCase()=='li') $this.addClass('open');
 				if ($this.attr('tagName').toLowerCase()=='ul') $this.prev('h6').find('a').addClass('on');
 				if ($this.attr('tagName').toLowerCase()=='ul') $this.prev('a').addClass('on'); 			
 			}
 			return false;
 			
        };
        
        //if selected category is found render nav
        if($('.filter a.on').length>0) {
	        me.updateLeftNav($('.filter a.on')[0]);
    	}
    	    
        // ajax breadcrumbs (sub cats only!)
        me.ajaxCrumbs = function() {
	        $('a.ajaxbread').click(function(){
	            me.updateLeftNav(this);
	            me.filterResults(this.href);
	            return false;
	        });
		};
		me.ajaxCrumbs();
		
        // enable small-banner ajax calls
        me.bindsmallbanner = function() {
	        $('a.smallbanner').click(function(){
	            me.updateLeftNav(this);
	            me.filterResults(this.href);
	            return false;
	        });
		};
		me.bindsmallbanner();
		
		// technology refinements
        me.bindTechnology = function() {
	        $('ul.technologies a').click(function(){
	            me.filterResults(this.href);
	            return false;
	        });
		};
		me.bindTechnology();
		me.rebindTechInfoBubbles = function() {
			$('dl.info-bubble-top').each(function(){
 				$('dd',this).append('<span/>');
			}).bind('mouseover mouseout',function(){
            	$('dd',this).toggle();
        	});		
		};
		
        //grid paging handler
        me.paging = function() {
        	$('#results-col .pages a').click(function(){
	            var $this = $(this);
	            jQuery("#results-col").load(this.href + '&format=ajax',function() {
					if($this.hasClass('all')) {            		
	            		$('body').removeClass('large-grid medium-grid small-grid');
	            		$('body').addClass('medium-grid');
	            	}
					initializeQuickShop();					
					jQuery("#results-col").fadeIn("normal");
				});
	            jQuery("#results-col").fadeOut("normal");                     
	            return false;
        	});
        }
        me.paging();
                
        //grid page size handler
        me.pageSizes = function() {
        	$('.sizes a').click(function(){
        		
	            var $this = $(this);
	            jQuery("#results-col").load(this.href + '&format=ajax',function() {
					$('body').removeClass('large-grid medium-grid small-grid');
					if($this.hasClass('image-link1')) {            		
	            		$('body').addClass('small-grid');
	            	}else if($this.hasClass('image-link2')) {
	            		$('body').addClass('medium-grid');
	            	}else if($this.hasClass('image-link3')) {
	            		$('body').addClass('large-grid');
	            	}
					initializeQuickShop();
					jQuery("#results-col").fadeIn("normal");				
				});
	            jQuery("#results-col").fadeOut("normal");                       
	            return false;
        	});
        }
        me.pageSizes(); 
        
        me.filterResults = function(url){
            var currentCategory = "";
        	var cgidpos = url.search(/cgid/);

            if(cgidpos != -1) {
            	var tmpURLString = url.substr(cgidpos+5);
            	
            	cgidpos = tmpURLString.search(/&/);
            	
            	if(cgidpos != -1) {
            		tmpURLString = tmpURLString.substring(0, cgidpos);
            	}
            	
            	currentCategory = tmpURLString;
            	
            	// after getting the current category id this must be changed
            	// in every a tag of the product filter
            	
            	var aItemUrl = "";
            	var aItemCgidStart = 0;
            	var aItemCgidEnd = 0;
            	var aItemTmp = 0;
            	
            	jQuery("#product-filters a").each(function (i, aitem) {
            		
            		//only target links should be affected, no anchor tags
            		if(aitem.href) {
            			
	            		//change relative target links, that just containes a sharp,
            			//to its absolute representation 
	            		if(aitem.href == '#') {
	            			aitem.href = window.location + '#';            			
	            		}
	            		
	            		//now search for the cgid value in the url
	            		
	            		aItemUrl = aitem.href;
	            		aItemTmp = aItemUrl.search(/cgid/);
	            		
	            		//if no cgid parameter found, skip this
	            		if(aItemTmp != -1) {
	            			aItemCgidStart = aItemTmp+5;
	            			
	            			//get end of cgid value
	            			aItemTmp = aItemUrl.substr(aItemCgidStart).search(/&/);
	            	
	            			if(aItemTmp == -1) {
	            				aItemTmp = aItemUrl.length;
	            			} else {
	            				aItemTmp += aItemCgidStart;
	            			}
	            			
	            			aItemCgidEnd = aItemTmp;
	            			
	            			//create new url and assign this to the current a elem href
	            			aItemTmp = aItemUrl.substring(0,aItemCgidStart) + currentCategory + aItemUrl.substring(aItemCgidEnd);
	            			aitem.href = aItemTmp;
	            			
	            			
	            			//set refineBaseUrl to current url, to provide the current cgid being used
	            			refineBaseUrl = aItemTmp;
	            		}
            		}
            	});
            }

            if ($('#image-link1[@rel="viewAll"]')) {
            	var gridsize = 1024;
        		
	            if($('body').hasClass('small-grid')) {            		
	        		gridsize = 1032;
	        	} else if ($('body').hasClass('large-grid')) {
	        		gridsize = 1014;
	        	}
            } else {
	            var gridsize = 24;
		
	            if($('body').hasClass('small-grid')) {            		
	        		gridsize = 32;
	        	} else if ($('body').hasClass('large-grid')) {
	        		gridsize = 14;
	        	}
            }
            
            //alert(url + (url.match(/\?/)?'&':'?') + 'sz=' + gridsize + '&format=ajax');
         //   debugger;
            jQuery("#results-col").load(url + (url.match(/\?/)?'&':'?') + 'sz=' + gridsize + '&format=ajax',function() {
				
            	initializeQuickShop();
				jQuery("#results-col").fadeIn("normal");
			});
            jQuery("#results-col").fadeOut("normal");
        
        };
        
        //update breadcrumbs
        
        me.updateBreadcrumbs = function(crumbs) {
        
			if(crumbs == null) return;
			this.loading = true;
			$('#nav-trail').empty();
			$('#nav-trail').append(crumbs);        
        
        };
        
        me.updaterefinementfilter = function(divid, filterhtml) {      
        	//alert(filterhtml);
			if(filterhtml == null) return;
			if(divid == null) return;
			this.loading = true;
			$('#'+divid).empty();
			$('#'+divid).append(filterhtml);       
			
        };
        
        $('.alternate-views-list li').click(function(){
            var el = $(this);
            // clear any existing selected alternate view
            $('li',this.parentNode).removeClass('selected');
            // 'select' this alternate view = set this element's className to 'selected'.
            el.addClass('selected');
            //load up the appropriate scene 7 image, based on the rel attribute of the LI.
            $('.s7-stack img').eq(0).attr('src', $(this).attr('rel'));
            return false;
        });
        
        //Newsletter checkboxes
        me.newsletterOptions = function() {
			
			/* handle Select All button on Profile page */
	        var selectAllBtn = $('#select-all-interests');
	        selectAllBtn.click(function(){
				selectAll('.interests input');
	            return false;
	        });
			if ($('#newsletter-box').attr('checked') == false) {
				$('#interests .checkbox').each(function(){
      				this.checked = false;
      				this.disabled = true;
      				$('#select-all-interests').unbind('click');
		       	});
	       	}
        	$('#newsletter-box').click(function() {
     		    $('#interests')[this.checked?'show':'hide']();
        		if (this.checked == true) {        			
         			$('#interests .checkbox').each(function(){
        				this.disabled = false;
        			});
					/* handle Select All button on Profile page */
			        var selectAllBtn = $('#select-all-interests');
			        selectAllBtn.click(function(){
						selectAll('.interests input');
			            return false;
			        });
        		}else{					
        			$('#interests .checkbox').each(function(){
        				this.checked = false;
        				this.disabled = true;
        				$('#select-all-interests').unbind('click');
        			});
        		}
        		return true;        		
        	});        	        
        };
        
        me.newsletterOptions();
		
		function selectAll(selectors) {
			$(selectors).each( function() {
				this.checked = true;
			});
		};
		
		//newsletter optin dialog (footer) handlers

		
			
			
		me.bindCustomizeClickToSubmit = function() {
			
			$("#save-customization").unbind("click").bind("click", function(e) {					
				var form = $("#email-customization");
				me.doSubscribe(form);
				return false;					
			});
			
		};
		
		me.doSubscribe = function(form) {
			
			if(form == null) return;
			this.loading = true;
			var url = null;
			url = form.attr("action");
			var json = form.serialize();
			$(".newsletter-signup-holder").html('<div class="loader" />');
			$("div.loader").toggle();
			$('.ui-dialog').css('marginTop',0);
			var handlerFunc = function(req) {					
				me.updateBox(req);					
			}				
			jQuery.post(url,json,handlerFunc);
		
		};
		
		me.updateBox = function(req) {
	
			$(".newsletter-signup-holder").html( req, function() {
				$("div.loader").toggle();
			});

		};
			

        
        //wire up search box for autocomplete
        //$("#global-search-text").autocomplete("services/search-autocomplete.html");
        
    });//End Onload

    /**
     * wireVideos
     * @description: 
     *      wires up elements so that clicking them plays the corresponding video.
     *      this is only used on pages that have the video player on the page, and not for video player overlays.
     * @param selector: 
     *      the css selector indicating the elements to wire up.
     * @setup:
     *      the elements should have a className of the form "v_VIDEOID", but may have more than one className (ie. "selected" or "hover")
     *      elements with the following ids must exist and be visible at the time of element click: ["videoPlayer","video-title","video-descr"]
     *          videoPlayer: the object that represents the flash video player instance.
     *          video-player-holder: the element that holds the flash video player instance (required for dynamically adjusting container height based on video height)
     *          video-title: a container for the video title
     *          video-desc: a container for the video description
     *          video-head: a container for the video IMAGE header (such as an H1). The image header will be applied as a background image. (unless we do sifr)
     */
    me.wireVideos = function(selector){
        var videoIds = [];
        var videoData = [];
        
        $playerHolder = $('#video-player-holder');
        
        function className2Id(el){
            return el.className ? el.className.replace(/v_([^" ]+).*/,'$1') : null;
        }
        
        $(selector).each(function(){
            videoIds.push( className2Id(this) );
        }).click(function(){
            var vid,
                id = className2Id(this);
            for(var i=0,l=videoData.length;i<l;i++){
                var d = videoData[i];
                if( d && d.id == id ){
                    vid = d;
                }
            }
            $(selector).removeClass('selected');
            $(this).addClass('selected');
            $('#video-title,#video-head').html(vid.title);
            $('#video-head').css('background', 'url('+vid.headerURL+') 0 4px no-repeat');
            $('#video-desc').html(vid.longText);
//            getById('videoPlayer').playVideo(vid.src);
            getById('videoPlayer').playVideo("../" + vid.src);
        });
        
        // utility function-s
        // Array.indexOf( value, begin, strict ) - Return index of the first element that matches value
        function arrayIndexOf ( v, b, s ) {
            for( var i = +b || 0, l = this.length; i < l; i++ ) {
                if( this[i]===v || s && this[i]==v ) { return i; }
            }
            return -1;
        };
        // Array.unique( strict ) - Remove duplicate values
        function arrayUnique ( b ) {
            var a = [], i, l = this.length;
            for( i=0; i<l; i++ ) {
                if( arrayIndexOf.call(a, this[i], 0, b ) < 0 ) { a.push( this[i] ); }
            }
            return a;
        };
        
        // make sure we are only requesting unique ids.
        videoIds = arrayUnique.call(videoIds);
        
        // request the video data for the video selections we have
        $.ajax({
            type: "GET",
            url: "/services/video-data.html",
            data: 'id='+videoIds.join('&id='),
            success: function(msg){
                videoData = eval('('+msg+')');
            }
        });
    };

/**
*Start of home page function
* this function has been moved from home.js to rf.js.
* it is needed to handle the mouseovers on the home page.	
*/
wireUpMosaic = function(){
    jQuery('#mosaic>div>div').mouseover(function(){
        jQuery(this).addClass('hover');
        if(window.fixpng && !this.fixed){
            jQuery('img',this).each(function(){
                fixpng(this);
            });
            this.fixed = true;
        }
    }).mouseout(function(){
        jQuery(this).removeClass('hover');
    }).each(function(){
        if(jQuery('html.ie6').size()){
            jQuery('.rollover-content',this).prepend('<div style="background:#000;z-index:-1;position:absolute;top:0;left:0;width:600px;height:600px;filter:alpha(opacity=80)"></div>');
        }
    });
    
};

/**
 * Initializes the Quick Shop
 */
initializeQuickShop = function(){
	
    // wire up quick shop
    var itemPics = $('.item-pic');
    var cartItems = $('.cartitemedit');
    
    if($('body').attr('className').indexOf('-grid') > -1){
        // add quickbrowse markup.
        // gotchya = the markup will probably have to be different for each product, depending on available sizes & colors & whatnot.
        var quickShopLayer = document.createElement('div');
        quickShopLayer.className = 'quick-shop-dialog';
        // these styles need to be applied immediately, can't even wait for css to be parsed and applied from an external stylesheet :(
        quickShopLayer.style.position = 'absolute';
        quickShopLayer.style.left = '-9999px';
        $('.results-col').append(quickShopLayer);
        
        $(quickShopLayer).css('display','none');
        
        $('a.add-to-wishlist').click(function(){
            //do add to wishlist.. (setTimeout only need to prevent alert from interfering with return, setTimeout not noramlly required here.)
            setTimeout(function(){alert('do add-to-wishlist');}, 100);
            return false;
        });
        
        //provide a getter for the private variable.
        //products.js needs it in order to know what product image to update when selecting colors.
        me.getLastClickedGridItem = function(){
            return lastClickedItemPic;
        };
        
        var isBeforeQuickShopDialogShown = true;
        var lastClickedItemPic;
        // show the quick shop button if the mouse is over an image
        $('.item-pic').bind('mouseover', function () {
            // if quick shop is hidden show it
            if(!$('.quick-shop', this.parentNode).is(':visible')) {
            	$('.quick-shop', this.parentNode.parentNode).hide();
                $('.quick-shop', this.parentNode).show(100);
            }
        });
        // hide the quickshop, but only if the mouse goes out of the image
        $('.item-pic').bind('mouseout', function(e) {
            if(!$(e.relatedTarget).hasClass('quick-shop-image') && !$(e.target).hasClass('quick-shop-image')) {
                //product image left on itself
                $('.quick-shop', this.parentNode).hide(50);
            }
            else {
            	if(($(e.relatedTarget).hasClass('quick-shop-image') && $(e.target).hasClass('image-product-mini')) ||
             	   ($(e.relatedTarget).hasClass('image-product-mini') && $(e.target).hasClass('quick-shop-image'))) {
					//do nothing, this happens on transition from product image to quickshop image and vice versa
            	}
            	else
            	{
              		//product image left on quickshop image
	               	//$('.quick-shop', this.parentNode).hide(50);              		
            	}

            }
        });
        $('.quick-shop-image').click(      		
            function(e){
            	
                $this = $(this.parentNode.parentNode);
                var itemPicMidHeight = parseInt(this.parentNode.parentNode.getElementsByTagName('a')[0].offsetHeight/2);
                var itemPicWidth = parseInt(this.parentNode.parentNode.getElementsByTagName('a')[0].offsetWidth);
                
                if(lastClickedItemPic != this){
                    var p = $this.position();
                    // do ajax calls synchronously
                    $.ajaxSetup({async:false});
                    // load quick shop into layer
                    
                    $(quickShopLayer).load(window.ProductURL+"?pid="+ $this.attr('rel') + '&sz=' + this.attributes['gsize'].value);
                    // disabled synchronization
                    $.ajaxSetup({async:true});
                    if(p.left > 379){
                        $(quickShopLayer).css({
                            top: p.top + itemPicMidHeight - 98,
                            left: p.left - 390 //403 is the width of the dialog
                        }).parent().addClass('righty');
                    } else {
                        $(quickShopLayer).css({
                            top: p.top + itemPicMidHeight - 98,
                            left: p.left + itemPicWidth - 20
                        }).parent().removeClass('righty');
                    }
                    // wires up the color and size selections, and tabifies the content.
		            // this function is defined in product.js file
		            if(window.setupProductDesign !== undefined) {
		            	window.setupProductDesign();
		            }
		            // $('head').append($('<script type="text/javascript" src="js/products.js"></script>'));
                }

                $(quickShopLayer).css({
                	'display':'block'
                });
                lastClickedItemPic = this;
                if(isBeforeQuickShopDialogShown){
                    rf.styleSelects('.quick-shop-dialog select');
                }
                isBeforeQuickShopDialogShown = false;
                
                //ie6 hack/fix - ui-dialog-titlebar-close not showing up.
                // it _already_ "hasLayout" .. just re-triggering it.
                setTimeout(function(){$('.quick-shop-dialog a.ui-dialog-titlebar-close').css('zoom',1);},100);
                return false;
            }
        );
        
        $('body').click(function(e){
            var targ = e.target, i=0;
            while(targ && ++i<10){
                var className = targ.className || '';
                if(className.indexOf('item-pic')>-1 || className.indexOf('quick-shop-dialog')>-1){
                    return;
                }
                targ = targ.parentNode;
            }
            $(quickShopLayer).css('display','none');
        });
        
    } /// </(if .item-pic size() > 0)>
    else if($('body').attr('className').indexOf('cart') > -1 || $('body').attr('className').indexOf('wish-list') > -1) {
    	// add quickbrowse markup.
        // gotchya = the markup will probably have to be different for each product, depending on available sizes & colors & whatnot.
        var quickShopLayer = document.createElement('div');
        quickShopLayer.className = 'quick-shop-dialog';
        // these styles need to be applied immediately, can't even wait for css to be parsed and applied from an external stylesheet :(
        quickShopLayer.style.position = 'absolute';
        quickShopLayer.style.left = '-9999px';
        var shownOnWishlist;
        if($('.cartfooter').length > 0) {
        	$('.cartfooter').append(quickShopLayer);
        	shownOnWishlist = false;
        } else if($('#wishlist-footer').length > 0) {
        	$('#wishlist-footer').append(quickShopLayer);
        	shownOnWishlist = true;
        }
        
		$(quickShopLayer).css('display','none');
        
        $('a.add-to-wishlist').click(function(){
            //do add to wishlist.. (setTimeout only need to prevent alert from interfering with return, setTimeout not noramlly required here.)
            setTimeout(function(){alert('do add-to-wishlist');}, 100);
            return false;
        });
        
        //provide a getter for the private variable.
        //products.js needs it in order to know what product image to update when selecting colors.
        me.getLastClickedGridItem = function(){
            return lastClickedItem;
        };
        
        var isBeforeQuickShopDialogShown = true;
        var lastClickedItem;
        $('.cartitemedit').click(    	
            function(e){
                 $this = $(this);
                //if(lastClickedItem != this){
                    var p = $this.position();
                    
                    // do ajax calls synchronously
                    $.ajaxSetup({async:false});
                    // load quick shop into layer
                    // window.ProductURL is defined in htmlscript.isml
                    var newURL=location.protocol+"//"+window.location.host+window.ProductURL;
                    $(quickShopLayer).load(newURL+"?pid="+$this.attr('rel')+(shownOnWishlist ? "&shownOnWishlist=true":"") + "&removePid="+$this.attr('rel') + "&sz=32");
   
                    // disabled synchronization
                    $.ajaxSetup({async:true});
                   	 
                    if(shownOnWishlist) {
                    	 $(quickShopLayer).css({
	                            top: p.top+271,
	                            left: p.left+270
	                        }).parent().removeClass('righty');
                    } else {
	                    if(p.right > 379){
	                        $(quickShopLayer).css({
	                            top: p.top - 97,
	                            left: p.left - 386 //403 is the width of the dialog
	                        }).parent().addClass('righty');
	                    } else {
	                        $(quickShopLayer).css({
	                            top: p.top - 97,
	                            left: p.left + parseInt(this.offsetWidth) - 10
	                        }).parent().removeClass('righty');
	                    }
                    }

                    $(quickShopLayer).css(
                    	'display','block'
                	);
                    
                    // wires up the color and size selections, and tabifies the content.
		            // this function is defined in product.js file
		            //if(window.setupProductDesign !== undefined) {
		            //	window.setupProductDesign();
		            //}
		            //$('head').append($('<script type="text/javascript" src="js/products.js"></script>'));
                //}
                
                lastClickedItem = this;
                if(isBeforeQuickShopDialogShown){
                    rf.styleSelects('.quick-shop-dialog select');
                }
                isBeforeQuickShopDialogShown = false;
                
                //ie6 hack/fix - ui-dialog-titlebar-close not showing up.
                // it _already_ "hasLayout" .. just re-triggering it.
                //setTimeout(function(){$('.quick-shop-dialog a.ui-dialog-titlebar-close').css('zoom',1);},100);
                
                return false;
            }
        );
        /*
        $('body').click(function(e){
            var targ = e.target, i=0;
            while(targ && ++i<10){
                var className = targ.className || '';
                if(className.indexOf('cartitemedit')>-1 || className.indexOf('quick-shop-dialog')>-1){
                    return;
                }
                targ = targ.parentNode;
            }
            $(quickShopLayer).css('display','none');
            lastClickedItem = undefined;
        });*/
        
    }
}

jQuery(wireUpMosaic);   


/*END of home page function*/    
})(jQuery);

function initMiniCartMouseOvers(visible) {
	var getById = function(n){ return document.getElementById(n); };
	if(visible) {
		$('#minicart dl.info-bubble-small').each(function(){
	        if( getById('wrapper').offsetWidth - (this.offsetLeft - getById('wrapper').offsetLeft) < 188 ){
	            //too far to the right for a right-falling bubble. needs to fall left.
	            $('dd',this).addClass('righty'); //I chose to call the class righty because the background image's pointer is on the right side.
	        }
	        $('dd',this).append('<span/>');
	    }).bind('mouseover mouseout',function(){
	        $('dd',this).toggle();
	    });
	}
	
	/* prepare minicart */
    var minicartClosedTime = 0;
    // when the mouse goes out of the minicart
    $('#minicart-wrapper').bind('mouseover',function(){
        // to prevent super-flicker-mania, don't toggle the cart via mouseover/out for half a second after closing it via the close button.
        if( (new Date()).getTime() - minicartClosedTime > 500 && productInCartTotal > 0){
            $('#minicart-layer').show();
        }
    });
    // when the mouse goes over the minicart
    $('#minicart-wrapper').bind('mouseout',function(){
        // to prevent super-flicker-mania, don't toggle the cart via mouseover/out for half a second after closing it via the close button.
        if( (new Date()).getTime() - minicartClosedTime > 500 ){
            $('#minicart-layer').hide();
        }
    });
    $('#showminicartlink').bind('click',function(){
        // to prevent super-flicker-mania, don't toggle the cart via mouseover/out for half a second after closing it via the close button.
        if( (new Date()).getTime() - minicartClosedTime > 500 && productInCartTotal > 0){
            $('#minicart-layer').show();
        }
    });
    
    
    /* Custom Scrollbars ala jScrollPane - found on minicart, various. */
    $('#minicart-summary').mouseover(); //element must be visible for jScrollPane to initialize properly.
    $('#minicart-content ul').jScrollPane({showArrows:true, scrollbarWidth: 21, arrowSize: 19});
    $('#minicart-layer a.mini-close').click(function(){
        minicartClosedTime = (new Date()).getTime();
        $('#minicart-layer').toggle();
    });
    if(!visible) {
    	$('#minicart-summary').mouseout(); //done initialize-ing, hide it again now.
    }
}
