// 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 $body = $("body"),
                        $share = $("#ShareThis"),
                        height = $(document).height(),
                        width = $(document).width();
                    
                    if(!$("#Lightbox").length) { $body.append("<div id='Lightbox'></div>"); }
                    if($.browser.msie && $.browser.version < 7){
                        $("#Lightbox").html("<iframe/>");
                        height = Math.max(document.documentElement.clientHeight, document.body.clientHeight);
                        width =  Math.max(document.documentElement.clientWidth, document.body.clientWidth);
                    }
                    $("#Lightbox, #Lightbox iframe")
                        .stop()
                        .css({
                            height: height,
                            width:  width,
                            "opacity": .3
                        })
                        .fadeIn(200);
                        
                    $share.stop().appendTo($body);
                    lib.layer.center("#ShareThis");
                    $share.fadeIn(200);
                },
                close: function(){
                    var $ShareThis = $("#ShareThis");
                    $ShareThis.stop().fadeOut(200, function(){ 
                        $ShareThis.find("input, textarea").val("");
                        $('#EmailFriendForm .error').hide().html('');
                        $('#EmailFriendForm').show();
                        $('#EmailFriendConfirmation').hide();
                    });
                    $("#Lightbox, #ShareThis-iframe").stop().fadeOut(200);
                }
            }
		}
	};
})($);

// on DOM 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.")));
       });
   });
   $("ol.selectSize img").bind("mouseenter mouseleave", function(e){
       var $this = $(this),
           enabled = $this.parent().parent().is(".disable") ? false : 
                     $this.parent().parent().is(".clearAll") ? false :
                     $this.parent().is(".selected") ? false : true;
       if(e.type == "mouseenter" && enabled){
           $this.attr("src", $this.attr("src").replace(/\.(\w+)$/, "-on.$1"));
       }
       if(e.type == "mouseleave" && enabled){
           $this.attr("src", $this.attr("src").replace(/-on\.(\w+)$/, ".$1"));           
       }
   });
   $("#Filter ol.selectColor img").bind("mouseenter mouseleave", function(e){
       var $this = $(this),
           enabled = $this.parent().parent().is(".disable") ? false : 
                     $this.parent().parent().is(".clearAll") ? false :
                     $this.parent().is(".selected") ? false : true;
       if(e.type == "mouseenter" && enabled){
           $this.attr("src", $this.attr("src").replace(/\.(\w+)$/, "_over.$1"));
       }
       if(e.type == "mouseleave" && enabled){
           $this.attr("src", $this.attr("src").replace(/_over\.(\w+)$/, ".$1"));           
       }
   });
   $("form[name='checkoutForm'] input.js-hasHover").live("mouseover", function(){ 
      var $this = $(this);
      $this.attr("src", $this.attr("src").replace(/_off\.(\w+)$/, "_on.$1"));
   });
   $("form[name='checkoutForm'] input.js-hasHover").live("mouseout", function(){  
      var $this = $(this);
      $this.attr("src", $this.attr("src").replace(/_on\.(\w+)$/, "_off.$1"));
   });
   
    /* Share this buttons */
   $("a.js-share-product").click(function(){
       site.obj.ShareThis.open();
       return false;
   });
   $("#ShareThis a.js-close, #Lightbox").live("click", function(){
       site.obj.ShareThis.close();
       return false;
   });
   lib.input.setMaxCharacters("#ShareThis textarea", { limit: 200 });
    
    /* js-select toggling */
	$("div.js-select, li.js-select").each(function(){
		var $this = $(this),
	    	   $trigger = $this.find("a.select-trigger"),
	           $li = $this.find(".list-options li");
		$().bind("click.select", function(e){
	    	var $target = $(e.target);
	        if($target.is(".select-trigger", $this)){
	        	$this.toggleClass("select-on");
	            return false;
	        }
	        else{ $this.removeClass("select-on"); }
		});
	    $li.each(function(){
	    	var $this = $(this);
	        $this.bind("mouseenter mouseleave", function(e){
	        	$this.toggleClass("hover");
			});
		})
	});
	/* END js-select */
   
	/* 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',''); }
    });
    
    /* 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"); }
                );
                $this.click(function(){
                   window.location = $this.find("a").attr("href");
                });
            });
            
        });
    /* End Primary Nav code */
  
    /* set up default text for search box, newsletter field  */
     lib.input.defaultText("#SiteSearch", {defaultText: "Search Keyword or Item #"}) ;
     lib.input.defaultText("#FooterSignup", {defaultText: "Sign-up for 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") })
    }
    
    /* 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) })
                    //.animate({"width": popupWidth}, 0);
				$("#genericLayerContent iframe")
                    .attr("src", iframeSRC)
                    //.animate({"height": iframeHeight}, 0);
				lib.layer.center("#genericLayerContent");
			}
		});
		evt.preventDefault();
	});
    /* ------------------- */
    
});



/* LEGACY */

/* AT popup code */




/*

BrowserUtil.getEvent BEGINS

*/

var BrowserUtil = {};

BrowserUtil.getEvent = function(evtObj) {

	var navAgent = navigator.userAgent.toLowerCase();
   var evt = null;

   if ((window.event != null) && (navAgent.indexOf("mac") == -1)) {

      // Internet Explorer

      evt = window.event;

      // * IE 6 standards-compliant mode document.documentElement reassignment
      if (document.documentElement && document.documentElement.clientWidth) {

         evt.getViewportAxisX = document.documentElement.clientWidth;
         evt.getViewportAxisY = document.documentElement.clientHeight;

      } else if (document.body) {

         evt.getViewportAxisX = document.body.clientWidth;
         evt.getViewportAxisY = document.body.clientHeight;

      }

      evt.getViewportOffsetX = document.documentElement.scrollLeft;
      evt.getViewportOffsetY = document.documentElement.scrollTop;

      evt.getPageCoordX = evt.clientX + document.documentElement.scrollLeft;
      evt.getPageCoordY = evt.clientY + document.documentElement.scrollTop;

      evt.getRelatedTarget = evt.toElement ? evt.toElement : evt.fromElement;
		evt.getTarget = evt.srcElement;

   } else if (evtObj != null) {

      // EOMB

      evt = evtObj;

      evt.getViewportAxisX = self.innerWidth;
      evt.getViewportAxisY = self.innerHeight;
      evt.getViewportOffsetX = self.pageXOffset;
      evt.getViewportOffsetY = self.pageYOffset;

      evt.getPageCoordX = evt.pageX;
      evt.getPageCoordY = evt.pageY;

      evt.getRelatedTarget = evt.relatedTarget;
		evt.getTarget = evt.target;

   }

   return evt;

}




var useNonMacMSPops = ((navigator.userAgent.indexOf("PowerPC") < 0) || (navigator.userAgent.indexOf("MSIE") < 0));

//**********************************************************************************
// The following five functions are copied from the js library /js/popupControl.js *
//**********************************************************************************

function openPopup(popupName, wid, ht, tp, lft, bgColor, titleSrc, evtObj) {
	document.location.href="#ATLtop";
	if (useNonMacMSPops) {
		var popLayer = document.getElementById(popupName + "Top");
		var popInner = document.getElementById(popupName + "Inner");
		var popHeader = document.getElementById(popupName + "Header");
		var popTitle = document.getElementById(popupName + "TitleImage");
		var popContents = document.getElementById(popupName);
		popLayer.style.width = wid + "px";
		popLayer.style.height = ht + "px";
		popInner.style.width = wid + "px";
		popInner.style.height = (ht - 22) + "px";
		popLayer.style.borderBottomColor = bgColor;
		popLayer.style.borderBottomWidth = 10 + "px";
	    popLayer.style.borderBottomStyle = "solid"
		popHeader.style.width = wid + "px";
		popHeader.style.backgroundColor = bgColor;
		popTitle.src = titleSrc;
		popContents.style.width = (wid - 1) + "px";
		popContents.style.height = (ht - 56) + "px";
		popLayer.style.visibility = "visible";
		popLayer.style.display = "inline";

        var posX = 0;
        var posY = 0;

        var newEventObject = new BrowserUtil.getEvent(evtObj);
        posX = Math.round(newEventObject.getViewportAxisX/2) + newEventObject.getViewportOffsetX - Math.round(wid/2);
   	    posY = Math.round(newEventObject.getViewportAxisY/2) + newEventObject.getViewportOffsetY - Math.round(ht/2);

        //alert(posX);

        popLayer.style.top = posY + "px";
	    popLayer.style.left = posX + "px";

        //popLayer.style.top = tp + "px";
		//popLayer.style.left = lft + "px";



        setDropdownVisibility(window, "hidden");
	} else {
		var settings = "height=" + ht + ",width=" + wid + ",status=no,toolbar=no,menubar=no,location=no";
		currentPopupWin = window.open("<util:envurl path='/atlblank.jsp' />", popupName, settings);
		if (window.focus) {currentPopupWin.focus();}
	}
}

function closePopup(popupName, closeLocation, redirect) {
	if (useNonMacMSPops) {
		var popLayer = document.getElementById(popupName + "Top");
		popLayer.style.visibility = "hidden";
		setDropdownVisibility(parent, "visible");
		document.getElementsByName(popupName)[0].src="<util:envurl path='/atlblank.jsp' />";
		if (redirect == "true" ) {
			window.location = closeLocation;
		}
	}
}

function setDropdownVisibility(win, visibility) {
	if (useNonMacMSPops) {
		var doc = win.document;
		var dropdowns = doc.getElementsByTagName("select");
		for (var i = 0; i < dropdowns.length; i++) {
			if (!hasHiddenAncestor(doc, dropdowns[i])) dropdowns[i].style.visibility = visibility;
		}
	}
}

function hasHiddenAncestor(doc, elem) {
	if ((doc == elem) || (elem.nodeType == 9))
		return false;
	var mom = elem.parentNode;
	if (mom.nodeType == 1) {
		var momsStyle;
		var momsVis;
		var momsDisp;
		if (mom.currentStyle) {
			momsStyle = mom.currentStyle;
			momsVis = momsStyle.visibility;
			momsDisp = momsStyle.display;
		} else {
			momsStyle = window.getComputedStyle(mom,"");
			momsVis = momsStyle.getPropertyValue("visibility");
			momsDisp = momsStyle.getPropertyValue("display");
		}
		if ((momsVis == "hidden") || (momsDisp == "none"))
			return true;
		else
			return hasHiddenAncestor(doc, mom);
	}
}

function addPopup(popupName, closeLocation, redirect){
	// Generic popup.  It consists of a layer containing an iframe.  The layer provides control over visibility,
	// positioning and sizing, while the iframe provides a target for forms and links, plus scrollbars, when needed.
	if (useNonMacMSPops) {
		document.write('<div id="' + popupName + 'Top" class="popLyr">');
		document.write('	<div id="' + popupName + 'Inner" class="popLyrInr">');
		document.write('		<div id="' + popupName + 'Header" class="popLyrHdr" onmousedown="beginPopupDrag(document.getElementById(\'' + popupName + 'Top\'),event);">');

		document.write('			<html:img styleId="' + popupName + 'TitleImage" src="/assets/images/header/nv_logo_sm.gif" env="css" alt="Ann Taylor LOFT" styleClass="popTtl" onMouseDown="return false;" onMouseMove="return false;" />');
		document.write('			<a href="#null" onclick="closePopup(\''+popupName+'\', \''+closeLocation+'\', \''+redirect+'\');return false;"><html:img src="/assets/images/buttons/b_closewindow.gif" env="css" alt="close window" styleClass="popClose" /></a>');

		document.write('		</div>');
		document.write('		<iframe name="' + popupName + '" id="' + popupName + '" src="/atlblank.html" />" frameborder="no" marginheight="0" marginwidth="0"></iframe>');
		document.write('	</div>');
		document.write('</div>');
	}
}

//*****************************************************************************
// The following two functions are copied from the js library /js/dragdrop.js *
//*****************************************************************************

function beginPopupDrag(elementToDrag, event) {
	var deltaX = event.clientX - parseInt(elementToDrag.style.left);
	var deltaY = event.clientY - parseInt(elementToDrag.style.top);
	if (document.addEventListener) {
		document.addEventListener("mousemove", moveHandler, true);
		document.addEventListener("mouseup", upHandler, true);
		document.addEventListener("mouseout", upHandler, true);
	} else if (document.attachEvent) {
		document.attachEvent("onmousemove", moveHandler);
		document.attachEvent("onmouseup", upHandler);
		document.attachEvent("onmouseout", upHandler);
	}

	if (event.stopPropogation) event.stopPropogation();
	else event.cancelBubble = true;

	if (event.preventDefault) event.preventDefault();
	else event.returnValue = false;

	function moveHandler(e) {
		if (!e) e = window.event;
		elementToDrag.style.left = (e.clientX - deltaX) + "px";
		elementToDrag.style.top = (e.clientY - deltaY) + "px";

		if (e.stopPropogation) e.stopPropogation();
		else e.cancelBubble = true;
	}

	function upHandler(e) {
		if (!e) e = window.event;

		if (document.removeEventListener) {
			document.removeEventListener("mouseup", upHandler, true);
			document.removeEventListener("mousemove", moveHandler, true);
			document.removeEventListener("mouseout", upHandler, true);
		} else if (document.detachEvent) {
			document.detachEvent("onmousemove", moveHandler);
			document.detachEvent("onmouseup", upHandler);
			document.detachEvent("onmouseout", upHandler);
		}
	}
	function getUpHandler() {
		return upHandler;
	}
}

// This appears to be some sort of vestige code that should probably be removed.
function detachOuterElement(popId) {
	if (document.removeEventListener) {
		;
	} else {
		;
	}
}

function printPopup(frameName) {
window.frames[frameName].focus();
window.frames[frameName].print();
}