// 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);
                    $share.kbNavigationBlock();
                },
                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;
    });

    // Not all browsers apply focus to the target of a hash url
    // so we work around this problem for the skip-to link.
    if (jQuery.browser && (jQuery.browser.webkit || jQuery.browser.opera)) {
        $('#skip-link a').click(function () {
            var selector = "a, area, object, :input:enabled";
            $('#skip-to-main-content')
            .nextAll()
            .each(function (i, el) {
                el = $(el)
                .filter(selector)
                .add($(selector, el))
                .filter(':visible')
                .eq(0);
                if (el.length > 0) {
                    el.focus();
                    return false;
                }
            });
        });
    }


    /* Handle hover states for buttons and images */
    $("input.js-hasHover, img.js-hasHover").each(function(){
       var $this = $(this);
       $this.bind("mouseenter mouseleave focusin focusout", function(e){
           $this.toggleClass("hover")
                .attr("src", $this.attr("src").replace(/_(off|on)\./, (e.type == "mouseenter" || e.type === "focusin" ? "_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 quicklook overlay */
    $(".quick-look").click(function() {
    quickViewCommands[0]=$(this).children("#quick-lookUrl").text();
        if( $("#widget-quickview").size() == 0 )
        { loadQuickView('show','.products'); }
    });
 
    /* Product grid overlay */
    $("div.products > div.grid").find("div.product").each(function(){
        var $this = $(this),
            $overlay = $.browser.msie ? $this.find("a.quick-look").css({ "visibility": "hidden", "display": "block" }) : $this.find("a.quick-look").css({ "opacity": 0, "display": "block" }),
            $meta = $this.find("div.meta");
        
        if($this.parent().parent().is(".showDetails")) { $overlay.css({"opacity": 1}); return; }
        $("div.outfits").css("position", "relative");


        $this.hover(
            function(){
                if($.browser.msie) {
                  $overlay.css({'visibility': 'visible'});
                } else {
                  $overlay.stop().animate({"opacity": 1}, function(){ if($.browser.msie){ this.style.removeAttribute("filter"); } }); 
                  $meta.stop().animate({"opacity": 0});
                }
            },
            function(){ 
                if($.browser.msie) {
                  $overlay.css({'visibility': 'hidden'});
                } else {
                  $overlay.stop().animate({"opacity": 0}); 
                  $meta.stop().animate({"opacity": 1}, function(){ if($.browser.msie){ this.style.removeAttribute("filter"); } });
                }
            })
        .kbhover();
    })

    /* 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")));
                             
                         }
                     )
                     .kbhover();
                     
                     $secondary.each(function(){
                         var $this = $(this),
                             $a = $this.find("a");
                         $this.hover(
                             function(){ $this.addClass("hover"); },
                             function(){ $this.removeClass("hover"); }
                         )
                         .kbhover();
                         $this.click(function(){
                             window.location = $a.attr("href");
                         });
                         $a.click(function(e){
                             eval($a.attr("onclick"));
                             e.preventDefault();
                         });
                     });
                    });
    /* End Primary Nav code */
    
    /* set up default text for search box, newsletter field, additional delivery instructions  */
    lib.input.defaultText("#SiteSearch", {defaultText: "Search Keyword or Item #"}) ;
    lib.input.defaultText("#FooterSignup", {defaultText: "Sign-up for updates"}) ;
    lib.input.defaultText("#delivText", {defaultText: ""});
    /* character limit for gift box message, additional delivery instructions */
    lib.input.setMaxCharacters("#gift-msg", {limit: 120, results: "#gift-msg-count"});
    lib.input.setMaxCharacters("#delivText", {limit: 30, results: "#add-instr-count"});

    /* 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]+"_"+baseImage[1] + "_off.gif";
		var onPath =  baseImage[0]+"_"+baseImage[1] + "_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),
            returnFocus = document.activeElement,
            popupWidth = $this.attr("data-width") || 431,
            iframeSRC = $this.attr("href");
        iframeHeight = $this.attr("data-height") || 310;
	lib.layer.create("#genericLayerContent", {
	    closeSelector : ".js-closeLayer",
	    url : "/loft/custserv/popupFrame.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");
                $("#genericLayerContent").kbNavigationBlock(returnFocus);
	    }
	});
	evt.preventDefault();
    });
    /* ------------------- */
    
        /* Setup any Generic Popups */
    $(".js-profilePopup").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 : "/loft/custserv/profilePopupFrame.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();
    });
    /* Setup any Small Generic Popups */
    $(".js-genericPopupSmall").click(function(evt) {
	var $this = $(this),
            returnFocus = document.activeElement,
            popupWidth = $this.attr("data-width") || 450,
            iframeSRC = $this.attr("href");
        iframeHeight = $this.attr("data-height") || 330;
	lib.layer.create("#genericLayerContent", {
	    closeSelector : ".js-closeLayer",
	    url : "/loft/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");
                $("#genericLayerContent").kbNavigationBlock(returnFocus);
	    }
	});
	evt.preventDefault();
    });
    /* ------------------- */
    
    /* Setup any Generic Popups with no logo */
    $(".js-genericPopupNoLogo").click(function(evt) {
	var $this = $(this),
            returnFocus = document.activeElement,
            popupWidth = $this.attr("data-width") || 685,
            iframeSRC = $this.attr("href");
        iframeHeight = $this.attr("data-height") || 450;
	lib.layer.create("#genericLayerContent", {
	    closeSelector : ".js-closeLayer",
	    url : "/loft/custserv/generic_layer_nologo.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");
                $("#genericLayerContent").kbNavigationBlock(returnFocus);
	    }
	});
	evt.preventDefault();
    });
    /* ------------------- */
        /* ------------------- */

 
    /* Setup any Generic Popups with no logo small */
    $(".js-genericPopupNoLogoSmall").click(function(evt) {
		var $this = $(this),
            returnFocus = document.activeElement,
            popupWidth = $this.attr("data-width") || 585,
            iframeSRC = $this.attr("href");
            iframeHeight = $this.attr("data-height") || 450;
		lib.layer.create("#genericLayerContent", {
			closeSelector : ".js-closeLayer",
			url : "/loft/custserv/generic_layer_nologo.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");
                $("#genericLayerContent").kbNavigationBlock(returnFocus);
			}
		});
		evt.preventDefault();
	});
    /* ------------------- */


    /* Setup any Generic Popups Large Size with no logo */
    $(".js-genericPopupNoLogoLarge").click(function(evt) {
	var $this = $(this),
            returnFocus = document.activeElement,
            popupWidth = $this.attr("data-width") || 845,
            iframeSRC = $this.attr("href");
        iframeHeight = $this.attr("data-height") || 450;
	lib.layer.create("#genericLayerContent", {
	    closeSelector : ".js-closeLayer",
	    url : "/loft/custserv/generic_layer_nologo.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");
                $("#genericLayerContent").kbNavigationBlock(returnFocus);
	    }
	});
	evt.preventDefault();
    });
    /* ------------------- */    

    setTimeout(function () {
      $('body').fixMissingHref();
    }, 50);
    $('body').ajaxSuccess(function (e, xhr, settings) {
      setTimeout(function () {
        $('body').fixMissingHref();
      }, 50);
    });
});

/* close generic popups */
function removeBillingAddress() {
    lib.layer.remove('#genericLayerContent');
}
function removeCreditCard() {
    lib.layer.remove('#genericLayerContent');
}
/* ------------------- */

/*

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="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();
    }
	
(function ($) {
  "use strict";

  // the kbhover() jQuery plugin triggers the analogous hover effect on the jQuery element
  // when a focus event occurs on it or one of it's children. This provides the same user user 
  // experience for keyboard navigation as for mouse navigation.
  $.fn.kbhover = function () {
    var selector = "a, area, object, :input";
    return this.each(function (i, el) {
      $(selector, el).add($(el).is(selector) ? el : null).bind("focusin focusout", function (event) {
        $(el).trigger(event.type === "focusin" ? "mouseenter" : "mouseleave");
      });
    });
  };

  // Add default (NOP) href attribute on any anchor missing an href
  $.fn.fixMissingHref = function () {
    $("a", this).each(function () {
      $(this).attr('href', function (i, o) { return (o ? o : 'javascript:void(0);'); });
    });
    return this;
  };

  // Create a keyboard navigation cycle by placing navigation sentinal
  // links before and after the innerhtml of each jQuery element. When a 
  // sentinal gains focus, an event handler will pass focus to the opposite
  // sentinal, keeping focus between the sentinal pairs.  Note that the last 
  // tab direction determines how the keyboard user passes through a sentinal.
  // 
  // Note that this effectively creates a keyboard trap unless the caller
  // provides an exit link.  If the exit link uses the site default css class,
  // then the keyboard focus will be returned to returnFocus element in
  // click. returnFocus defaults to the active element.
  //
  // Focus is initially sent to the first sentinal in the first jQuery object.
  (function () {
    var forwardTab = true,
        mousedown = function (e) {
          forwardTab = true;
        },
        keypress = function (e) {
          if (e.which === 9 || e.keyCode === 9) {
            forwardTab = (e.shiftKey) ? false : true;
          }
        },
        html = '<div class="focus-link-container"><a href="javascript:void(0);"></a></div>'
        ;
  
    $.fn.kbNavigationBlock = function (returnFocus) {
      returnFocus = returnFocus || document.activeElement;
      $(this).each(function () {
        var that = this;
        $(this)
        .prepend($(html).find('a').addClass('focus-link-first').end())
        .append($(html).find('a').addClass('focus-link-last').end())
        .unbind('mousedown', mousedown)
        .unbind('keydown', keypress)
        .bind('mousedown', mousedown)
        .bind('keydown', keypress)
        .find(".focus-link-first", this)
        .focus(function () {
          if (forwardTab === false) {
            $(".focus-link-last", that).focus();
          }
        })
        .end()
        .find(".focus-link-last", this)
        .focus(function () {
          if (forwardTab === true) {
            $(".focus-link-first", that).focus();
          }
        })
        .end()
        .find(".js-close, .closeLink, .js-closeLayer")
        .click(function () {
          $(that).unbind('mousedown', mousedown);
          $(that).unbind('keydown', keypress);
          $(returnFocus).focus();
        })
        .end()
        ;
      })
      .find(".focus-link-first:first")
      .focus();
      return this;
    };

    // add support for activeElement on older browsers
    if (typeof document.activeElement === 'undefined') {
        try {
            document.activeElement = null;
            document.addEventListener("focus", function () {
                try {
                    document.activeElement = e.target === document ? null : e.target;
                } catch(e1) {
                    throw(e1);
                }
            }, true);
        } catch(e2) {
        }
    } 

  }());
}(jQuery));

