jQuery(document).ready(function(){

    var $ = jQuery,
        getById = function(n){ return document.getElementById(n); };
 
          
        ie = $.browser.msie,
        ff = $.browser.mozilla,
        wk = $.browser.webkit,
        sa = $.browser.safari
        $('html').addClass( 'jsEnabled' + (($.browser.msie ? ' ie ie': $.browser.safari ? ' sa sa' : $.browser.mozilla ? ' ff ff' : $.browser.webkit ? ' wk wk' : ' other') + parseInt($.browser.version)) );
        
        
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 
        

    initMiniCartMouseOvers = function(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('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();
            }
        });
        $('#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.
        });
    }

    
    initMiniCartMouseOvers(false); 
    
    /* Custom Scrollbars ala jScrollPane - found on minicart, various. */
    $('#minicart-layer').mouseover(); //element must be visible for jScrollPane to initialize properly.
    $('#minicart-content .items').jScrollPane({showArrows:true, scrollbarWidth: 21, arrowSize: 19});
    $('#minicart-layer a.mini-close').click(function(){
        minicartClosedTime = (new Date()).getTime();
        $('#minicart-layer').toggle();
    });

    ///  added this section as experimental
    $('#minicart-summary').bind('mouseover',function(){
    	if (productInCartTotal > 0) {
    		minicartClosedTime = (new Date()).getTime();
        	$('#minicart-layer').toggle();
    	}
    });

    $('#minicart-layer').mouseout(); //done initialize-ing, hide it again now.
    $('#minicart-layer').hide();

   /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

buildPopupDivId = function( title )    
{
	return 'modal-' + onlyAlphaNumeric( title ).toLowerCase();
}

onlyAlphaNumeric = function( 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('');
}  


/* load content assets in modal window */
$('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;
});

/* MODALS */
$.ui.dialog.bgiframe = true;
$.ui.dialog.modal = true;
$.ui.dialog.width = 367;
$.ui.dialog.draggable = false;
$.ui.dialog.resizable = false;

var modals = {};
modal = function( o )
{
    var dialog = modals[o.title];
    
    dialog = document.createElement('div');
    dialog.title = o.title;
    dialog.innerHTML = o.body;
    getById('main_content').appendChild(dialog);
   
    dialog.id = buildPopupDivId( o.title );
    modals[o.title] = $(dialog).dialog({zIndex: 10000, modal:true,width:(o.width || $.ui.dialog.defaults.width)});
    return modals;
}

/******************
 * QUICK SHOP
 * ****************/
initializeQuickShop = function(QS_type){
	
    // wire up quick shop
    var itemPics = $('.item-pic');
    var cartItems = $('.cartitemedit'); 
    
    
    if(QS_type == 'grid'){
        // add quickbrowse markup.
        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';
        $('.main_grid').append(quickShopLayer);
        
        $(quickShopLayer).css('display','none');
        
        //provide a getter for the private variable.
        //products.js needs it in order to know what product image to update when selecting colors.
       this.getLastClickedGridItem = function(){
            return lastClickedItemPic;
        };
        
        var isBeforeQuickShopDialogShown = true;
        var lastClickedItemPic;
        // show the quick shop button if the mouse is over an image
        if(navigator.platform.indexOf("iPad") == -1)
        {
	        $('.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(50);
	            }
	        });
	      
	        //hide the quickshop button on mouseout
	        $('.item-pic').mouseout(function (e) {
	        	if($.contains(this, e.relatedTarget) == false) {
	        		$('.quick-shop').hide(50);
	        	}
	        	}); 
        }
        
        $('.quick-shop-image').click(      		
        		function(e){
        		
                $this = $(this.parentNode.parentNode);
                $pos = $(this.parentNode.parentNode.parentNode);
                var itemPicMidHeight = parseInt(this.parentNode.parentNode.getElementsByTagName('a')[0].offsetHeight/2);
                var itemPicWidth = parseInt(this.parentNode.parentNode.getElementsByTagName('a')[0].offsetWidth);
                
                var isBeforeQuickShopDialogShown = true;
                if(lastClickedItemPic != this)
                {
	                   //var p = $pos.position();
                		var p = $pos.offset();
	                   
	                   
	                   // 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 > 500){
	                       $(quickShopLayer).css({
	                    	   top: p.top + itemPicMidHeight - 98,
	                           left: p.left - 390 //430 is the width of the dialog
	                       })
	                   } else {
	                	   $(quickShopLayer).css({
	                           top: p.top + itemPicMidHeight - 98,
	                           left: p.left + itemPicWidth - 20
	                       })
	                   }
	                   

                }
                
                $(quickShopLayer).css({
                	'display':'block'
                });
                
                lastClickedItemPic = this;
                isBeforeQuickShopDialogShown = false;

            	s.prop1="Quick Shop View";
            	s.prop7=s.eVar7="MHW";
            	s.prop8=s.eVar8="US";
            	s.prop9=s.eVar26=$this.attr('rel');
            	s.state=omnStateCode;
            	s.zip=omnPostalCode;
            	s.events="event25";
            	s.products=";"+$this.attr('rel');
            	var s_code=s.t();if(s_code)document.write(s_code);
                
                
                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( QS_type == 'cart' || QS_type == 'wish-list' ) {
    	// add quickbrowse markup.
        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;
        	showEditButton = true;
        } 
        else if($('#wishlist-footer').length > 0) 
        {
        	$('#wishlist-footer').append(quickShopLayer);
        	shownOnWishlist = true;
        	showEditButton = true;
        }
        
		$(quickShopLayer).css('display','none');
        
        //provide a getter for the private variable.
        //products.js needs it in order to know what product image to update when selecting colors.
		this.getLastClickedGridItem = function(){
	           return lastClickedItemPic;
	    };
    
        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') + (showEditButton ? "&showEditButton=true":"") + (shownOnWishlist ? "&shownOnWishlist=true":"") + "&removePid="+$this.attr('rel') + "&sz=32");
   
                    // disabled synchronization
                    $.ajaxSetup({async:true});
                   	 
                    if(shownOnWishlist) {
                    	
                    	 $(quickShopLayer).css({
	                            top: p.top-300,
	                            left: p.left-450  
	                        })
                    } else {
	                    if(p.right > 379){
	                    	
	                    	
	                        $(quickShopLayer).css({
	                            top: p.top - 97,
	                            left: p.left - 386 //403 is the width of the dialog
	                        })
	                    } else {
	                    	
	                    	
	                        $(quickShopLayer).css({
	                            top: p.top - 97,
	                            left: p.left + parseInt(this.offsetWidth) - 10
	                        })
	                    }
                    }

                    $(quickShopLayer).css(
                    	'display','block'
                	);
                    
                    
                lastClickedItem = this;
                isBeforeQuickShopDialogShown = false;
                
                return false;
            }
        );
        
        
    }
}



var removeHolder = $('#remove-account-holder');
$('.account_stuff a.remove-account').click(function(){
    
	 modal({
           title: 'Remove Elevated Rewards'
            ,body: removeHolder.html()
           ,width: 450
       });
       return false;
    
});



/* Forgot Password Modal */
/* modal for Forgot Password on My Account Login */
var forgotHolder = $('#forgot-holder');
$('.forgot-password').click(function(){
	
	
    modal({
        title: 'Forgot Your Password?'
        ,body: forgotHolder.html()
    });
    return false;
});

/* Password Confirmation/error */
this.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 address. Please try again or ";
						message += "register now.";
					$('.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;
};


/* Left Side Bar  */
adjustLeftNav = function(n)
{
	
	
	$(".grey_bar_block").show();
	block=$(".grey_bar_block")
	if (block.position()) {
			
		bartop=block.position().top;
		
		var footer = $('#footer');
		barheight=parseInt( (footer.position().top - bartop) - 43);
			
		
		//Category landing pages
		if ($(".category_section").length ) 
		{
			barheight=parseInt( (footer.position().top - bartop) - 51);
		}
		//--
		
		//PDP Page
		if ($(".tabbertab").length ) 
		{
			if( n == 'true')
			{
			barheight=0;
			}else
			{
				barheight=parseInt( (footer.position().top - bartop) - 43);
			}
			
		}
		//--
		
		//IE 7 funkiness
		if ($.browser.msie && $.browser.version.substr(0,1)<8) 
		{
			var scrollTop = $(window).scrollTop();
			if(scrollTop > 0)
			{
				barheight = barheight - scrollTop;
			}
		}
		
		if (typeof barheight!="undefined" ) 
		{
			
			$(".grey_bar_block").css('height',parseInt(barheight));
			if (barheight>390) 
			{
				$(".grey_bar_block img").show();
			}
			else 
			{
				if (barheight<10) {
					$(".grey_bar_block").hide();
				}

			}

		}
	}

}

    
   
});

//load this one after the page and images have completely loaded.
$(window).load(function () {
	//setTimeout(function() { adjustLeftNav('true'); }, 1500);
	adjustLeftNav('true');
	});


