// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed
(function(){
  var cache = {};
 
  this.tmpl = function tmpl(str, data){
    // Figure out if we're getting a template, or if we need to
    // load the template - and be sure to cache the result.
    var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
        tmpl(document.getElementById(str).innerHTML) :
     
      // Generate a reusable function that will serve as a template
      // generator (and which will be cached).
      new Function("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +
       
        // Introduce the data as local variables using with(){}
        "with(obj){p.push('" +
       
        // Convert the template into pure JavaScript
        str
          .replace(/[\r\t\n]/g, " ")
          .split("<#").join("\t")
          .replace(/((^|%>)[^\t]*)'/g, "$1\r")
          .replace(/\t=(.*?)#>/g, "',$1,'")
          .split("\t").join("');")
          .split("#>").join("p.push('")
          .split("\r").join("\\'")
      + "');}return p.join('');");
   
    // Provide some basic currying to the user
    return data ? fn( data ) : fn;
  };
})();


(function($) {
	var site = window.site = {
		data : {
			// js data
		},
		func : {
			// commonly used site specfic functions
		},
		obj : {
			// site specfic objects
			ShareThis: {
                open: function(){
                    var $elem = $("#main-bd-inner > div.grid > div.gu-last"),
                        pos = $elem.offset();
                    $("#ShareThis-iframe, #ShareThis")
                        .appendTo($("body"))
                        .css({
                            "left": pos.left + 10,
                            "top": pos.top
                        })
                        .stop().fadeIn(200);
                },
                close: function(){
                    var $ShareThis = $("#ShareThis, #ShareThis-iframe");
                    $ShareThis.stop().fadeOut(200, function(){ 
                        $ShareThis.find("input, textarea").val("");
                        $('#EmailFriendForm .error').hide().html('');
                        $('#EmailFriendConfirmation').hide();
                        $('#EmailFriendForm').show();
                    });
                },
                submit: function(){
                    
                }
            }
		}
	};
})($);

// on body load
$(function() {
    // init
    
    /* External links open in new windows */
    $("a[rel='external']").bind("click.external", function(){
        window.open(this.href);
        return false;
    });
    
    /* Handle hover states for buttons and images */
   $("input.js-hasHover, img.js-hasHover").each(function(){
       var $this = $(this);
       $this.bind("mouseenter mouseleave", function(e){
           $this.toggleClass("hover")
                .attr("src", $this.attr("src").replace(/_(off|on)\./, (e.type == "mouseenter" ? "_on." : "_off.")));
       });
   });
    
    /* Share this buttons */
   $("input.js-share-product").click(function(){
       site.obj.ShareThis.open();
       return false;
   });
   $("#ShareThis a.js-close").click(function(){
       site.obj.ShareThis.close();
       return false;
   });
    
	/* generic show/hide toggler */
	$("a.js-toggler").live("click", function(){
	    var $this = $(this),
              $subject = $($this.attr("href").match(/(#\w+)$/)[0]); // expects the href to be an id
        $this.toggleClass("selected");
        $subject.toggleClass("toggle-on");
        return false;
    } );
          
     /* Show cart on hover */
    $(".js-cartToggle").mouseover(function() { 
    	if( $("#universalCart").size() == 0 )
    	{ showBasket('show',''); }
    });
    
    /* Product grid overlay */
    $("div.products > div.grid").find("div.product").each(function(){
        var $this = $(this),
            $overlay = $this.find("div.overlay").css({ "opacity": 0, "display": "block" }),
            $meta = $this.find("div.meta");
        
        if($this.parent().parent().is(".showDetails")) { $overlay.css({"opacity": 1}); return; }
        
        if($.browser.msie && $.browser.version >= 8){
            $overlay.stop().fadeOut(0);
            $this.hover(
                function(){ $overlay.stop().fadeIn(0), function(){ this.style.removeAttribute("filter"); } },
                function(){ $overlay.stop().fadeOut(0); }
            );
            return; 
        }
        $("div.outfits").css("position", "relative");
        
        $this.hover(
            function(){ 
                $overlay.stop().animate({"opacity": 1}, function(){ if($.browser.msie){ this.style.removeAttribute("filter"); } }); 
                $meta.stop().animate({"opacity": 0});
            },
            function(){ 
                $overlay.stop().animate({"opacity": 0}); 
                $meta.stop().animate({"opacity": 1}, function(){ if($.browser.msie){ this.style.removeAttribute("filter"); } });
            }
        );
    })
    
    
    /* Primary Navigation hide/show behavior */
    $("#nav-site > ul.list-l1")
        .data("delay", 500)
        .data("opened", null)
        .children("li").each(function(){
            var $this = $(this),
                getSelected = function(){ return $this.parent().children("li.selected").find("div.wrapper-l2"); },
                $l2 = $this.find("div.wrapper-l2"),
                $secondary = $l2.find(".list-l2 > li"),
                $parent = $this.parent(),
                $siblings = $this.siblings(),
                $all = $siblings.andSelf(),
                rate = 400;
           
            if($this.is(":not(.selected)")){
                $l2.css({ "opacity": 0 });    // We're directly animating opacity because there's wonkyness with jQuery's fadeIn/Out   
            }
            
            $this.click(function(e){
                clearTimeout($this.data("timer"));
                show();
                $this.siblings().removeClass("active-off").removeClass("selected").removeClass("hover").end().addClass("selected");
                if ($(e.target).is(":not(.label-l2)")) { return false; }
            });
            
            var show = function(){
                $all.each(function(){
                   clearTimeout($(this).data("timer")); 
                });
                $this.addClass("hover");
                $parent.data("opened", $this);
                if ($this.is(":not(.selected)")) {
                    var $selected = getSelected();
                    // fading-in element should be at max z-index for usability's sake
                    $l2.css({ "z-index": 10, "display": "block" }).stop().animate( { "opacity": 1 }, rate, function(){ if ($.browser.msie) { this.style.removeAttribute("filter"); } });
                    $selected.parent().addClass("active-off");
                    $selected.css("z-index", 1).stop().animate({ "opacity": 0 }, rate, function(){ $selected.css("display", "none") }); 
                }    
            }
            var hide = function(){
                $this.removeClass("hover");
                if ($this.is(":not(.selected)")) {
                    var $selected = getSelected();
                    // hide when done, to avoid triggering mouse events
                    $l2.css("z-index", 1).stop().animate({"opacity": 0}, rate,  function(){ $l2.css("display", "none") } );
                    if($parent.data("opened") == $this){
                        $selected.parent().removeClass("active-off");
                        $selected.css({"z-index": 10, "display": "block" }).stop().animate({"opacity": 1}, rate);
                        $parent.data("opened", null);
                    }
                }
            }
            
            
            $this
                .data("timer", null)
                .hover(
                    function(){ // over
                        clearTimeout($this.data("timer"));
                        $this.data("timer", setTimeout(show, $parent.data("delay")));
                    },
                    function(){ // out
                        clearTimeout($this.data("timer"));
                        $this.data("timer", setTimeout(hide, $parent.data("delay")));
    
                    }
                );
           
            $secondary.each(function(){
                var $this = $(this);
                $this.hover(
                    function(){ $this.addClass("hover"); }, 
                    function(){ $this.removeClass("hover"); }
                );
            });
           
        });
    /* End Primary Nav code */
    
    /* Setup any buttons */
    $(".js-imageButton").each(function() {
		var baseImage = $(this).attr("src").split("_");
		var offPath = baseImage[0] + "_off.gif";
		var onPath = baseImage[0] + "_on.gif";
		new lib.obj.button({
			off: offPath,
			hover: onPath,
			buttonSelector: this,
			buttonCollectionSelector : ".js-imageButton"
		});
	});
    /* --------------- */
  
    /* Setup any Generic Popups */
    $(".js-genericPopup").click(function(evt) {
		var $this = $(this),
            popupWidth = $this.attr("data-width") || 685,
            iframeSRC = $this.attr("href");
            iframeHeight = $this.attr("data-height") || 450;
		lib.layer.create("#genericLayerContent", {
			closeSelector : ".js-closeLayer",
			url : "/custserv/generic_layer.jsp",
			keepCentered : false,
			callback : function() {
                $("#genericLayerContent").bind("mousedown", function(e){ beginPopupDrag(this, e) });
				$("#genericLayerContent iframe").attr("src", iframeSRC);
                $("#genericLayerContent").animate({"width": popupWidth}, 0);
                $("#genericLayerContent iframe").animate({"height": iframeHeight}, 0);
				lib.layer.center("#genericLayerContent");
			}
		});
		evt.preventDefault();
	});
    /* ------------------- */
    
    /* set up default text for search box, newsletter field  */
     lib.input.defaultText("#SiteSearch", {defaultText: "KEYWORD OR ITEM #"}) ;
     lib.input.defaultText("#FooterSignup", {defaultText: "SIGN UP FOR EMAIL UPDATES"}) ;
     
     /* Radio buttons on refinements trigger click behavior */
    $("#Filter .radioGroup").each( function(){ 
        var $this = $(this), 
               $radio = $this.find("input"), 
               href = $this.find("a").attr("href"); 
        $radio.bind("focus", function(){ 
            window.location.href = href;
        });
    });
    
    /* Addresses IE clickthrough issue on product grid */
    if($.browser.msie){
        $(".product .thumb img").click(function(){ window.location = $(this).parent().parent().find("a.clickthrough").attr("href") })
    }
   
});