/* need to wrap Jquery because
 * of default Magento script conflict
 */

 jQuery(document).ready(function($){
if (typeof console == "undefined") {
	console = {log: function() {}};
}

/////////////////////////////////////////////////////////////////
///  Category Left Menu
/////////////////////////////////////////////////////////////////
		
        // Left-nav clicking and sliding
        
        $('.child-accordion').hide();
		
		// auto-open navigation level if on current page
		
		$('.side-nav .current').children('.child-accordion').show().addClass('opened').css('background-color','#eee');
		
		
		
		$('ul.opened').each(function(){
		if($(this).find('.opened').length > 0){
			$(this).css('background-color','#fff');
			}
		});
		
		//toggle arrows
		
		$('.side-nav li').each(function(index){
                if ($(this).children('.child-accordion').size() > 0) {
					if ($(this).children('ul').hasClass('opened')) {
						$(this).prepend('<div class="nav_toggles arrow_down">&nbsp;</div>');
					}
					else {
						$(this).prepend('<div class="nav_toggles arrow_right">&nbsp;</div>').removeClass('opened');
					}
			}
		});
			
		
        $('.nav_toggles').click(function(){
            $(this).siblings('.child-accordion').slideToggle('fast');
            $(this).toggleClass('arrow_right arrow_down');
			// $(this).siblings('.child-accordion').css('background-color','#eee');	
        });

		// remove 'current' class on all but true current page
		
		testForCurrent();
		
	 	 function testForCurrent(){
			$('.side-nav li.current').each(function(){
				if ($(this).find('.current').length > 0) {
					$(this).removeClass('current');
				}		
			});
		};
		
		
		
		
		 
  
        
/////////////////////////////////////////////////////////////////
///  Ajax Add to Cart
/////////////////////////////////////////////////////////////////

		
		// Ajax 'add to cart' function. 
        
        
        $('.ajax-add-to-cart').click(function(event){
			
			event.preventDefault();

            // get the existing values from the form (in catalog/product/view).
            // returns: qty, id, and the hidden 'category path' name
            // then sends it to the custom cart controller
            
            var values = {};
            $.each($('#NB_product_addtocart_form').serializeArray(), function(i, field){
                values[field.name] = field.value;
            });
			
			
			
			// grab the add-to-cart route
            
            var aURL = $('#NB_product_addtocart_form').attr('action');
            //alternately try ../index.php/checkout/cart/add
			
			
			

            
            
			
			$('.ajax-add-to-cart')
			.ajaxStart(function(){
					var loading = $("<img src='/shop/skin/frontend/nbrewer/nbrewer/images/opc-ajax-loader.gif' alt='loading' />");
			 		$('.ajax-loading').remove(); //destroy any loading divs that may exist in the dom because of previous same-page attempts
					$('.ajax-add-to-cart').before('<div class="ajax-loading"></div>');
					$('.ajax-add-to-cart').hide();
			 		$('.ajax-loading').html(loading);
					
				})
			.ajaxStop(function(){
					$('.ajax-loading').remove();
					$('.ajax-add-to-cart').show();
			});
            
            $.ajax({
                url: aURL,
                data: values,
                type: 'POST',
				cache: 'false',
				async: 'false',
                dataType: 'json',
                success: function(json){
                    if (json.errorMessage) { 
					//if the request is successful, but doesn't include all necessary options
                        errorModal(json.errorMessage);
                    }
                    else {
                        updateMyCartLinks(json);
                        addToCartWindow(json);
                        setBackUrl();
						GA_add(json);
                    }
                },
                error: function (){
                    $eMsg = "We're sorry, there has been an error. Please try again."
//                    errorModal($eMsg);
                }
                
            });
			
			function GA_add(json){
				//google analytics
				try {
					_gaq.push(['_trackEvent', 'Add to Cart', 'Click', json.sku]);
					console.log('GA added', json.sku);
				}
				catch(err) {
					console.log('Error on addtocart GA submission');
				}   	
			}
            
            
            // update the My Cart item number in the top links
            
            function updateMyCartLinks(json){
                if (json.totalItems > 1) {
                    $('.top-link-cart').html('My Cart (' + json.totalItems + ' items)');
                }
                else {
                    $('.top-link-cart').html('My Cart (' + json.totalItems + ' item)');
                }
            }
         

	function htmlspecialchars_decode (string, quote_style) {
	    var optTemp = 0,
		i = 0,
		noquotes = false;
	    if (typeof quote_style === 'undefined') {
		quote_style = 2;
	    }
	    string = string.toString().replace(/&lt;/g, '<').replace(/&gt;/g, '>');
	    var OPTS = {
		'ENT_NOQUOTES': 0,
		'ENT_HTML_QUOTE_SINGLE': 1,
		'ENT_HTML_QUOTE_DOUBLE': 2,
		'ENT_COMPAT': 2,
		'ENT_QUOTES': 3,
		'ENT_IGNORE': 4
	    };
	    if (quote_style === 0) {
		noquotes = true;
	    }
	    if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags
		quote_style = [].concat(quote_style);
		for (i = 0; i < quote_style.length; i++) {
		    // Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4
		    if (OPTS[quote_style[i]] === 0) {
			noquotes = true;
		    } else if (OPTS[quote_style[i]]) {
			optTemp = optTemp | OPTS[quote_style[i]];
		    }
		}
		quote_style = optTemp;
	    }
	    if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
		string = string.replace(/&#0*39;/g, "'"); // PHP doesn't currently escape if more than one 0, but it should
		// string = string.replace(/&apos;|&#x0*27;/g, "'"); // This would also be useful here, but not a part of PHP
	    }
	    if (!noquotes) {
		string = string.replace(/&quot;/g, '"');
	    }
	    // Put this in last place to avoid escape being double-decoded
	    string = string.replace(/&amp;/g, '&');

	    return string;
	}

			
            // create modal window to display 'adding product to cart' info		
           
            function addToCartWindow(json){
            
                var $modalWindow = $('<div id="addedtocart"><h2 class="fontface">' + htmlspecialchars_decode(json.messages.success) + '</h2></div>').dialog({
                    autoOpen: false,
                    buttons: {
						
                        "Go to Cart": function(){
                            $(this).dialog("close");
							
							// analytics
						try {
							_gaq.push(['_trackEvent', 'Modal Checkout', 'Click', json.sku]);
							console.log('GA event for going to cart');
							cartLocation = json.checkoutUrl
							goToUrl(cartLocation);				
							}
						catch(err) {
							console.log(err + ' : error on capturing GA event for going to Checkout');
								}
                        },
						
						"Continue Shopping": function(){
                            $(this).dialog("close");
							// analytics
							try {
								_gaq.push(['_trackEvent', 'Modal Continue Shopping', 'Click', json.sku]);
								console.log('GA event for Continue Shopping');
								var continueLocation = values.category_name;
								goToUrl(continueLocation);	
								}
							catch(err){
								console.log(err + ' : error on capturing GA event for going to Continue Shopping');	
								}
                        }
                    },
					closeText: 'X',
					modal	 : true
                })
				$modalWindow.dialog({
					width: 475
				});
                $modalWindow.dialog('open');
				
			 var width =$('#addedtocart').dialog('option','width');
			 $('#addedtocart').dialog('option','width',475);
			 
			 $('.ui-dialog-buttonset :button').addClass('form-submit form-button');
			 
			 //for GA tracking to forward to the correct URL after timeout
			 
			 function goToUrl(finalLocation){
			 	
				function redirUrl(){
					window.location = finalLocation;
				}
				
			 	setTimeout(redirUrl, 500);
			 }
			 
            } //end addToCartWindow
            
	
            function errorModal(html){
                var $modalWindow = $('<div id="addedtocart">' + html + '</div>').dialog({
                    autoOpen: false
                });
                $modalWindow.dialog('open');
            }
            
            
            function setBackUrl(){
                var currUrl = window.location;
                
            }
            
            
        }); // end ajaxAddToCart()
        
		//tracking for wishlist clicks
		$('.link-wishlist').click(function(event){
				event.preventDefault();
				
				try {
					_gaq.push(['_trackEvent', 'Add to Wishlist', 'Click']);
					console.log('GA event for Add to Wishlist');
					var wishLocation = $('.link-wishlist').attr('href');
					function finalLoc(){
						window.location = wishLocation;
					}
					setTimeout(finalLoc, 500);
				}
				catch(err){
					console.log(err + ' : error on capturing GA event for going to adding to Wishlist');	
					}
				
		});


// show the Megamenu on hover 
	
		
		$('.nav-container ul li:first').mouseenter(function(){
			$('#shop_mega').stop(true,true).fadeIn();
			checkPersist();
	
		});
		
		function checkPersist(){
				
			$('#shop_mega').mouseleave(function(){
				$('#shop_mega').stop(true,true).fadeOut();
			
			});
			
			$('.nav-container li:not(:first)').mouseenter(function(){
				if ($('#shop_mega').is(':visible')) {
					$('#shop_mega').fadeOut();
					
				}
			});
			
			$('.wrapper').mouseleave(function(){
				if ($('#shop_mega').is(':visible')) {
					$('#shop_mega').fadeOut();
					
				}
			});
			
			$('.header-container').mouseenter(function(){
				if ($('#shop_mega').is(':visible')) {
					$('#shop_mega').fadeOut();
					
				}
			});
		}        
		
/////////////////////////////////////////////////////////////////
///  Jquery UI
/////////////////////////////////////////////////////////////////
        
		// add tabs to product page
	
		$('.product-collateral').tabs();
		
		
	$(window).load(function(){
	
		// show 'live chat' if available	
		// The chat js returns an image  to display if chat is 
		// available or not. Nothing to hook into. 
		// To fix this one image is 1px
		// wider than the other. If that's the one displaying
		// then chat is available. 
		// image is set to display:none in CSS
	

		var imgWidth = $('.live-chat img').width();
		
		if (imgWidth == 161) {
			$('.live-chat img').parent('a').append('Live Chat ').parent('li').after('|');
		}
		else {
			$('.live-chat').html('');
		}
	});
   
})

