$(document).ready(function(){

	$(document).keydown(function(event){
        if (event.keyCode == 9)
        {
                tabdown = true;
        }
	});
	
	$(document).keyup(function(event){
        if (event.keyCode == 9)
        {
                tabdown = false;
        }
	});

	initializeShoppingBag();
	
	$("li#globalShoppingBag a").hover(function(){
		$(this).css({"cursor":"pointer"});
	},function(){
	
	});	
});

var tabdown = false;
var reallyOpen = null;
ROSB = {
	listen: function(delay){
			
		sbModelData.shoppingBagLinkURL = sbConfig.miscobj.shoppingBagURL;

		
//		$("li#globalShoppingBag a").attr("onclick","return storeClick();");
		
//		$(".SB_PopInTab a").attr("onclick","return storeClick();");
	
		if (typeof(sbRolloverDisable) == "undefined" || sbRolloverDisable == false) {
			var reallyOpen;
			//OPEN POPIN ON HOVER OVER SHOPPING BAG, UNDERLINE TEXT LINK ON HOVER OVER IMAGE
			$("li#globalShoppingBag").hover(
				function(){
					if (sbConfig.miscobj.isSignature != 'true')
					{
					$("li#globalShoppingBag span a").css({"text-decoration":"underline", "color":"#990000"});
					$("li#globalShoppingBagData").css({"text-decoration":"none", "color":"#4D4D45"});
					}
					var delayedOpen = "SBPopin.openROSB()";
					reallyOpen = setTimeout(delayedOpen, delay);
				},
				function(){
					if (sbConfig.miscobj.isSignature != 'true')
					{
					$("li#globalShoppingBag span a").css({"text-decoration":"none", "color":"#4D4D45"});
					}
					clearTimeout(reallyOpen);
					delete reallyOpen;
				}
			);			

			$("li#globalShoppingBag").click(function(){
				storeClick();
				SBPopin.close();
			});

			//OPEN POPIN ON HOVER OVER SHOPPING BAG
			$("li#globalShoppingBag a").focus(function(){
					if (tabdown == false)
					{
						return;
					}
					tabdown = false;
					SBPopin.close();
					//FIVE MINUTE CLOSE TIMER
					var duration = sbConfig.miscobj.rosbCloseTimer;
					SBPopin.openROSB(duration);
			});
		}
	}
}

SBPopin = {
	openROSB: function(){
		
		//BEGIN FPO SUPPRESSION
		if (sbModelData.numItemsInCart <= 0)
		{
			return;
		}
		
		if (sbModelData.pasbInProgress) // if pasb is in progress, don't bother displaying information
		{
			return;	
		}
		if (sbModelData.rosbInProgress) // if rosb is in progress, don't bother displaying information
		{
			return;
		}
		
		if (sbModelData.disableRollOver)
		{
			return;   
		}
		
		$("span.SB_PopInContentHeaderAdded").css("display","none");
		//END FPO SUPPRESSION		
		sbController.onROSB();
		SBPopin.build();
		eval( $(".ROSB_JSDiv").html() );
		SBPopin.align();
		//FPO AJAX LOAD TIME SIMULATION WITH DISPLAY RESET
		if (sbModelData.rosbComplete == true)
		{
			sbController.onReadyToDisplay();
		}
		else
		{
			$("div.SB_PopInContentContainer").addClass("SB_PopInLoading");
			$("div.popInContainer div.SB_PopInLoadingContainer").css({"display":"inline", "float":"left"});
			$("div.popInContainer div.SB_PopInContentWrapper").css({"display":"none"});
			$("div.popInContainer").addClass("overPopin"); 
		}
		
		if(!isSignature){
		
			headerPopin.forceClose();
		
		}
		
		fixQuirks();
	},

	openPASB: function(){
		SBPopin.close();
		 backupBrowserWrite = document.write;
                document.write = writeReplacement;
		if (typeof(sbRolloverDisable) != "undefined" && sbRolloverDisable == true) {
			return;	
		}
		//TWENTY SECOND CLOSE TIMER
		var duration = sbConfig.miscobj.pasbCloseTimer; 
		var miopError = sbConfig.miscobj.miopPasbErrorMessage;
		if (typeof(isMiopPasbError) != 'undefined' && isMiopPasbError == true)
		{
			$(".SB_PopInErrorContainer").html(miopError);
			$(".SB_PopInErrorContainer").css({"display":"inline"});
		}
		SBPopin.build();
		eval( $(".SB_JSDiv").html() );
		eval( $(".PASB_JSDiv").html() );
		SBPopin.align();

		//FPO AJAX LOAD TIME SIMULATION WITH DISPLAY RESET
		
		$(".Add_to_Shopping_Bag").css({"display":"none"});
		$(".Inactive_Add_to_Shopping_Bag").css({"display":"inline"});
		
		$("span.SB_PopInContentHeaderAdded").css("display","inline");
		sbController.onReadyToDisplay();
		
		fixQuirks();
		try
		{
        if (typeof ll_RR=="object"){
          var x= ( typeof sbProducts!="undefined" ? sbProducts : '' );
          ll_RR.richRelevancePASBCaller(x);
 
          if(ll_RR.abSeg != 'a'){
            $('.ll_atb_dds').css('display', 'block'); 
          }


        }
		populateMetricsObject("pasb");
		} catch(err) {}
		//alert('submitting metrics');
		var s_code = s_o_sc.t();
		document.write = backupBrowserWrite;
	},
	
	build: function(){
		var SB_PopInContainer = ".SB_PopInContainer";
		popInContainer = document.createElement("div");
		$(popInContainer).addClass("popInContainer");
		$("body").append(popInContainer);
		$("div.popInContainer").html($(SB_PopInContainer).html());
		$("div.popInContainer").fadeIn("fast");

		//FIX IE6 SELECT HACK
		if($.browser.msie && $.browser.version < 7){
			$("select").animate({opacity:"hide"});
		}

		//SET FOCUS ON POPIN 
		$("div.popInContainer div.SB_PopInContentHeaderButton a").focus();		
		
		//CLOSE POPIN ON CLOSE BUTTON CLICK
		$("div.popInContainer div.SB_PopInContentHeaderButton *").click(function(){
			$("div.popInContainer").removeClass("overPopin");
			SBPopin.close();
			$("#hsearchinput").focus();
			return false;
		});		

		//UNDERLINE TEXT LINK ON HOVER OVER TAB
		$("div.popInContainer .SB_PopInTabWrapper *").mouseover(function(){
				$("div.popInContainer div.SB_PopInTabLabel").addClass("tabHover");
				$("div.popInContainer div.SB_PopInTabWrapper").addClass("overPopinTab");
		});
		$("div.popInContainer div.SB_PopInTabWrapper").mouseout(function(){
				$(".tabHover").removeClass("tabHover");
				$("div.popInContainer div.SB_PopInTabWrapper").removeClass("overPopinTab");
		});	
		
		//CLOSE POPIN ON GLOBAL DROPDOWN OPEN
		$(".categoryListItem").hover(
			function(){
				$("div.popInContainer").removeClass("overPopin");
				SBPopin.close();
			},
			function(){
			}
		);		
				
		$("div.SB_PopInTab a").hover(function(){
			$(this).css({"cursor":"pointer"});
		},function(){
		
		});	
		
		//RETURN PAGE TO TOP ON OPEN
		window.scrollTo(0,0);
				
	},

	setBehaviors: function(duration){
		//SET POPIN AUTO-CLOSE AFTER X MILLISECONDS
		timeout.initiate(duration);
		
		//SET POPIN AUTO-CLOSE ON MOUSE-OFF AFTER MOUSE-ON WITH THREE SECOND DELAY
		var reallyClose;
		var closeDelay = sbConfig.miscobj.mouseOffCloseDelay;
		$("div.popInContainer").hover(
			function(){
				clearTimeout(reallyClose);
				delete reallyClose;				
				timeout.suspend();
				$("div.popInContainer").addClass("overPopin");      
			},
			function(){
				reallyClose = setTimeout("SBPopin.close()", closeDelay);
				$(".overPopin").removeClass("overPopin");
		});			
	
		$("div.popInContainer .SB_PopInItemContainer").scroll(function () { 
		  $("div.popInContainer").addClass("overPopin");
		});
		
		
		//SUSPEND POPIN AUTO-CLOSE ON MOUSE-OFF WITH SCROLL
		$(window).scroll(function () { 
			clearTimeout(reallyClose);
			delete reallyClose;				
		});
	},	

	align: function(){
		
		if (sbConfig.miscobj.isSignature == 'true')
		{
			var popinOffset = $("li#globalShoppingBag").offset().top + 47;
			var popinOffsetLeft = $("li#globalShoppingBag").offset().left - 283;
			
			if($.browser.msie && $.browser.version < 7){
				popinOffset = $("li#globalShoppingBag").offset().top + 61;
				popinOffsetLeft = $("li#globalShoppingBag").offset().left - 299;
			}
			
			$("div.popInContainer").css({"margin-top":popinOffset, "left":popinOffsetLeft});
			
			if($.browser.msie && $.browser.version > 6){
			
				$("div.SB_PopInContentWrapper").css({"margin-top":"0px"});
				
				$("div.popInContainer div.SB_PopInWrapper div.SB_PopInContentContainer").attr({"style":"padding-bottom:10px!important"});
			
			}
			
		}
		else
		{
		/*
		var popinOffset = $("li#globalShoppingBag").offset().top + 26;
		
		if($.browser.msie && $.browser.version < 7){
			popinOffset = $("li#globalShoppingBag").offset().top + 46;
		}
		$("div.popInContainer").css("margin-top",popinOffset);
		*/
		
		/*
		//FPO TODO: REMOVE
		var isSignature = false;
		//FPO TODO: REMOVE
		
		
		if(isSignature){
			var popinOffset = $("li#globalShoppingBag").offset().top + 47;
			var popinOffsetLeft = $("li#globalShoppingBag").offset().left - 283;
			
			if($.browser.msie && $.browser.version < 7){
				popinOffset = $("li#globalShoppingBag").offset().top + 61;
				popinOffsetLeft = $("li#globalShoppingBag").offset().left - 299;
			}
		}else */
		
		if(misc_str_isjapan == "false"){
			var popinOffset = $("li#globalShoppingBag").offset().top + 45;
			var popinOffsetLeft = $("li#globalShoppingBag").offset().left - 289;
			
			
			
			if($.browser.msie && $.browser.version < 7){
				popinOffset = $("li#globalShoppingBag").offset().top + 45;
				popinOffsetLeft = $("li#globalShoppingBag").offset().left - 317;
			}
			/*else if($.browser.msie && $.browser.version >= 7){
				//popinOffset = $("li#globalShoppingBag").offset().top + 26;
				//popinOffsetLeft = $("li#globalShoppingBag").offset().left - 283;
				//$(".SB_PopInTabData").css({"margin-top":"-1px"});
			}*/		
			
		
		}else{
			var popinOffset = $("li#globalShoppingBag").offset().top + 41;
			var popinOffsetLeft = $("li#globalShoppingBag").offset().left - 242;
			
			if($.browser.msie && $.browser.version < 7){
				popinOffset = $("li#globalShoppingBag").offset().top + 61;
				popinOffsetLeft = $("li#globalShoppingBag").offset().left - 267;
			}/*else if($.browser.msie && $.browser.version >= 7){
				popinOffset = $("li#globalShoppingBag").offset().top + 42;
				popinOffsetLeft = $("li#globalShoppingBag").offset().left - 282;
				$(".SB_PopInTabData").css({"margin-top":"-1px"});
			}	*/
		
		}
		
		$("div.popInContainer").css({"margin-top":popinOffset, "left":popinOffsetLeft});
		
		
		//var positionLeft = $("li#globalShoppingBag").offset().left - 284;
		
		//$("div.popInContainer").css({"left": positionLeft});	

		}
		
		
		//MAX-HEIGHT FIX
		var shoppingBagLength = 0;
		if( typeof(window.itemRowDivCount) != "undefined") {
			shoppingBagLength = window.itemRowDivCount;
		}
		if(shoppingBagLength <= 3){
			$("div.popInContainer div.SB_PopInItemWrapper").parent().css({"height":"auto"});
		}
		
		//var positionLeft = $("li#globalShoppingBag").offset().left - 284;
		
		//$("div.popInContainer").css({"left": positionLeft});	

	},
	
	populate: function(duration){
		
		//executing popin JS in special div in rosbIncl.jsp and pasbIncl.jsp
		eval( $(".SB_JSDiv").html() );
		eval( $(".ROSB_JSDiv").html() );
		
		if(duration == null){
			duration = sbConfig.miscobj.pasbCloseTimer;
		}
		//FPO AJAX LOAD SIMULATION - AJAX CALL COULD BE USED HERE
		$(".SB_PopInLoading").removeClass("SB_PopInLoading");
		$("div.SB_PopInLoadingContainer").hide();
		SBPopin.align();
		$("div.SB_PopInContentWrapper").fadeIn(sbConfig.miscobj.fadeInSpeed);
		SBPopin.setBehaviors(duration);
		fixQuirks();
	},
	
	close: function(){

		if(!$("div.popInContainer").hasClass("overPopin")){
			
			//$("div.popInContainer").fadeOut("fast",function(){});
			
			//FIX IE6 SELECT HACK
			if($.browser.msie && $.browser.version < 7){
				// show all select boxes except inseam
				$("select:not(#inseam_cuffs, #inseam_nocuffs)").animate({opacity:"show"});
			}
			//$("select").animate({opacity:"show"});
			
			if (!sbModelData.pasbInProgress)
			{
				$(".Inactive_Add_to_Shopping_Bag").css({"display":"none"});
				$(".Add_to_Shopping_Bag").css({"display":"inline"});
			}
			$("div.popInContainer").remove();
			$("div.SB_PopInErrorContainer").css({"display":"none"});

		}

	}	
}

timeout = {
	initiate: function(duration){
		this.ID = setTimeout("SBPopin.close()", duration); 
	},
	suspend: function(){
		clearTimeout(this.ID);
		delete this.ID;
	}
}

function initializeShoppingBag(){
	//DEFAULT ONE-HALF A SECOND OPEN DELAY
	
	if (typeof sbConfig == 'undefined')
	{
		return;	
	}
	
	sbModelData.setItemsLink();
	
	// this will be called when the page is MIOP. In MIOP, this utilityFunction used
	// to be added to run on load using the addOnLoadEvent method in globalonLoad. This
	// utility function was running after the pop up here in initializeShoppingBag.
	// utilityFunction builds the select inputs so this was causing a bleed through
	// issue in IE 6. The call has now been brought here to initializeShoppingBag
	// to have more control and make sure it runs before the pop up layer.
	if (typeof(callUtilityFunction) != "undefined" && callUtilityFunction == true)
	{
		utilityFunction();
	}
	
	var delay = sbConfig.miscobj.rosbDelayTimer; 
	ROSB.listen(delay);

	if (typeof(pasbError) != "undefined" && pasbError == true)
	{
		$("#pp_ajaxPasbError").html(sbConfig.miscobj.pasbErrorMessage);
		$(".pp_PasbErrorHTML").css({"display":"inline"});
		if(typeof adjustToOrderColumnHeight == 'function')
		{
			adjustToOrderColumnHeight();
		}
	}
	else if (isPASB != undefined && isPASB == 1)
	{
		SBPopin.openPASB();
	}
	
	//FPO: REALIGN SHOPPING BAG ON WINDOW RESIZE
        $(window).resize(function(){
               SBPopin.align();
        });	
}

function populateMetricsObject(callType) {
	
    var sig='';
    if(typeof(sigPage)!='undefined') sig='SIG-';
        
	if(typeof(sbPageName) != "undefined") {
		s_pageName = sig+sbPageName;
	}
	if(typeof(sbEvent) != "undefined") {
		s_events = sbEvent;
        if (gcookie("FSRCookie") && sbEvent.indexOf('scAdd')>-1){
          // foresee var passed if cookie present;see also metrics for visitorid
          foresee.ForeCStdSetCookie(foresee.triggerParms["oecpp_bagFlag"], 1, null, "/", foresee.triggerParms["domain"]);	
        }
	}
	if(callType== 'pasb' && typeof(sbProducts) != "undefined") {
		s_products = sbProducts; 
	}
	s_prop1 = llcdata;
	if(typeof(sbProp2) != "undefined") {
		s_prop2 = sbProp2;
	}
	if(typeof(sbProp4) != "undefined") {
		s_prop7= s_prop4 = sbProp4;
	}
    if(ll_o.sigInd.length>1){
      s_prop9=ll_o.sigInd+s_prop4;
      s_prop11=ll_o.sigInd+s_prop7; 
    }

	s_prop11 = s_eVar21+":"+s_prop4;
	
	if(typeof(sbDDSEvent) != "undefined") {
		s_prop19 = sbDDSEvent;
	}
	if(typeof(sbDDSProducts) != "undefined") {
		s_prop20 = sbDDSProducts;
	}
	if(typeof(sbDDSSegment) != "undefined") {
		s_prop21 = sbDDSSegment;
	}
	
	s_prop22 = getMemberId();
    s_eVar14=hasLoginCookie();
	
	if(typeof(sbVar18) != "undefined") {
		s_eVar18= sbVar18;
	}

    if (callType=="pasb"){
      handleDDS();
      s_prop19 =DDSEvent;
      s_prop20 =DDSProducts;
      s_prop21 =DDSSegment;
      
    }

    oapSeg();
	s_eVar21 = llev21;
	s_eVar22 = llev22;
	s_eVar23 = llev23;

}

//FPO: SHOPPING BAG TAB IMAGE PRE-LOAD
$.preloadImages = function(){
	image1 = new Image(133,37);
	image1.src = imagePath + "img_top_rounded_tab.gif";
	image2 = new Image(37,34);
	image2.src = imagePath + "shopping_bag_full.gif";
	image3 = new Image(6,10);
	image3.src = imagePath + "nav_bullet.gif";	
}	
$.preloadImages();


function fixQuirks(){
	if(!$.browser.safari){
		var mode = document.compatMode;
		if(mode){
			if(mode == "BackCompat" && $.browser.msie && $.browser.version < 7){
				$("div.popInContainerdiv.SB_PopInWrapper").css({"width":"auto"});
				$("div.popInContainer div.SB_PopInContentContainer").css({"width":"434px"});
				$("div.popInContainer div.SB_PopInContentWrapper").css({"width":"438px"});
				$("div.popInContainer div.SB_PopInContentHeaderContainer").css({"width":"416px"});
				$("div.popInContainer div.SB_PopInContentError").css({"padding-left":"11px"});
				$("div.popInContainer div.SB_PopInData").css({"width":"420px"});
				$("div.popInContainer div.SB_PopInData").css({"width":"420px"});
				$("div.popInContainer div.SB_PopInButtonsWrapper").css({"width":"260px"});
				$("div.popInContainer ul.SB_PopInYMACItemImages").css({"width":"420px"});
				$("div.popInContainer ul.SB_PopInYMACItemImages li").css({"width":"138px"});
				$("div.popInContainer ul.SB_PopInYMACItemLinks").css({"width":"420px"});
				$("div.popInContainer ul.SB_PopInYMACItemLinks li").css({"width":"138px"});
				$("div.popInContainer ul.SB_PopInYMACItemRatings").css({"width":"420px"});
				$("div.popInContainer ul.SB_PopInYMACItemPrices").css({"width":"420px"});
			}else if(mode == "BackCompat" && $.browser.msie){
				$("div.popInContainer").css({"width":"425px","margin-top":"62px"});
				$("div.popInContainer div.SB_PopInWrapper").css({"width":"auto"});
				$("div.popInContainer div.SB_PopInContentContainer").css({"width":"425px"});
				$("div.popInContainer div.SB_PopInContentHeaderContainer").css({"width":"425px"});
				$("div.popInContainer div.SB_PopInData").css({"width":"425px"});
				$("div.popInContainer div.SB_PopInData").css({"width":"425px"});
				$("div.popInContainer div.SB_PopInButtonsWrapper").css({"width":"265px"});
				$("div.popInContainer ul.SB_PopInYMACItemImages").css({"width":"420px"});
				$("div.popInContainer ul.SB_PopInYMACItemImages li").css({"width":"138px"});
				$("div.popInContainer ul.SB_PopInYMACItemLinks").css({"width":"420px"});
				$("div.popInContainer ul.SB_PopInYMACItemLinks li").css({"width":"138px"});
				$("div.popInContainer ul.SB_PopInYMACItemRatings").css({"width":"420px"});
				$("div.popInContainer ul.SB_PopInYMACItemPrices").css({"width":"420px"});
			}
		}
	}
}



// begin AJAX code

//begin command object	
var sbCmds={
	rosb:{
		execute: function() {
			var serviceURL = sbConfig.servicesobj.rosbAddress;
			serviceURL += "?ajaxReq=1";
			serviceURL += "&" + sbConfig.contextobj.commonURLParms;
			sbCmds.ajaxCall(serviceURL, this.onResult, this.onFault);
		},
		onResult: function(type, data, evt) {
			/*
				We need to test if ROSB is still marked as in progress. If it isn't, then it means
				PASB reset it to false. If PASB reset it, then the call back method for ROSB should
				discard the data.
			*/
			if (!sbModelData.rosbInProgress)
			{
				sbModelData.rosbComplete = false;
				return;	
			}
			if (data == null)
			{
				sbController.onRosbFaultResult();
				sbModelData.rosbInProgress = false;
				sbModelData.rosbComplete = false;
				return;
			}			
			
			if (sbModelData.linkClicked)
			{
				window.location = sbModelData.shoppingBagLinkURL;
			}
			sbModelData.setItemsLink();
			sbModelData.setRosbResponse(data); // else, update div with returned data
			sbModelData.rosbInProgress = false;
			sbModelData.pasbComplete = false;
			sbModelData.rosbComplete = true; // set status to complete so next time rolled over, it will display without making an ajax call
		},
		onFault: function(type, error) {
			if (sbModelData.pageUnload)
			{
				return;	
			}
			if (!sbModelData.rosbInProgress)
			{
				sbModelData.rosbComplete = false;
				return;
			}
			sbController.onRosbFaultResult();
			sbModelData.rosbInProgress = false;
			sbModelData.rosbComplete = false;
		}
	},
	pasb:{
		execute:function(){
			document.body.style.cursor = 'progress';
			var serviceURL = sbConfig.servicesobj.pasbAddress;
			serviceURL += "?" + sbModelData.atbQuerystring;
			serviceURL += "&ajaxReq=1";
			sbCmds.ajaxCall(serviceURL, this.onResult, this.onFault);
		},
		onResult: function(type, data, evt) {
			sbModelData.setPasbResponse(data);
			sbModelData.setItemsLink();
			resetFlag(); // reset double click after response has been received
			sbModelData.pasbInProgress = false;
			sbModelData.pasbComplete = true;
			document.body.style.cursor = 'auto';
		},
		onFault: function(type, error) {
			sbController.onPasbFaultResult();
			resetFlag(); // reset double click after response has been received
			sbModelData.pasbInProgress = false;
			sbModelData.pasbComplete = true;
		}
	},
	ajaxCall:function(url,onsuccess,onfailure) {
		var req = null;
		if (window.XMLHttpRequest) {
			req = new XMLHttpRequest();
		} else if (window.ActiveXObject){
			req = new ActiveXObject("Microsoft.XMLHTTP");
		}
		//util.debug("url="+url);
		req.open("GET", url, true);
		req.onreadystatechange = function(){
			if(req.readyState == 4) {
				if (req.status == 302) {
					redirectLogoff();
				} else if (req.status == 200) {
					if (req.responseText.indexOf('meta http-equiv="Refresh"') > -1 && req.responseText.indexOf('sessionTimeout') > -1)
					{
						redirectLogoff();
					}
					else
					{
						onsuccess("load",req.responseXML,req);
					}
				} else {
					onfailure("error",req.responseXML,req);
				}
			}
		};
		req.send(null);
	}
};
//end command object

function redirectLogoff()
{
	window.location = '/webapp/wcs/stores/servlet/Logoff?storeId=1&langId=-10&catalogId=1&URL=ReLogonFormView';
}

//begin controller object	
sbController = {
	
	onROSB: function () {
		if (sbModelData.pasbInProgress) // if pasb is in progress, don't bother displaying information
		{
			return;	
		}
        if (sbModelData.rosbInProgress) // if rosb is in progress, don't bother displaying information
        {
			return;
        }
		if (sbModelData.rosbComplete) // contents are in hidden div, so display
		{
			$("span.SB_PopInContentHeaderAdded").css("display","none");
			return;	
		}
		sbModelData.rosbInProgress = true; // rosb call is going to be made
		
		//var testshoppingbaglinks = $(".SB_PopInTab a");
		//$(".SB_PopInTab a").click();
		
		// clear contents of SB_PopInContentWrapper
		$("div.SB_PopInContentWrapper").html("");
		
		clearTimeout(sbModelData.rosbTimeoutRef);
		sbModelData.rosbTimeoutRef = setTimeout("sbController.onRosbFaultResult();", sbConfig.miscobj.rosbTimeout);
		sbCmds.rosb.execute();
	},
	
	onATB: function () {
		if (sbModelData.pasbInProgress) // if pasb is in progress already, return
		{
			return;	
		}
		
		if(sbModelData.firstCall)
		{
			sbModelData.originalBuyValue = $("#buy").val();
			sbModelData.originalJSDisabledValue = $("#jsflag").val();
			sbModelData.firstCall = false;
		}
		
		sbModelData.pasbInProgress = true; 
		sbModelData.rosbInProgress = false; // this can be set to false so when the rosb call in progress returns, it knows not to do anything
		SBPopin.close();
		sbModelData.rosbComplete = false; // clear status of rosb as complete (so it will reload next time
		
		clearTimeout(sbModelData.rosbTimeoutRef);
		clearTimeout(sbModelData.pasbTimeoutRef);
		sbModelData.pasbTimeoutRef = setTimeout("sbController.onPasbFaultResult();", sbConfig.miscobj.pasbTimeout);
		sbCmds.pasb.execute();
	},
	
	refresh: function()
	{
		var serviceURL = sbConfig.servicesobj.pasbAddress;
		
		serviceURL += "?" + sbModelData.atbQuerystring;
	
		window.location = serviceURL;
		
	},
	
	onAjaxRosbResponseResult: function() {
		clearTimeout(sbModelData.rosbTimeoutRef);
		sbController.transferHTML("rosb"); // extract the xml from the response, put into the hidden div
		
		// TODO: extract some metric information from xml
		$("span.SB_PopInContentHeaderAdded").css("display","none");
		sbController.onReadyToDisplay();
		try {
		populateMetricsObject("rosb");
		} catch(err) {}
		var s_code = s_o_sc.t();		
	},
	
	onAjaxPasbResponseResult: function() {
		clearTimeout(sbModelData.pasbTimeoutRef);
		sbController.transferHTML("pasb"); // extract the xml from the response, put into the hidden div
		
		// TODO: extract other information from xml including number of items and some metric information 
		if (sbModelData.pasbError == false)
		{
			if (typeof qvData != 'undefined')
			{
				if (qvData.isQvOpen == 'true')
				{
					$("#quickview").dialog("close");
				}
			}
			var theform = $("form[name='data']");
			
			if (theform != undefined && theform.length > 0)
			{
				theform[0].reset();	// this will need to be changed
				
				if (typeof(pageControllerObject) != 'undefined' && typeof(pageControllerObject.resetForm) != 'undefined')
				{
					pageControllerObject.resetForm();
				}
								
				if (typeof(pageControllerObject) != 'undefined' && pageControllerObject != null &&
					typeof(pageControllerObject.menuForm) != 'undefined' && pageControllerObject.menuForm != null &&
					typeof(pageControllerObject.menuForm.availableMenus) != 'undefined' && pageControllerObject.menuForm.availableMenus != null)
				{
					for(var i = 0; i < pageControllerObject.menuForm.availableMenus.length; i++)
					{
						pageControllerObject.menuForm.focusedObject = pageControllerObject.menuForm["drop"+(i)];
						pageControllerObject.menuForm.onChangeMenu(pageControllerObject.menuForm.focusedObject);
					}
					
					
				}
			}
			
			// persisting a couple hidden input values (IE resets hidden inputs when form.reset is called)
			if (sbModelData.originalJSDisabledValue != null)
			{
			$("#jsflag").val(sbModelData.originalJSDisabledValue);
			}

			if (sbModelData.originalBuyValue != null)
			{
				$("#buy").val(sbModelData.originalBuyValue);
			}

			SBPopin.openPASB(); // Moved after form reset to avoid bleed through of attributes on collection ordering page
		}
		else if (sbModelData.pasbRefresh == false)
		{
			$(".Add_to_Shopping_Bag").css({"display":"inline"});
			$(".Inactive_Add_to_Shopping_Bag").css({"display":"none"});
		}
	},	
	
	// extract the xml from the response, put into the hidden div
	transferHTML: function(callType) {
		backupBrowserWrite = document.write;
		document.write = writeReplacement;
		returnedXML = sbModelData.receivedXML;
		var SB_PopIn = "div.SB_PopInContentWrapper";
		var theHTML = '';
		if (returnedXML == null)
		{
			if (callType == "pasb")
			{
				sbController.onPasbFaultResult();
			}
			else // call type is rosb
			{
				sbController.onRosbFaultResult();
			}				
			return;
		}
		var refreshNodes = returnedXML.getElementsByTagName('refresh');
		var componentErrorNodes = returnedXML.getElementsByTagName('badItem');	
		var errorNodes = returnedXML.getElementsByTagName('error');
		var pageErrorNodes = returnedXML.getElementsByTagName('pageerror');
		var hideShipMessageNodes = returnedXML.getElementsByTagName('hideshipmessage');
		$(".productNameTitle").css({"color":"#3E3F39"});	
		if (refreshNodes != null && refreshNodes.length != 0)
		{
			sbController.refresh(); // do full page submission (inventory changed since user loaded PP)
			sbModelData.pasbError = true;
			sbModelData.pasbRefresh = true;
		}
		else if (errorNodes != null && errorNodes.length > 0)
		{
			if (callType == "pasb")
			{
				sbController.onPasbFaultResult();
			}
			else // call type is rosb
			{
				sbController.onRosbFaultResult();
			}
		}
		else if (componentErrorNodes != null && componentErrorNodes.length > 0)
		{
			$(".pp_PasbErrorHTML").css({"display":"block"});
			var firstError = true;
			for (var i = 0; i < componentErrorNodes.length; i++)
			{
				var componentKey = componentErrorNodes[i];
				var component;
				if (componentKey.text) { // IE;
					component = componentKey.text;
				}
				else if (componentKey.textContent)
				{
					component = componentKey.textContent;	 
				}
				$("#productName_" + component).css({"color":"#FF0000"}); // this is for collection ordering page
				
				// the following if stmt is for APP
				if ( document.getElementById("productName1_" + component) ) 
				{	
					var productName1 = document.getElementById("productName1_" + component);
					var productName2 = document.getElementById("productName2_" + component);
					productName1.className = "alertRed";
					productName2.className = "alertRed";	
					
					if (firstError) {
						// if first error, set the orderItem to open status
						setOrderItemActive($("#orderItem_" + component));
						firstError = false;
					}
				}
			}
			
			if(typeof adjustToOrderColumnHeight == 'function')
			{
				adjustToOrderColumnHeight();
			}
			sbModelData.pasbError = true;
			
			//RETURN PAGE TO TOP ON OPEN
			window.scrollTo(0,0);
		}
		else if (pageErrorNodes != null && pageErrorNodes.length > 0)
		{
			var pageErrorNode = pageErrorNodes[0];
			errorHTML = sbController.findCData(pageErrorNode);
			$("#pp_ajaxPasbError").html(errorHTML);
			$(".pp_PasbErrorHTML").css({"display":"inline"});
			if(typeof adjustToOrderColumnHeight == 'function') 
			{
				adjustToOrderColumnHeight();
			}
			sbModelData.pasbError = true;
			if (hideShipMessageNodes != null && hideShipMessageNodes.length > 0)
			{
				if ( document.getElementById("pp_noAttrShippingInfo") ) 
				{	
			         var shipMsgElement = document.getElementById("pp_noAttrShippingInfo");
			         shipMsgElement.style.display = "none";	
				}
				
				// if backorder error message is being displayed (and shipping message being hidden, set buy to yes
				// so the user can click add to bag the next time and successfully add to bag.
				$("#buy").val("Y");
			}
		}
		else
		{
			var shoppingbagnodes = returnedXML.getElementsByTagName('shoppingbag');
			var shoppingbagnode = shoppingbagnodes[0];
			if (shoppingbagnode.getElementsByTagName('hypertext')[0].hasChildNodes()) // find HTML (within node named hypertext)
			{
				htmlnode = shoppingbagnode.getElementsByTagName('hypertext')[0]; // get the first one
				theHTML = sbController.findCData(htmlnode);
			}
			
			$(SB_PopIn).html(theHTML); // set popin container with HTML from cdata
			if (callType == "pasb")
			{
				$("#pp_ajaxPasbError").html("");
				$(".pp_PasbErrorHTML").css({"display":"none"});
				if(typeof adjustToOrderColumnHeight == 'function') 
				{
					adjustToOrderColumnHeight();
				}
				sbModelData.pasbError = false;
				if (sbModelData.originalBuyValue != null)
				{
					$("#buy").val(sbModelData.originalBuyValue);	
				}
			}
		}
		document.write = backupBrowserWrite;
	},
	
	findCData: function (htmlnode) {
		if (htmlnode == null || htmlnode.childNodes == undefined)
		{
			return null;	
		}
		
		for (var i = 0; i < htmlnode.childNodes.length; i++) // loop through children to find CDATA node
		{
			if (htmlnode.childNodes[i].nodeType == 4 ) // is it CDATA
			{
				return htmlnode.childNodes[i].nodeValue;	// extract HTML from CDATA
				
			}
		}
		
	},
	
	onReadyToDisplay: function() {		
		SBPopin.populate();
		
	},
	
	onRosbFaultResult: function() {
		// TODO:add fault message handling.
		
		sbModelData.rosbInProgress = false;
		sbModelData.rosbComplete = false;
		clearTimeout(sbModelData.rosbTimeoutRef);
		if (sbModelData.linkClicked)
		{
			window.location = sbModelData.shoppingBagLinkURL;
		}
		$("div.SB_PopInContentWrapper").html(sbConfig.miscobj.rosbErrorMessage);
		$("span.SB_PopInContentHeaderAdded").css("display","none");
		sbController.onReadyToDisplay();
	},
	
	onPasbFaultResult: function() {
		clearTimeout(sbModelData.pasbTimeoutRef);
		$("#pp_ajaxPasbError").html(sbConfig.miscobj.pasbErrorMessage);
		$(".pp_PasbErrorHTML").css({"display":"inline"});
		if(typeof adjustToOrderColumnHeight == 'function')
		{
			adjustToOrderColumnHeight();
		}
		
		$(".Add_to_Shopping_Bag").css({"display":"inline"});
		$(".Inactive_Add_to_Shopping_Bag").css({"display":"none"});
		
		document.body.style.cursor = 'auto';
		sbModelData.pasbError = true;
		
		// TLM May 2010 added if statement to realign scrollable div in QV
		// if error message is displayed at top. Also added else around
		// already existing scrollto. The scrollto is meant to send the user
		// to the top of the page if there is an error to see. In the case of
		// QV, the error will be displayed in the QV layer, which may not be
		// near the top of the page.
		if (typeof qvData != 'undefined' && qvData.isQvOpen == 'true')
		{
			setQVBehaviors();
		}
		else
		{
			//RETURN PAGE TO TOP ON OPEN
			window.scrollTo(0,0);
		}
	}
			
		
};

sbModelData = {

	/** Ajax call in progress */	
	pasbInProgress:false,
	rosbInProgress:false,
	rosbComplete:false,
	pasbComplete:false,
	pasbError:false,
	pasbRefresh:false,
	numItemsInCart:0,
	disableRollOver:false,
	linkClicked:false,
	shoppingBagLinkURL:'',
	pasbTimeoutRef:null,
	rosbTimeoutRef:null,
	originalBuyValue:null,
	originalJSDisabledValue:null,
	firstCall:true,
	receivedXML:null, // xml received from the most recent call
	/* 
		needs to be generated by javascript and set before call to add to bag (PASB call). The atbQuerystring will be
		appended to the other parameters, such as storeId or langId. The format will be
		"parameter1=value1&parameter2=value2" without a leading ampersand.
	*/
	atbQuerystring:'',
	
	setItemsLink: function()
	{
		if(document.cookie == null || document.cookie == "") {
			//$("li#globalShoppingBagData").remove();
			
			$("span.sbLinkData").empty();
			
			$("div.SB_PopInTabData").remove();
			$('img.sbImage').each(function(){this.src = imagePath + "shopping_bag_empty.gif"});
			sbModelData.numItemsInCart = 0;
		}
		else {
			var numItemsInCartCookie = strGetCookie("LLBOI");
			var numItemsInCart = 0;
			if( numItemsInCartCookie != null && numItemsInCartCookie > 0 ) { numItemsInCart = numItemsInCartCookie; }
			sbModelData.numItemsInCart = numItemsInCart;
			
			if ( numItemsInCart > 0)
			{
				$('img.sbImage').each(function(){this.src = imagePath + "bag_black.gif"});
				if((typeof(sbRolloverDisable) == "undefined") || ((typeof(sbRolloverDisable) != "undefined") && !sbRolloverDisable)) {
					$("li#globalCheckoutButton").css({"display":"inline"});
				}
			}
			var numItemText = sbConfig.miscobj.pluralItems;
			if( numItemsInCart == 1 ) { numItemText = sbConfig.miscobj.singularItem; }
			$('a.itemsLink').html(numItemsInCart+' '+numItemText);
			$("span.sbLinkData").html(numItemsInCart+' '+numItemText);
		}
	},
	
	setRosbResponse: function(xml) {
		
		this.receivedXML = xml;
		
		// notify the controller that the ajax request data has been stored in the model
		sbController.onAjaxRosbResponseResult();
	},
	
	setPasbResponse: function(xml) {
		
		this.receivedXML = xml;
		
		// notify the controller that the ajax request data has been stored in the model
		sbController.onAjaxPasbResponseResult();
	}
};
/*
var util={};
util.debug=function(msg) {
	var newMsg = document.createTextNode(msg);
	var newMsgDiv= document.createElement('div');
	newMsgDiv.appendChild(newMsg);
	document.getElementById("logNode").appendChild(newMsgDiv);
}
*/
String.prototype.trim = function () {
	return this.replace(/^\s+|\s+$/g,"");
}

function storeClick()
{
	clearTimeout(reallyOpen);
	sbModelData.disableRollOver = true;
	if (sbModelData.rosbInProgress)
	{
			sbModelData.linkClicked = true;
//			return false;
	}
//	return true;
}

function buttonClose()
{
	$("div.popInContainer").removeClass("overPopin");
	SBPopin.close();
	$("#hsearchinput").focus();
	return false;
}

function closeSBforQV()
{
	$("div.popInContainer").removeClass("overPopin");
	SBPopin.close();
	return false;
}

function writeReplacement(a)
{
        $('#recsTempContainer').html(a);

}

function recsDone()
{
	$('.r3Container').html($('#recsTempContainer').html());
}
