/* Customized Add2Cart Notification Shadowbox */
(function($) {

	$.extend({
		add2cart: function(source_id, target_id, callback) {
    
		      var source = $('#' + source_id );
		      var target = $('#' + target_id + ' a');
		      
		      var shadow = $('#' + source_id + '_shadow');
		      if( !shadow.attr('id') ) {
			  $('body').prepend('<div id="'+source.attr('id')+'_shadow" style="display: none; background-color: #ddd; border: solid 1px darkgray; position: static; top: 0px; z-index: 100000;">&nbsp;</div>');
			  var shadow = $('#'+source.attr('id')+'_shadow');
		      }
		      
		      if( !shadow ) {
			  alert('Cannot create the shadow div');
		      }
		      
		      shadow.width(source.attr('width'))
                    .height(source.attr('height'))
                    .css('top', source.offset().top)
                    .css('left', source.offset().left)
                    .css('opacity', 0.5)
                    .show();
		      shadow.css('position', 'absolute');
		      
		      shadow.animate( { width: target.innerWidth(), height: target.innerHeight(), top: target.offset().top, left: target.offset().left }, { duration: 400 } )
		      .animate( { opacity: 0 }, { duration: 100, complete: function() {
			      shadow.remove();
			      }
		      } );
        
		}
	});
})(jQuery);

/* Start On DOM Ready Code */
$(document).ready(function(){

/* Standard Sitewide NDI JavaScript */
$('#searchWTerm').focus(function() {
	if(this.value=='search keyword or item #') {
		this.value = '';
	}
});
$('#searchTerm').focus(function() {
	if(this.value=='search keyword or item #') {
		this.value = '';
	}
});
$('#searchWTerm').blur(function() {
	if(this.value=='') {
		this.value = 'search keyword or item #';
	}
});
$('#searchTerm').blur(function() {
	if(this.value=='') {
		this.value = 'search keyword or item #';
	}
});

/* Standard Sitewide Accordion Menu */
	$("div.nav ul.expand-single li ul").hide(); // Hide all sub menus
	$("div.nav ul.expand-single li a.current").parent().find("ul").slideToggle("slow"); // Slide down the current menu item's sub menu
	$("div.nav ul.expand-single li a.current").addClass("open"); // Add the "open" class to the current menu item
	$("div.nav ul.expand-single li a.expander").click( // When a top menu item is clicked...
		function () {
			$(this).parent().siblings().find("ul").slideUp("normal"); // Slide up all sub menus except the one clicked
			$(this).parent().siblings().find("a").removeClass("open"); // Remove "open" class if anchors have them.
			$(this).next().slideToggle("normal"); // Slide down the clicked sub menu
			if($(this).hasClass("open")) {
				$(this).removeClass("open"); // Remove the "open" class from the anchor when clicked to close it
			} else {
				$(this).addClass("open"); // Add the "open" class to the anchor
			}
			return false;
		}
	);
	$("div.nav ul.expand-single li a.no-submenu").click( // When a menu item with no sub menu is clicked...
		function () {
			window.location.href=(this.href); // Just open the link instead of a sub menu
			return false;
		}
	);
	$("div.nav ul.expand-all li ul").hide(); // Hide all sub menus
	$("div.nav ul.expand-all li a.current").parent().find("ul").slideToggle("slow"); // Slide down the current menu item's sub menu
	$("div.nav ul.expand-all li a.current").addClass("open"); // Add the "open" class to the current menu item
	$("div.nav ul.expand-all li a.expander").click( // When a top menu item is clicked...
		function () {
			$(this).next().slideToggle("normal"); // Slide down the clicked sub menu
			if($(this).hasClass("open")) {
				$(this).removeClass("open"); // Remove the "open" class from the anchor when clicked to close it
			} else {
				$(this).addClass("open"); // Add the "open" class to the anchor
			}
			return false;
		}
	);
	$("div.nav ul.expand-all li a.no-submenu").click( // When a menu item with no sub menu is clicked...
		function () {
			window.location.href=(this.href); // Just open the link instead of a sub menu
			return false;
		}
	);
	$("div.nav ul#filters li ul li.seeAllItems a.seeAll").click( // When the "See All" button is clicked
		function () {
			$(this).parent(".seeAllWrapper").siblings(".seeAllList").children("ul").slideToggle('show'); // Make "See All" options visible
			$(this).parent(".seeAllWrapper").slideToggle('hide'); // Hide the "See All Items" text
			return false;
		}
	);
	
/* Standard Sitewide Floating Shopping Cart */
	$("div#floating-cart a.toggle").live("click", // When Minimizer Toggle button is clicked...
		function () {
			if($("div#floating-cart div.inner").hasClass("minimized")) {
				$("div#floating-cart div.inner").removeClass("minimized");
				$("div#floating-cart div.inner").addClass("maximized");
				$(this).addClass("minimizer");
				$(this).removeClass("maximizer");
			} else {
				if($("div#floating-cart div.inner").hasClass("maximized")) {
					$("div#floating-cart div.inner").removeClass("maximized");
					$("div#floating-cart div.inner").addClass("minimized");
					$(this).addClass("maximizer");
					$(this).removeClass("minimizer");
				}
			}
			return false;
		}
	);

    var productHovering = false;
    var hoveringWatchers = [];
	$("div#floating-cart div.cart-item-image a").bind("mouseenter", // When hovered over a product
		function () {
			if($(this).parent().siblings().hasClass('hidden')) { // If hidden, show it.
				$(this).parent().siblings().removeClass('hidden');
				$(this).parent().siblings().addClass('shown');
                productHovering = true;
                //console.log(" Keep it open ");
			}
		}
	);
	$("div#floating-cart div.cart-item-image a").bind("mouseleave", // When stopped hovering over a product
		function () {
			if($(this).parent().siblings().hasClass('shown')) { // If not hidden, hide it.
				$(this).parent().siblings().removeClass('shown');
				$(this).parent().siblings().addClass('hidden');
			}
			if($(this).children('span.quantity').hasClass('changer')) {

                if (!productHovering) {
                    //console.log(" Wait, don't close it ");
                    return;
                }
                //console.log(" Prep to close ");

                var self = this;
				var hideIt = (function() {
                    for (var i=0; i<hoveringWatchers.length; i++) {
                        clearTimeout( hoveringWatchers[i] );
                    }
                    hoveringWatchers = [];
                    if (productHovering) {
                        //console.log(" It's hovering. Let's wait ");
                        return;
                    }
                    //console.log(" Closing input ");
                    $(self).children('span.quantity').html($(self).children('span.quantity').children('span').children('input.oldQuantity').val());
                    $(self).children('span.quantity').removeClass('changer');
                });
                productHovering = false;

                hoveringWatchers.push( setTimeout(hideIt, 3000) );
			}
		}
	);
	$("div#floating-cart div.cart-item-image a span.quantity").live("click", // When a quantity is clicked
		function () {
			if($(this).parent().parent().siblings().hasClass('shown')) { // If not hidden, hide it.
				$(this).parent().parent().siblings().removeClass('shown');
				$(this).parent().parent().siblings().addClass('hidden');
			}
			if(!$(this).hasClass('changer')) {
				$(this).html('<span><input id="newQuantity" type="text" value="' + $(this).text() + '" class="newQuantity basicText" ="100" /><input type="hidden" value="' + $(this).text() + '" class="oldQuantity" /><button class="newQuantityChange stdButton">Update</button> or <button class="stdButton floatDelete">Delete</button></span>'); // Replace its content with the quantity changer
				$(this).addClass('changer'); // Activate it as a "changer"
				$(".newQuantityChange").live("click", // When a new quantity change button is clicked
					function () {
                        var newQuantity = $(this).siblings("input.newQuantity").val();
                        var P = new PHP_JS();
                        if(P.is_numeric(newQuantity) && newQuantity > 0) {
                			$("div#floating-cart").load("/inc/php/shop.cart.actions.php?updateCart=" + $(this).parent().parent().parent().parent().parent().attr("id").substr(10) + "&quantity=" + newQuantity + '&userHash=' + $('li#navAccount a').attr("id"),'',function() {
                				$("li#navCart").load("/inc/php/shop.cart.actions.php?updateHdrCart=now");
                			});
                        } else if(newQuantity == 0) {
                            $(this).parent().find('.floatDelete').click();
                        }
						return false;
					}
				);
				$(".floatDelete").live("click", // When a new quantity change button is clicked
					function () {
						$("div#floating-cart").load("/inc/php/shop.cart.actions.php?deleteFromFloatCart=" + $(this).parent().parent().parent().parent().parent().attr("id").substr(10) + '&userHash=' + $('li#navAccount a').attr("id"),'',function() {
							$("li#navCart").load("/inc/php/shop.cart.actions.php?updateHdrCart=now");
						});
						return false;
					}
				);

                $('#newQuantity').keypress(function(event) {
                        if (event.keyCode!='13') {
                            return;
                        }
                        $('.newQuantityChange').trigger('click');
                        return false;

                });
                $('#newQuantity').focus();
                $('#newQuantity').select();
			}
			return false; // Make sure you don't go to the product page
		}
	);
	$("div#products input.addToCart").live("click",
		function () {
			var productID = $(this).attr("id").substr(10);
			var quantityBeingAdded = $("input#quantity-" + $(this).attr("id").substr(10)).val();
            var P = new PHP_JS();
            if(P.is_numeric(quantityBeingAdded) && quantityBeingAdded > 0) {
                $("div#floating-cart").load("/inc/php/shop.cart.actions.php?addToCart=" + $(this).attr("id").substr(10) + "&quantity=" + $("input#quantity-" + $(this).attr("id").substr(10)).val() + '&userHash=' + $('li#navAccount a').attr("id") + '&type=parent','',function() {
                        $("li#navCart").load("/inc/php/shop.cart.actions.php?updateHdrCart=now",'',function() {
                            $.add2cart( 'productPhoto', 'navCart' );
                            if($('div#products input.addToCart').hasClass('hasOptions')) {
                                $.prettyPhoto.open('/inc/php/shop.cart.actions.php?showOptions=' + productID + '&quantityToAdd=' + quantityBeingAdded + '&iframe=true&width=60%&height=60%','Optional Items','');
                            }
                        });
                });
            }
				
			return false;
		}
	);
	
	$(function () {
		addItemOption = function(productToAdd,quantityToAdd,itemParent) {
			$("div#floating-cart").load("/inc/php/shop.cart.actions.php?addToCart=" + productToAdd + "&quantity=" + quantityToAdd + '&itemParent=' + itemParent + '&userHash=' + $('li#navAccount a').attr("id"),'',function() {
					$("li#navCart").load("/inc/php/shop.cart.actions.php?updateHdrCart=now");
			});
		};
	});

/* Various Animations / Effects Initialization */
	// Initializes jquery.prettyPhoto.js
	$("a[rel^='prettyPhoto']").prettyPhoto({
	    callback: function(){
	        $('html').css('overflow','auto');
	    },
	    openCallback: function(){
	        $('html').css('overflow','hidden');
	    }
	});

/* Notifications */
	//Close button:
		
		$(".close").click(
			function () {
				$(this).parent().fadeTo(400, 0, function () { // Links with the class "close" will close parent
					$(this).slideUp(400);
				});
				return false;
			}
		);
		
    // Autoclose notifications
    		$(document).ready(
			function(){
				setTimeout(
					function(){
						$("div.autofade").fadeTo(500, 0, function () {
								$("div.autofade").slideUp(300);
						});
					}, 2000);
			});
	// Toggle href
		
		$(".open-href").click( // Links with the class "open-href" will open the element with id equal to the link's href
			function () {
				var toToggle = $(this).attr('href');
				$(toToggle).slideDown(400, function () { 
					$(this).fadeTo(400, 1);
				});
				return false;
			}
		);

		
/* Open Social Media Footer Links in new window */
	$(function(){
		$('#navSocial a').click(function(){
			window.open(this.href);
			return false;
		});
	});

    $('.resetForm').click(function() {
        window.location.reload();
        return false;
    });
});
