require(["dojo/_base/event","dojo/_base/lang","dojo/dom-class","dojo/dom-geometry","dojo/dom-style","dojo/has","dojo/on","dojo/query","dojo/_base/sniff","dojo/domReady!","dojo/NodeList-dom","dojo/NodeList-traverse"],function(b,c,n,d,h,o,k,m){var g=null;var e=null;var q=null;var f={};var p="";var j="departmentMenu_";var l=function(){if(g==null){g=k(document.documentElement,"mousedown",a);}};var i=function(){if(g!=null){g.remove();g=null;}};var a=function(s){var w=s.target;if(e!=null&&w!=document.documentElement){var x=true;var v=e.getAttribute("data-parent");while(w&&w!=document.documentElement){if(w==e||w==q||n.contains(w,"dijitPopup")||v==w.getAttribute("data-parent")){x=false;break;}w=w.parentNode;}if(w==null){var u=m("div",e);for(var t=0;t<u.length;t++){var r=d.position(u[t]);if(s.clientX>=r.x&&s.clientX<r.x+r.w&&s.clientY>=r.y&&s.clientY<r.y+r.h){x=false;break;}}}if(x){deactivate(e);}}};activate=function(u){var r=(u.id.slice(0,j.length)==j);if(this.ajaxRefresh=="true"&&r){setAjaxRefresh("");wc.render.updateContext("departmentSubMenuContext",{"targetId":u.id});if(typeof cX==="function"){setTimeout(function(){cX("");},1000);}return;}var s=u.getAttribute("data-parent");if(s&&f[s]){deactivate(f[s]);}if(s){activate(document.getElementById(s));}n.add(u,"active");m("a[data-activate='"+u.id+"']").addClass("selected");var t=m("a[data-toggle='"+u.id+"']");t.addClass("selected");if(s){f[s]=u;if(e==null){e=u;q=t.length>0?t[0]:null;l();}}};deactivate=function(s){if(f[s.id]){deactivate(f[s.id]);}n.remove(s,"active");m("a[data-activate='"+s.id+"']").removeClass("selected");m("a[data-toggle='"+s.id+"']").removeClass("selected");var r=s.getAttribute("data-parent");delete f[r];if(s==e){e=null;q=null;i();}};toggle=function(r){if(r!=null){if(n.contains(r,"active")){deactivate(r);}else{activate(r);}}};setUpEventActions=function(){k(document,"a[data-activate]:click",function(s){var r=this.getAttribute("data-activate");activate(document.getElementById(r));b.stop(s);});k(document,"a[data-deactivate]:click",function(s){var r=this.getAttribute("data-deactivate");deactivate(document.getElementById(r));b.stop(s);});k(document,"a[data-toggle]:click",function(s){var r=this.getAttribute("data-toggle");toggle(document.getElementById(r));b.stop(s);});k(document,"a[data-toggle]:keydown",function(t){if(t.keyCode==27){var s=this.getAttribute("data-toggle");deactivate(document.getElementById(s));b.stop(t);}else{if(t.keyCode==40){var s=this.getAttribute("data-toggle");var r=document.getElementById(s);activate(r);m('[class*="menuLink"]',r)[0].focus();b.stop(t);}}});if(o("ie")<10){m("input[placeholder]").forEach(function(r){var u=r.getAttribute("placeholder");if(u){var s=document.createElement("label");s.className="placeholder";s.innerHTML=u;r.parentNode.insertBefore(s,r);var t=function(){s.style.display=(r.value?"none":"block");};window.setTimeout(t,200);k(r,"blur, focus, keyup",t);k(s,"click",function(v){r.focus();});}});}};setUpEventActions();});function setWelcomeMessage(f){var g="G";var e="";var a=dojo.cookie("MATTEL_WELCOME_MSG");if(null!=a&&undefined!=a&&a.trim()!=""){e=a;g="R";console.log("setWelcomeMessageCookie("+g+","+a+")");}else{console.log("firstName cookie value not found: "+a);}var b=document.getElementsByClassName("nav-login");console.info("storeIndicator:"+f);if(null!=f&&undefined!=f&&f=="AG"){b=document.getElementsByClassName("nav-login-ag");}if(b!=null&&b!=undefined){if(g=="G"){if(f=="HW"){for(var d=0;d<b.length;d++){var c=document.createElement("img");c.setAttribute("src","/wcsstore/MattelSAS/images/colors/hw/sign_in.png");b[d].appendChild(c);}}else{if(f=="AG"){for(var d=0;d<b.length;d++){b[d].innerHTML="AG Rewards / Sign in";}}else{for(var d=0;d<b.length;d++){b[d].innerHTML="Sign In / Register";}}}}else{if(e!=null&&e.trim()!=""){for(var d=0;d<b.length;d++){if(null!=f&&undefined!=f&&f=="AG"){b[d].innerHTML="Hello, "+e+"<i class='fa fa-chevron-down'></i>";}else{b[d].innerHTML="Hello, "+e;}}}else{for(var d=0;d<b.length;d++){b[d].innerHTML="My Account";}}}}}HeaderJs={rlcRedirect:function(a){var b={};b["isForumRedirect"]="true";b["storeId"]=WCParamJS.storeId;b["sfIndicator"]=a;cursor_wait();wc.service.invoke("RLCForumRedirectUrl",b);}};if(typeof(MessageHelper)=="undefined"||!MessageHelper||!MessageHelper.topicNamespace){MessageHelper={messages:{},errors:new Array(),msgBox:null,msgBoxTimer:null,identifier:"",tooltip:null,focusElement:"",getCurrentYear:function(){return new Date().getFullYear();},getCurrentMonth:function(){return new Date().getMonth()+1;},getCurrentDay:function(){return new Date().getDate();},getRenderContextProperty:function(context,propertyName){console.debug("enter getRenderContextProperty with propertyName = "+propertyName);if(context==null){console.debug("context is null. Return null...");return null;}
var result=context.properties[propertyName]
console.debug("the found property value is: "+result);return result;},setMessage:function(key,msg){this.messages[key]=msg;},setFocusElement:function(element){this.focusElement=element;},showHideMessageArea:function(topOffset){cursor_clear();if(topOffset==null||topOffset==undefined){topOffset=0;}
var node=dojo.byId("MessageArea");var fadeInAnimArgsArray=new Array();fadeInAnimArgsArray["node"]=node;fadeInAnimArgsArray["duration"]=50;fadeInAnimArgsArray["delay"]=0;dojo.style(node,"opacity",0);if(dijit.byId("MessageArea_ACCE_Title")!=null){dijit.byId("MessageArea_ACCE_Title").style.display="block";}
dojo.style(node,"display","block");var fadeInAnim=dojo.fadeIn(fadeInAnimArgsArray);fadeInAnim.play();},hideMessageArea:function(){cursor_clear();var focusOnElement="";if(dojo.byId(this.focusElement)!=null){focusOnElement=dojo.byId(this.focusElement);}
var node=dojo.byId("MessageArea");var fadeOutAnimArgsArray=new Array();fadeOutAnimArgsArray["node"]=node;fadeOutAnimArgsArray["duration"]=500;fadeOutAnimArgsArray["onEnd"]=function(){dojo.style(node,"display","none");if(dijit.byId("MessageArea_ACCE_Title")!=null){dijit.byId("MessageArea_ACCE_Title").style.display="none"}
dojo.style(node,"opacity",100);if(dojo.byId(focusOnElement)!=null){focusOnElement.focus();}};dojo.fadeOut(fadeOutAnimArgsArray).play();dojo.byId('ErrorMessageText').innerHTML="";this.focusElement="";},displayErrorMessage:function(msg,topOffset,showType){if(msg!=null&&msg!='undefined'&&msg.indexOf("The user does not have the authority to run this command")!=-1){location.reload();return;}
$("html, body").animate({scrollTop:0},'slow',function(){MessageHelper.msgBox=dojo.byId("messageBoxDisplay");MessageHelper.msgBox.className="";MessageHelper.msgBox.innerHTML=msg;MessageHelper.msgBox.className="show error";clearTimeout(MessageHelper.msgBoxTimer);MessageHelper.msgBoxTimer=setTimeout(function(){MessageHelper.msgBox.className="";},10000);});},setMessageAreaStyle:function(styleId){dojo.byId("success_icon").style.display="none";dojo.byId("error_icon").style.display="none";if(dojo.byId(styleId)!=null){dojo.byId(styleId).style.display="inline";}},displayStatusMessage:function(msg,topOffset){$("html, body").animate({scrollTop:0},'slow',function(){MessageHelper.msgBox=dojo.byId("messageBoxDisplay");MessageHelper.msgBox.className="";MessageHelper.msgBox.innerHTML=msg;MessageHelper.msgBox.className="show success";clearTimeout(MessageHelper.msgBoxTimer);MessageHelper.msgBoxTimer=setTimeout(function(){MessageHelper.msgBox.className="";},10000);});},hideAndClearMessage:function(){dojo.byId('ErrorMessageText').innerHTML="";dojo.byId('MessageArea').style.display="none";},adjustCoordinates:function(topOffset){if(dojo.style("MessageArea","display")!="none"){var page=dojo.byId("page");var node=dojo.byId("MessageArea");if(page!=null&&node!=null){var coords=dojo.coords(page,true);var width=coords.w;if(dojo.isSafari){width=dojo.style('page','width');}
if(topOffset==null||topOffset==undefined){topOffset=0;}
dojo.style(node,{"width":width+20+"px","left":coords.x-10+"px","top":(coords.y+topOffset)+"px"});}}},formErrorHandle:function(serviceResponse,formName,success){var success=success||false;this.formErrorHandleClient(serviceResponse.errorMessageParam,serviceResponse.errorMessage,success);},resetErrors:function(){for(var id in MessageHelper.errors){MessageHelper.removeError(id);}
MessageHelper.errors=new Array();},removeError:function(id){$(MessageHelper.errors[id]["element"]).attr("aria-invalid","false").removeClass("ui-state-error").off("focus");$(MessageHelper.errors[id]["node"]).remove();delete MessageHelper.errors[id];MessageHelper.isScrolled=false;},formErrorHandleClient:function(id,errorMessage,success){var success=success||false;console.debug('formErrorHandleClient',id,errorMessage);if(id==null){console.debug("formErrorHandleClient: The id is null.");return;}
if(errorMessage==null){console.debug("formErrorHandleClient: The error message is null.");return;}
var element=dojo.byId(id);if(element){var node=document.createElement('p');var imgDirPath=getImageDirectoryPath();if(dojo.isIE<7)
{node.innerHTML=errorMessage+"<iframe id='errorMessageIFrame' scrolling='no' frameborder='0' src='"+imgDirPath+"images/empty.gif'></iframe>";}
else
{node.innerHTML=errorMessage;}
if($("#"+id+"_error").length==0){var error=new Object();error.element=element;error.node=node;MessageHelper.errors[id]=error;if(MessageHelper.errors[Object.keys(MessageHelper.errors)[0]].element.id==id){MessageHelper.scrollToErrMsg(MessageHelper.errors[Object.keys(MessageHelper.errors)[0]].element);}
if(success){$(node).attr("role","alert").attr("aria-atomic","true").attr("id",id+"_error").attr("class","error text-info small");}else{$(node).attr("role","alert").attr("aria-atomic","true").attr("id",id+"_error").attr("class","error text-danger small");}
if(element.type!=undefined&&(element.type=="checkbox"||element.type=="radio")){var spanElement=dojo.query(element).next()[0];var errorElement=spanElement==undefined?element:spanElement;$(element).addClass("ui-state-error").change(function(){MessageHelper.removeError(element.id)
$(element).unbind("change");}).blur();$(errorElement).after(node);}else{if(success){setTimeout(function(){MessageHelper.removeError(element.id);},155000);}else{$(element).addClass("ui-state-error").focus(function(){MessageHelper.removeError(element.id)}).blur();}
$(element).after(node);}}
if(typeof TealeafWCJS!="undefined"){TealeafWCJS.logClientValidationCustomEvent({fieldId:element.id,message:errorMessage});}}else{console.debug("formErrorHandleClient: The element is missing.");}},isScrolled:false,scrollToErrMsg:function(id){if(MessageHelper.isScrolled!=true){$('html, body').animate({scrollTop:$(id).offset().top},500);}
MessageHelper.isScrolled=true;},hideFormErrorHandle:function(){if(this.tooltip!=null){this.tooltip.destroyRecursive();this.tooltip=null;this.clearCurrentIdentifier();}},clearCurrentIdentifier:function(){this.identifier="";},emptyFunc:function(event){},containsDoubleByte:function(target){var str=new String(target);var oneByteMax=0x007F;for(var i=0;i<str.length;i++){chr=str.charCodeAt(i);if(chr>oneByteMax){return true;}}
return false;},isValidEmail:function(strEmail){if(this.containsDoubleByte(strEmail)){return false;}
if(strEmail.length==0){return false;}else if(strEmail.length<5){return false;}else{if(strEmail.indexOf(" ")>0){return false;}else{if(strEmail.indexOf("@")<1){return false;}else{if(strEmail.lastIndexOf(".")<(strEmail.indexOf("@")+2)){return false;}else{if(strEmail.lastIndexOf(".")>=strEmail.length-2){return false;}}}}}
return true;},isValidUTF8length:function(UTF16String,maxlength){if(this.utf8StringByteLength(UTF16String)>maxlength)return false;else return true;},utf8StringByteLength:function(UTF16String){if(UTF16String===null)return 0;var str=String(UTF16String);var oneByteMax=0x007F;var twoByteMax=0x07FF;var byteSize=str.length;for(i=0;i<str.length;i++){chr=str.charCodeAt(i);if(chr>oneByteMax)byteSize=byteSize+1;if(chr>twoByteMax)byteSize=byteSize+1;}
return byteSize;},IsNumeric:function(text,allowDot)
{if(allowDot)var ValidChars="0123456789.";else var ValidChars="0123456789";var IsNumber=true;var Char;for(i=0;i<text.length&&IsNumber==true;i++)
{Char=text.charAt(i);if(ValidChars.indexOf(Char)==-1)
{IsNumber=false;}}
return IsNumber;},IsValidPhone:function(text)
{var ValidChars="0123456789()-+ ";var IsValid=true;var Char;for(i=0;i<text.length&&IsValid==true;i++)
{Char=text.charAt(i);if(ValidChars.indexOf(Char)==-1)
{IsValid=false;}}
return IsValid;},showConfirmationDialog:function(topicName,message){require(["dijit/registry","dojo/dom","dojo/on","dojo/topic","dojo/_base/event"],function(registry,dom,on,topic){dom.byId("confirmationPopupMessage").innerHTML=message;var confirmationPopupWidget=registry.byId('confirmationPopup');confirmationPopupWidget._signalYes=on(dom.byId("confirmationPopupYES"),"click",function(e){e.preventDefault();if(confirmationPopupWidget._signalYes!==undefined&&confirmationPopupWidget._signalYes!==null){confirmationPopupWidget._signalYes.remove();}
if(confirmationPopupWidget._signalNo!==undefined&&confirmationPopupWidget._signalNo!==null){confirmationPopupWidget._signalNo.remove();}
confirmationPopupWidget.hide();topic.publish(topicName,{action:"YES"});}),confirmationPopupWidget._signalNo=on(dom.byId("confirmationPopupNO"),"click",function(e){e.preventDefault();if(confirmationPopupWidget._signalYes!==undefined&&confirmationPopupWidget._signalYes!==null){confirmationPopupWidget._signalYes.remove();}
if(confirmationPopupWidget._signalNo!==undefined&&confirmationPopupWidget._signalNo!==null){confirmationPopupWidget._signalNo.remove();}
confirmationPopupWidget.hide();topic.publish(topicName,{action:"NO"});})
confirmationPopupWidget.show();});},showErrorDialog:function(errorMessage,errorTitle){if(!errorTitle){errorTitle="Message";}
if(dojo.byId("errorDialogTitle"))
dojo.byId("errorDialogTitle").innerHTML=errorTitle;if(dojo.byId("errorDialogMessage")&&errorMessage)
dojo.byId("errorDialogMessage").innerHTML=errorMessage;dijit.byId("ErrorMessageDialog").show();},parseHtml:function(msg){var tempElem=document.createElement('textarea');tempElem.innerHTML=msg;return tempElem.value;}}}
CommonContextsJS={langId:"-1",storeId:"",catalogId:"",setCommonParameters:function(langId,storeId,catalogId){this.langId=langId;this.storeId=storeId;this.catalogId=catalogId;},setContextProperty:function(contextId,property,value){wc.render.getContextById(contextId).properties[property]=value;}}
dojo.addOnLoad(function(){wc.render.declareContext("multipleShipmentDetailsContext",{shipmentDetailsArea:"update"},""),wc.render.declareContext("singleShipmentShipChargeContext",null,""),wc.render.declareContext("multipleShipmentShipChargeContext",null,""),wc.render.declareContext("CreateShoppingListContext",{"listType":"","catalogId":""},""),wc.render.declareContext("myAccountRewardsAreaContext",null,""),wc.render.declareContext("traditionalShipmentDetailsContext",{shipmentDetailsArea:"update"},""),wc.render.declareContext("currentOrder_Context",{fromPage:""},""),wc.render.declareContext("promoCode_Context",null,""),wc.render.declareContext("rewardCode_Context",null,""),wc.render.declareContext("editShippingAddressContext",{shippingAddress:"0",addressType:"ShippingAndBilling"},"","Main"),wc.render.declareContext("billingAddressDropDownBoxContext",{billingAddress1:"0",billingAddress2:"0",billingAddress3:"0",billingURL1:"",billingURL2:"",billingURL3:"",areaNumber:'0',payment1:"",payment2:"",payment3:"",paymentTCId1:"",paymentTCId2:"",paymentTCId3:""},""),wc.render.declareContext("contextForMainAndAddressDiv",{showArea:"0",hideArea:"0"},""),wc.render.declareContext("shippingAddressDropDownBoxContext",null,""),wc.render.declareContext("CategoryDisplay_Context",{pageView:"",beginIndex:""},""),wc.render.declareContext("SubCategoryDisplay_Context",null,""),wc.render.declareContext("ShopCartPaginationDisplay_Context",{},""),wc.render.declareContext("PendingOrderPaginationDisplay_Context",{},""),wc.render.declareContext("PendingOrderDisplay_Context",{beginIndex:"0"},""),wc.render.declareContext("OrderItemPaginationDisplay_Context",{beginIndex:"0"},""),wc.render.declareContext("OrderDetailPaginationDisplay_Context",{beginIndex:"0"},""),wc.render.declareContext("MSOrderItemPaginationDisplay_Context",{beginIndex:"0"},""),wc.render.declareContext("CouponDisplay_Context",null,""),wc.render.declareContext("PromotionFreeGifts_Context",null,""),wc.render.declareContext("ListOrdersDisplay_Context",{startNumber:"0"},""),wc.render.declareContext("ScheduledOrdersStatusDisplay_Context",{beginIndex:"0",selectedTab:"Scheduled"},""),wc.render.declareContext("ProcessedOrdersStatusDisplay_Context",{beginIndex:"0",selectedTab:"PreviouslyProcessed"},""),wc.render.declareContext("WaitingForApprovalOrdersStatusDisplay_Context",{beginIndex:"0",selectedTab:"WaitingForApproval"},""),wc.render.declareContext("BrowsingHistoryContext",{status:"init"},""),wc.render.declareContext("BrowsingHistoryDisplay_Context",{currentPage:"0",pageView:""},""),wc.render.declareContext("CategorySubscriptionContext",null,""),wc.render.declareContext("RecurringOrderDisplay_Context",{beginIndex:"0"},""),wc.render.declareContext("SubscriptionDisplay_Context",{beginIndex:"0"},""),wc.render.declareContext("RecentRecurringOrderDisplay_Context",{beginIndex:"0",isMyAccountMainPage:"true"},""),wc.render.declareContext("RecentSubscriptionDisplay_Context",{beginIndex:"0",isMyAccountMainPage:"true"},""),wc.render.declareContext("RecurringOrderChildOrdersDisplay_Context",{beginIndex:"0",orderId:""},""),wc.render.declareContext("SubscriptionChildOrdersDisplay_Context",{beginIndex:"0",orderItemId:"",subscriptionName:""},""),wc.render.declareContext("QuickInfoContext",null,""),wc.render.declareContext("AddOnServicesContext",null,""),wc.render.declareContext("DiscountDetailsContext",null,""),wc.render.declareContext("QuickInfoDiscountDetailsContext",null,""),wc.render.declareContext("DoubleContentAreaESpot_Context",{emsName:""},""),wc.render.declareContext("ScrollableESpot_Context",{emsName:""},""),wc.render.declareContext("TopCategoriesESpot_Context",{emsName:""},""),wc.render.declareContext("CategoryFeaturedProductsESpot_Context",{emsName:""},""),wc.render.declareContext("HomeHeroESpot_Context",{emsName:""},""),wc.render.declareContext("HomeLeftESpot_Context",{emsName:""},""),wc.render.declareContext("HomeRightTopESpot_Context",{emsName:""},""),wc.render.declareContext("HomeRightBottomESpot_Context",{emsName:""},""),wc.render.declareContext("TallDoubleContentAreaESpot_Context",{emsName:""},""),wc.render.declareContext("TopCategoryHeroESpot_Context",{emsName:""},""),wc.render.declareContext("TopCategoryTallDoubleESpot_Context",{emsName:""},""),wc.render.declareContext("AttachmentPagination_Context",{beginIndex:"0"},""),wc.render.declareContext("MattelStandardPayPalContext",{piId:"",orderId:""},"");wc.render.declareContext("AjaxPhoneEmailUpdateContext",{action:""},"");wc.render.declareContext("MattelOrderGiftDetailsContext",{piId:"",orderId:""},""),wc.render.declareContext("MattelStandardAmazonContext",{piId:"",orderId:""},""),wc.render.declareContext("MattelRecentlyViewedItemsContext",{emsName:"",widgetSuffix:""},""),wc.render.declareContext("paymentContext",{payment1:"",payment2:"",payment3:"",currentPaymentArea:"1",billingMode1:"none",billingMode2:"none",billingMode3:"none",currentTotal:"0",creditCardId:"-1"},"");wc.render.declareContext("billingAddressDisplayAreaContext",{addressId:"",count:"1",fromPage:"BillingInfo",paymentType:""},""),wc.render.declareContext("billingAddressEditAreaContext",{billingAddress:"0",addressType:"Billing",pageName:"billingPage",formId:"PaymentCreateBillingForm"},"","Main"),wc.render.declareContext("MattelGiftCartPaginationDisplay_Context",{},""),wc.render.declareContext("clubSearchNavigationContext",null,""),wc.render.declareContext("HaveItWantItWishlistDisplay_Context",{url:""},"");});CommonControllersDeclarationJS={langId:"-1",storeId:"",catalogId:"",ajaxCheckOut:true,setCommonParameters:function(langId,storeId,catalogId){this.langId=langId;this.storeId=storeId;this.catalogId=catalogId;},setControllerURL:function(controllerId,url){wc.render.getRefreshControllerById(controllerId).url=url;}}
dojo.addOnLoad(function(){wc.render.declareRefreshController({id:"CategoryDisplay_Controller",renderContext:wc.render.getContextById("CategoryDisplay_Context"),url:"",formId:"",renderContextChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;categoryDisplayJS.contextChanged=true;widget.refresh(renderContext.properties);},postRefreshHandler:function(widget){var controller=this;var renderContext=this.renderContext;if(categoryDisplayJS.contextChanged&&(!categoryDisplayJS.isHistory)){var identifier="&identifier="+(new Date()).getTime();var historyObject=new categoryDisplayJS.HistoryTracker('CategoryDisplay_Widget',controller.url+identifier);dojo.back.addToHistory(historyObject);categoryDisplayJS.contextChanged=false;categoryDisplayJS.isHistory=false;}
cursor_clear();try{if(typeof(ceadojo)!="undefined"){ceadojo.publish("/wc/collaboration/CategoryDisplayRefreshed",[]);}}catch(err){console.log(err);}}}),wc.render.declareRefreshController({id:"SubCategoryDisplay_Controller",renderContext:wc.render.getContextById("SubCategoryDisplay_Context"),url:"",formId:"",renderContextChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;categoryDisplayJS.contextChanged=true;widget.refresh(renderContext.properties);},postRefreshHandler:function(widget){var controller=this;var renderContext=this.renderContext;if(categoryDisplayJS.contextChanged&&(!categoryDisplayJS.isHistory)){var identifier="&identifier="+(new Date()).getTime();var historyObject=new categoryDisplayJS.HistoryTracker('SubCategoryDisplay_Widget',controller.url+identifier);dojo.back.addToHistory(historyObject);categoryDisplayJS.contextChanged=false;categoryDisplayJS.isHistory=false;}
cursor_clear();}}),wc.render.declareRefreshController({id:"ShopCartDisplayController",renderContext:wc.render.getContextById("ShopCartPaginationDisplay_Context"),url:"",formId:"",modelChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;if(message.actionId in order_updated){widget.refresh(renderContext.properties);submitRequest();cursor_wait();}},postRefreshHandler:function(widget){resetRequest();var controller=this;var renderContext=this.renderContext;if(typeof(savedOrdersJS)!=null&&typeof(savedOrdersJS)!='undefined')
{savedOrdersJS.isCurrentOrderPage(true);}
var controller=this;if(document.getElementById("discountDetailsSection")!=null){document.getElementById("discountDetailsSection").style.display="block";}
if(document.getElementById("appliedPromotionCodes")!=null){document.getElementById("appliedPromotionCodes").style.display="block";}
if(!CheckoutHelperJS.isAjaxCheckOut()){CheckoutHelperJS.setFieldDirtyFlag(false);CheckoutHelperJS.initDojoEventListenerShoppingCartPage();}
var orderId=renderContext.properties["orderId"];if(document.getElementById("currentOrderId")){orderId=document.getElementById("currentOrderId").value;}
ShipmodeSelectionExtJS.displaySavedShipmentTypeForOrder(orderId);if(document.getElementById("OrderFirstItemId"))
{ShipmodeSelectionExtJS.orderItemId=document.getElementById("OrderFirstItemId").value;}
dojo.query('div[id^="shoppingListScript_"]').forEach(function(node,index,nodelist){dojo.eval(node.innerHTML);});dojo.query('#ShopCartPagingDisplay input[id^="orderItem_"]').forEach(function(orderItem){try{dojo.eval(dojo.byId('addToRequisitionListScript_'+orderItem.value).innerHTML);dojo.eval('addReqListsJS'+orderItem.value+'.setCatEntryId("'+dojo.byId('catalogId_'+(orderItem.id.substring(orderItem.id.indexOf('_')+1))).value+'");');}catch(e){console.log("ShopCartDisplayController-addToRequisitionListScript not found");}});if($("#checkForGuarantee").val()=='true'){$("#guaranteeEspot").show();}else{$("#guaranteeEspot").hide();}
cursor_clear();}}),wc.render.declareRefreshController({id:"ShopCartPaginationDisplayController",renderContext:wc.render.getContextById("ShopCartPaginationDisplay_Context"),url:"",formId:"",renderContextChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;if(controller.testForChangedRC(["beginIndex"])){widget.refresh(renderContext.properties);}},postRefreshHandler:function(widget){var controller=this;var renderContext=this.renderContext;cursor_clear();if(!CheckoutHelperJS.isAjaxCheckOut()){CheckoutHelperJS.setFieldDirtyFlag(false);CheckoutHelperJS.initDojoEventListenerShoppingCartPage();}
var orderId=renderContext.properties["orderId"];if(document.getElementById("currentOrderId")){orderId=document.getElementById("currentOrderId").value;}
ShipmodeSelectionExtJS.displaySavedShipmentTypeForOrder(orderId);dojo.query('div[id^="shoppingListScript_"]').forEach(function(node,index,nodelist){dojo.eval(node.innerHTML);});dojo.query('input[id^="orderItem_"]').forEach(function(orderItem){dojo.eval(dojo.byId('addToRequisitionListScript_'+orderItem.value).innerHTML);dojo.eval('addReqListsJS'+orderItem.value+'.setCatEntryId("'+dojo.byId('catalogId_'+(orderItem.id.substring(orderItem.id.indexOf('_')+1))).value+'");');});}}),wc.render.declareRefreshController({id:"PendingOrderPaginationDisplayController",renderContext:wc.render.getContextById("PendingOrderPaginationDisplay_Context"),url:"",formId:"",renderContextChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;if(controller.testForChangedRC(["beginIndex"])){widget.refresh(renderContext.properties);}},postRefreshHandler:function(widget){var controller=this;var renderContext=this.renderContext;cursor_clear();}}),wc.render.declareRefreshController({id:"OrderItemPaginationDisplayController",renderContext:wc.render.getContextById("OrderItemPaginationDisplay_Context"),url:"",formId:"",renderContextChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;if(controller.testForChangedRC(["beginIndex"])){widget.refresh(renderContext.properties);}else if(renderContext.properties["operation"]=='OrderReviewRefresh'){widget.refresh(renderContext.properties);}},modelChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;if(message.actionId=='AjaxUpdateOrderItem'||message.actionId=='AjaxAddOrderItem'||message.actionId=='AjaxDeleteOrderItem'){widget.refresh(renderContext.properties);cursor_wait();}},postRefreshHandler:function(widget){var controller=this;var renderContext=this.renderContext;cursor_clear();if(renderContext.properties["analytics"]=='true'){dojo.topic.publish("order_contents_ProductRec",dojo.byId("orderPartNumbers").value);}}}),wc.render.declareRefreshController({id:"SSFSOrderItemPaginationDisplayController",renderContext:wc.render.getContextById("OrderItemPaginationDisplay_Context"),url:"",formId:"",renderContextChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;if(controller.testForChangedRC(["beginIndex"])){widget.refresh(renderContext.properties);}},postRefreshHandler:function(widget){var controller=this;var renderContext=this.renderContext;var orderStr=document.getElementById("jsonOrderStr").innerHTML;var beginIndex=this.renderContext.properties['beginIndex'];var pageSize=this.renderContext.properties['pageSize'];sterlingIntegrationJS.populateOrderLineInfoForSingleShipment(orderStr,beginIndex,pageSize);cursor_clear();}}),wc.render.declareRefreshController({id:"MSOrderItemPaginationDisplayController",renderContext:wc.render.getContextById("MSOrderItemPaginationDisplay_Context"),url:"",formId:"",renderContextChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;if(controller.testForChangedRC(["beginIndex"])){widget.refresh(renderContext.properties);}},postRefreshHandler:function(widget){var controller=this;var renderContext=this.renderContext;cursor_clear();if(renderContext.properties["analytics"]=='true'){dojo.topic.publish("order_contents_ProductRec",dojo.byId("orderPartNumbers").value);}}}),wc.render.declareRefreshController({id:"SSFSMSOrderItemPaginationDisplayController",renderContext:wc.render.getContextById("MSOrderItemPaginationDisplay_Context"),url:"",formId:"",renderContextChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;if(controller.testForChangedRC(["beginIndex"])){widget.refresh(renderContext.properties);}},postRefreshHandler:function(widget){var controller=this;var renderContext=this.renderContext;var orderStr=document.getElementById("jsonOrderStr").innerHTML;var beginIndex=this.renderContext.properties['beginIndex'];var pageSize=this.renderContext.properties['pageSize'];sterlingIntegrationJS.populateOrderLineInfoForMultipleShipment(orderStr,beginIndex,pageSize);cursor_clear();}}),wc.render.declareRefreshController({id:"CouponDisplay_Controller",renderContext:wc.render.getContextById("CouponDisplay_Context"),url:"",formId:"",modelChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;if(message.actionId=='AjaxCouponsAddRemove'||message.actionId=='AjaxWalletItemProcessServiceDelete'){widget.refresh(renderContext.properties);}}}),wc.render.declareRefreshController({id:"PromotionFreeGifts_Controller",renderContext:wc.render.getContextById("PromotionFreeGifts_Context"),url:"",formId:"",modelChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;},renderContextChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;widget.refresh(renderContext.properties);},postRefreshHandler:function(widget){var controller=this;var renderContext=this.renderContext;cursor_clear();PromotionChoiceOfFreeGiftsJS.showFreeGiftsDialog();}}),wc.render.declareRefreshController({id:"ListOrdersDisplay_Controller",renderContext:wc.render.getContextById("ListOrdersDisplay_Context"),url:"",formId:"",modelChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;if(message.actionId in listorders_changed){if((message.actionId=='AjaxOrderCreate'||message.actionId=='AjaxSingleOrderCalculate')&&this.renderContext.properties["startNumber"]!=0)
{wc.render.updateContext("ListOrdersDisplay_Context",{'startNumber':0});}
else
{widget.refresh(renderContext.properties);}}},renderContextChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;if(controller.testForChangedRC(["startNumber"])){widget.refresh(renderContext.properties);}},postRefreshHandler:function(widget){var controller=this;var renderContext=this.renderContext;if(savedOrdersJS.updateCurrentOrder)
{savedOrdersJS.initializeCurrentOrder();savedOrdersJS.updateCurrentOrder=false;}
savedOrdersJS.updateToolbar();savedOrdersJS.checkAllIfNeeded();}}),wc.render.declareRefreshController({id:"PendingOrderDisplayController",renderContext:wc.render.getContextById("PendingOrderPaginationDisplay_Context"),url:"",formId:"",modelChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;if(message.actionId in order_updated){this.currentDesc=document.getElementById('OrderDescription_input').value;widget.refresh(renderContext.properties);}},postRefreshHandler:function(widget){var controller=this;cursor_clear();if(this.currentDesc!=document.getElementById('OldOrderDescription').value)
{var inputElement=document.getElementById('OrderDescription_input');if(inputElement!=null&&inputElement!='undefined')
{inputElement.value=this.currentDesc;dojo.removeClass(inputElement,'savedOrderDetailsInputBorder');dojo.addClass(inputElement,'savedOrderDetailsInputBorderWarning');}}}}),wc.render.declareRefreshController({id:"BrowsingHistoryController",renderContext:wc.render.getContextById("BrowsingHistoryContext"),url:"",formId:"",renderContextChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;if(controller.testForChangedRC(["status"])){widget.refresh(renderContext.properties);}},postRefreshHandler:function(widget){if(!document.getElementById('WC_ScrollingProductsESpot_EmptyImgContainer_BrowsingHistory')){document.getElementById('WC_LeftSidebarDisplay_div_5').style.display='block';}}}),wc.render.declareRefreshController({id:"BrowsingHistoryDisplay_Controller",renderContext:wc.render.getContextById("BrowsingHistoryDisplay_Context"),url:"",formId:"",renderContextChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;if(controller.testForChangedRC(["currentPage"])||controller.testForChangedRC(["pageView"])){widget.refresh(renderContext.properties);}},postRefreshHandler:function(widget){cursor_clear();}}),wc.render.declareRefreshController({id:"CategorySubscriptionController",renderContext:wc.render.getContextById("CategorySubscriptionContext"),url:"",formId:"",modelChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;if(message.actionId=="AjaxCategorySubscribe"){widget.refresh(renderContext.properties);}},postRefreshHandler:function(widget){cursor_clear();if(dojo.byId("CategorySubscriptionImage")==null){dojo.animateProperty({node:dojo.byId("CategorySubscriptionLink"),duration:1500,properties:{backgroundColor:{start:"yellow",end:dojo.style("CategorySubscriptionLink","backgroundColor")}}}).play();}}}),wc.render.declareRefreshController({id:"RecurringOrderDisplayController",renderContext:wc.render.getContextById("RecurringOrderDisplay_Context"),url:"",formId:"",modelChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;if(message.actionId=="AjaxCancelSubscription"){controller.url=wc.render.getRefreshControllerById("RecurringOrderDisplayController").url;widget.refresh(renderContext.properties);}},renderContextChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;if(controller.testForChangedRC(["beginIndex"])){widget.refresh(renderContext.properties);}},postRefreshHandler:function(widget){var controller=this;var renderContext=this.renderContext;cursor_clear();}}),wc.render.declareRefreshController({id:"SubscriptionDisplayController",renderContext:wc.render.getContextById("SubscriptionDisplay_Context"),url:"",formId:"",modelChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;if(message.actionId=="AjaxCancelSubscription"){controller.url=wc.render.getRefreshControllerById("SubscriptionDisplayController").url;widget.refresh(renderContext.properties);}},renderContextChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;if(controller.testForChangedRC(["beginIndex"])){widget.refresh(renderContext.properties);}},postRefreshHandler:function(widget){var controller=this;var renderContext=this.renderContext;cursor_clear();}}),wc.render.declareRefreshController({id:"RecentRecurringOrderDisplayController",renderContext:wc.render.getContextById("RecentRecurringOrderDisplay_Context"),url:"",formId:"",modelChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;if(message.actionId=="AjaxCancelSubscription"){controller.url=wc.render.getRefreshControllerById("RecurringOrderDisplayController").url;widget.refresh(renderContext.properties);}},postRefreshHandler:function(widget){var controller=this;var renderContext=this.renderContext;cursor_clear();}}),wc.render.declareRefreshController({id:"RecentSubscriptionDisplayController",renderContext:wc.render.getContextById("RecentSubscriptionDisplay_Context"),url:"",formId:"",modelChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;if(message.actionId=="AjaxCancelSubscription"){controller.url=wc.render.getRefreshControllerById("SubscriptionDisplayController").url;widget.refresh(renderContext.properties);}},postRefreshHandler:function(widget){var controller=this;var renderContext=this.renderContext;cursor_clear();}}),wc.render.declareRefreshController({id:"RecurringOrderChildOrdersDisplayController",renderContext:wc.render.getContextById("RecurringOrderChildOrdersDisplay_Context"),url:"",formId:"",renderContextChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;if(controller.testForChangedRC(["beginIndex"])){widget.refresh(renderContext.properties);}},postRefreshHandler:function(widget){var controller=this;var renderContext=this.renderContext;cursor_clear();}}),wc.render.declareRefreshController({id:"SubscriptionChildOrdersDisplayController",renderContext:wc.render.getContextById("SubscriptionChildOrdersDisplay_Context"),url:"",formId:"",renderContextChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;if(controller.testForChangedRC(["beginIndex"])){widget.refresh(renderContext.properties);}},postRefreshHandler:function(widget){var controller=this;var renderContext=this.renderContext;cursor_clear();}}),wc.render.declareRefreshController({id:"AddOnServicesController",renderContext:wc.render.getContextById("AddOnServicesContext"),url:"",formId:"",renderContextChangedHandler:function(message,widget){widget.refresh(this.renderContext.properties);},postRefreshHandler:function(widget){var controller=this;var renderContext=this.renderContext;var AddOnServicesFormId=document.getElementById('AddOnServices');if(AddOnServicesFormId){AddOnServicesFormId.scrollIntoView();}
cursor_clear();}}),wc.render.declareRefreshController({id:"QuickInfoDetailsController",renderContext:wc.render.getContextById("QuickInfoContext"),url:"",formId:"",quickInfoEvenSubscribed:false,renderContextChangedHandler:function(message,widget){widget.refreshGet(this.renderContext.properties);},postRefreshHandler:function(widget){if(dojo.byId("QuickInfostoreParams")){var storeParams=dojo.byId("QuickInfostoreParams").value;if(dojo.byId("catEntryParamsForJS")){var catEntryParams=dojo.byId("catEntryParamsForJS").value;}
var shoppingListNames=dojo.byId("QuickInfoshoppingListNames").value;shoppingListJSQuickInfo=new ShoppingListJS(dojo.fromJson(storeParams),dojo.fromJson(catEntryParams),dojo.fromJson(shoppingListNames),"shoppingListJSQuickInfo");if(!this.quickInfoEvenSubscribed){this.quickInfoEvenSubscribed=true;dojo.topic.subscribe("DefiningAttributes_Resolved",function(catEntryId,productId){shoppingListJSQuickInfo.setItemId(catEntryId,productId);});dojo.topic.subscribe("QuickInfo_attributesChanged",function(catEntryAttributes){shoppingListJSQuickInfo.setCatEntryAttributes(catEntryAttributes);});dojo.topic.subscribe("Quantity_Changed",function(catEntryQuantityObject){shoppingListJSQuickInfo.setCatEntryQuantity(catEntryQuantityObject);});dojo.topic.subscribe("ShoppingList_Changed",function(serviceResponse){shoppingListJSQuickInfo.updateShoppingListAndAddItem(serviceResponse);});dojo.topic.subscribe("ShoppingListItem_Added",function(){shoppingListJSQuickInfo.deleteItemFromCart();});dojo.connect(dojo.byId("QuickInfoaddToShoppingListDropdown"),"onmouseover",function(){shoppingListJSQuickInfo.mouseOnArrow=true;});dojo.connect(dojo.byId("QuickInfoShoppingList_0"),"onmouseover",function(){shoppingListJSQuickInfo.exceptionFlag=true;document.getElementById('QuickInfoShoppingListLink_0').focus();});}
var catEntryId=dojo.fromJson(catEntryParams).id;if(null!=catEntryId&&''!=catEntryId){wc.render.updateContext('QuickInfoDiscountDetailsContext',{productId:dojo.fromJson(catEntryParams).id});}}
if(dojo.byId("catEntryParamsForJS")){QuickInfoJS.catEntryParams=dojo.fromJson(dojo.byId('catEntryParamsForJS').value);}
var quickInfoPopup=dijit.byId("quickInfoPopup");if(quickInfoPopup!=null){quickInfoPopup.closeButtonNode.style.display='none';closeAllDialogs();if(QuickInfoJS.itemId==''){QuickInfoJS.setCatEntryQuantity(1);QuickInfoJS.parseQuickViewAttributes();}else{QuickInfoJS.selectCurrentAttributes();}
quickInfoPopup.show();$("#quickInfoMainImage").load(function(){quickInfoPopup.resize();quickInfoPopup.resize();quickInfoPopup.resize();quickInfoPopup.resize();quickInfoPopup.resize();quickInfoPopup.resize();quickInfoPopup.resize();quickInfoPopup.resize();quickInfoPopup.resize();quickInfoPopup.resize();quickInfoPopup.resize();quickInfoPopup.resize();$("body").scrollTop(0);});if(typeof TealeafWCJS!="undefined"){TealeafWCJS.rebind("quickInfoPopup");}
var reviewCount=parseInt($('#quickInfoRefreshArea .reviews abbr').text().replace(')','').replace('(',''));$('#quickInfoRefreshArea .reviews abbr').remove();QuickInfoJS.parseInventoryScript();if(reviewCount>0){$('#quickInfoRefreshArea .reviews').append('<a href="'+widget.controller.renderContext.properties.href+'#BVMattel">Read reviews ('+reviewCount+')</a>|');}
$('#quickInfoRefreshArea .reviews').append('<a href="'+widget.controller.renderContext.properties.href+'#BVOSWriteReview">Write a review</a>');}else{console.debug("quickInfoPopup does not exist");}
cursor_clear();}}),wc.render.declareRefreshController({id:"DiscountDetailsController",renderContext:wc.render.getContextById("DiscountDetailsContext"),url:"DiscountDetailsView",formId:"",renderContextChangedHandler:function(message,widget){widget.refresh(this.renderContext.properties);},postRefreshHandler:function(widget){cursor_clear();}}),wc.render.declareRefreshController({id:"QuickInfoDiscountDetailsController",renderContext:wc.render.getContextById("QuickInfoDiscountDetailsContext"),url:"DiscountDetailsView",formId:"",renderContextChangedHandler:function(message,widget){widget.refresh(this.renderContext.properties);},postRefreshHandler:function(widget){cursor_clear();}}),wc.render.declareRefreshController({id:"DoubleContentAreaESpot_Controller",renderContext:wc.render.getContextById("DoubleContentAreaESpot_Context"),url:"",formId:"",renderContextChangedHandler:function(message,widget){if(this.testForChangedRC(["emsName"])){widget.refresh(this.renderContext.properties);}},postRefreshHandler:function(widget){cursor_clear();}}),wc.render.declareRefreshController({id:"ScrollableESpot_Controller",renderContext:wc.render.getContextById("ScrollableESpot_Context"),url:"",formId:"",renderContextChangedHandler:function(message,widget){if(this.testForChangedRC(["emsName"])){widget.refresh(this.renderContext.properties);}},postRefreshHandler:function(widget){cursor_clear();}}),wc.render.declareRefreshController({id:"TopCategoriesESpot_Controller",renderContext:wc.render.getContextById("TopCategoriesESpot_Context"),url:"",formId:"",renderContextChangedHandler:function(message,widget){if(this.testForChangedRC(["emsName"])){widget.refresh(this.renderContext.properties);}},postRefreshHandler:function(widget){cursor_clear();}}),wc.render.declareRefreshController({id:"CategoryFeaturedProductsESpot_Controller",renderContext:wc.render.getContextById("CategoryFeaturedProductsESpot_Context"),url:"",formId:"",renderContextChangedHandler:function(message,widget){if(this.testForChangedRC(["emsName"])){widget.refresh(this.renderContext.properties);}},postRefreshHandler:function(widget){cursor_clear();}}),wc.render.declareRefreshController({id:"HomeHeroESpot_Controller",renderContext:wc.render.getContextById("HomeHeroESpot_Context"),url:"",formId:"",renderContextChangedHandler:function(message,widget){if(this.testForChangedRC(["emsName"])){widget.refresh(this.renderContext.properties);}},postRefreshHandler:function(widget){cursor_clear();}}),wc.render.declareRefreshController({id:"HomeLeftESpot_Controller",renderContext:wc.render.getContextById("HomeLeftESpot_Context"),url:"",formId:"",renderContextChangedHandler:function(message,widget){if(this.testForChangedRC(["emsName"])){widget.refresh(this.renderContext.properties);}},postRefreshHandler:function(widget){cursor_clear();}}),wc.render.declareRefreshController({id:"HomeRightTopESpot_Controller",renderContext:wc.render.getContextById("HomeRightTopESpot_Context"),url:"",formId:"",renderContextChangedHandler:function(message,widget){if(this.testForChangedRC(["emsName"])){widget.refresh(this.renderContext.properties);}},postRefreshHandler:function(widget){cursor_clear();}}),wc.render.declareRefreshController({id:"HomeRightBottomESpot_Controller",renderContext:wc.render.getContextById("HomeRightBottomESpot_Context"),url:"",formId:"",renderContextChangedHandler:function(message,widget){if(this.testForChangedRC(["emsName"])){widget.refresh(this.renderContext.properties);}},postRefreshHandler:function(widget){cursor_clear();}}),wc.render.declareRefreshController({id:"TallDoubleContentAreaESpot_Controller",renderContext:wc.render.getContextById("TallDoubleContentAreaESpot_Context"),url:"",formId:"",renderContextChangedHandler:function(message,widget){if(this.testForChangedRC(["emsName"])){widget.refresh(this.renderContext.properties);}},postRefreshHandler:function(widget){cursor_clear();}}),wc.render.declareRefreshController({id:"TopCategoryHeroESpot_Controller",renderContext:wc.render.getContextById("TopCategoryHeroESpot_Context"),url:"",formId:"",renderContextChangedHandler:function(message,widget){if(this.testForChangedRC(["emsName"])){widget.refresh(this.renderContext.properties);}},postRefreshHandler:function(widget){cursor_clear();}}),wc.render.declareRefreshController({id:"TopCategoryTallDoubleESpot_Controller",renderContext:wc.render.getContextById("TopCategoryTallDoubleESpot_Context"),url:"",formId:"",renderContextChangedHandler:function(message,widget){if(this.testForChangedRC(["emsName"])){widget.refresh(this.renderContext.properties);}},postRefreshHandler:function(widget){cursor_clear();}}),wc.render.declareRefreshController({id:"AttachmentPagination_Controller",renderContext:wc.render.getContextById("AttachmentPagination_Context"),url:"",formId:"",renderContextChangedHandler:function(message,widget){if(this.testForChangedRC(["beginIndex"])){widget.refresh(this.renderContext.properties);}},postRefreshHandler:function(widget){var pagesList=document.getElementById("pages_list_id");if(pagesList!=null&&!isAndroid()&&!isIOS()){dojo.addClass(pagesList,"desktop");}
cursor_clear();}}),wc.render.declareRefreshController({id:"MattelRecentlyViewedItemsController",renderContext:wc.render.getContextById("MattelRecentlyViewedItemsContext"),url:"",formId:"",renderContextChangedHandler:function(message,widget){if(this.testForChangedRC(["emsName"])){widget.refresh(this.renderContext.properties);}},postRefreshHandler:function(widget){cursor_clear();}}),wc.render.declareRefreshController({id:"clubSearchNavigation_controller",renderContext:wc.render.getContextById("clubSearchNavigationContext"),url:"",formId:"",renderContextChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;widget.refresh(this.renderContext.properties);},postRefreshHandler:function(widget){cursor_clear();}}),wc.service.declare({id:"RLCForumRedirectUrl",actionId:"RLCForumRedirectUrl",url:"AjaxCheckMemberShip",formId:"",successHandler:function(serviceResponse){var isRLC=serviceResponse.isRLC;var isForumRedirect=serviceResponse.isRLC;if(isRLC){if(document.getElementById("HWCRLCForumsURL")){var HWCRLCForumsURL=document.getElementById("HWCRLCForumsURL").value;window.location.href=HWCRLCForumsURL;}}
else{if(document.getElementById("HWCForumsURL")){var HWCForumsURL=document.getElementById("HWCForumsURL").value;window.location.href=HWCForumsURL;}}},failureHandler:function(serviceResponse){}}),wc.render.declareRefreshController({id:"CreateShoppingListController",renderContext:wc.render.getContextById("CreateShoppingListContext"),url:"ShowShoppingListView",formId:"",renderContextChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;widget.refresh(this.renderContext.properties);},postRefreshHandler:function(widget){cursor_clear();}}),wc.render.declareRefreshController({id:"HaveItWantItWishlistDisplay_Controller",renderContext:wc.render.getContextById("HaveItWantItWishlistDisplay_Context"),url:"HaveItWantItDetailsView",formId:"",renderContextChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;widget.refresh(renderContext.properties);},postRefreshHandler:function(widget){var controller=this;var renderContext=this.renderContext;var popup=dijit.byId("wishListDetailsPopup");var popupDisplay=document.getElementById("wishListDetailsPopup");$('#haveItWantItListPopup .header-sub-title').html(shoppingListJS.productName);if(popup!=null){if(popupDisplay.style.display=="none"){popup.closeButtonNode.style.display='none';closeAllDialogs();setTimeout(function(){popup.show();},250);var wishlistLength=$(".wish-list-popup .wishlists-list label").length;$(".total-wishlists-count").text(wishlistLength);if(wishlistLength>4){$(".wish-list-popup .wishlists-list label:gt(3), .wish-list-popup .wishlists-list br:gt(3)").hide();$(".wish-list-popup .view-all-wishlists").show();}else{$(".wish-list-popup .view-all-wishlists").hide();}
$(".view-all-wishlists").click(function(){$(".wish-list-popup .wishlists-list label:gt(3), .wish-list-popup .wishlists-list br:gt(3)").show();$(".wish-list-popup .view-all-wishlists").hide();})
var collectionsLength=$(".wish-list-popup .collections-list label").length;$(".total-collections-count").text(collectionsLength);if(collectionsLength>4){$(".wish-list-popup .collections-list label:gt(3), .wish-list-popup .collections-list br:gt(3)").hide();$(".wish-list-popup .view-all-collections").show();}else{$(".wish-list-popup .view-all-collections").hide();}
$(".view-all-collections").click(function(){$(".wish-list-popup .collections-list label:gt(3), .wish-list-popup .collections-list br:gt(3)").show();$(".wish-list-popup .view-all-collections").hide();});}}else{console.debug(action+"wishListDetailsPopup"+" does not exist");}
cursor_clear();}});});ServicesDeclarationJS={langId:"-1",storeId:"",catalogId:"",partNumber:"",setCommonParameters:function(langId,storeId,catalogId){this.langId=langId;this.storeId=storeId;this.catalogId=catalogId;}}
function nullCartTotalCookie(orderId){var parts=location.hostname.split('.');while(parts.length>2)
var subdomain=parts.shift();var upperleveldomain=parts.join('.');dojo.cookie("WC_CartTotal_"+orderId,null,{expires:-1,path:'/',domain:upperleveldomain});var cookies=document.cookie.split(";");for(var i=0;i<cookies.length;i++){var index=cookies[i].indexOf("=");var name=cookies[i].substr(0,index);var value=cookies[i].substr(index+1)
name=name.replace(/^\s+|\s+$/g,"");value=value.replace(/^\s+|\s+$/g,"");if(value==orderId){dojo.cookie(name,null,{expires:-1,path:'/'});break;}}}
dojo.addOnLoad(function(){wc.service.declare({id:"SubscribeToEmail",actionId:" SubscribeToEmail",url:" SubscribeToEmail",formId:"",successHandler:function(serviceResponse){},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){alert(serviceResponse.errorMessage);}}});wc.service.declare({id:"AjaxInterestItemAddAndDeleteFromCart",actionId:"AjaxInterestItemAddAndDeleteFromCart",url:getAbsoluteURL()+"AjaxInterestItemAdd",formId:"",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();resetRequest();CheckoutHelperJS.deleteFromCart(serviceResponse.orderItemId,true);MessageHelper.displayStatusMessage(MessageHelper.messages["WISHLIST_ADDED"]);},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxSFLAddAndDeleteFromCart",actionId:"AjaxSFLAddAndDeleteFromCart",url:getAbsoluteURL()+"MattelAjaxSFLOrderProcess",formId:"",successHandler:function(serviceResponse){resetRequest();CheckoutHelperJS.deleteFromCart(serviceResponse.penOrderItemId,true);},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxSFLAddAndDeleteFromCartNew",actionId:"AjaxSFLAddAndDeleteFromCartNew",url:getAbsoluteURL()+"MattelAjaxSFLOrderProcess",formId:"",successHandler:function(serviceResponse){resetRequest();CheckoutHelperJS.sflItemAdded=true;CheckoutHelperJS.deleteFromCart(serviceResponse.penOrderItemId,true);},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxAddOrderItem",actionId:"AjaxAddOrderItem",url:getAbsoluteURL()+"AjaxRESTOrderItemAdd",formId:"",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();cursor_clear();if(categoryDisplayJS){var attributes=document.getElementsByName("attrValue");var singleSKU=true;for(var i=0;i<attributes.length;i++){if(attributes[i].options.length>1)
{singleSKU=false;}}
if(!singleSKU)
{categoryDisplayJS.selectedAttributes=[];for(var i=0;i<attributes.length;i++){if(attributes[i]!=null){attributes[i].value="";}}}}
if(typeof(ShipmodeSelectionExtJS)!=null&&typeof(ShipmodeSelectionExtJS)!='undefined'){ShipmodeSelectionExtJS.setOrderItemId((serviceResponse.orderItem!=null&&serviceResponse.orderItem[0].orderItemId!=null)?serviceResponse.orderItem[0].orderItemId:serviceResponse.orderItemId);}},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){if(serviceResponse.errorMessageKey=="_ERR_NO_ELIGIBLE_TRADING"){MessageHelper.displayErrorMessage(MessageHelper.messages["ERROR_CONTRACT_EXPIRED_GOTO_ORDER"]);}else if(serviceResponse.errorMessageKey=="_ERR_RETRIEVE_PRICE"){MessageHelper.displayErrorMessage(MessageHelper.messages["ERROR_RETRIEVE_PRICE"]);}else{MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxAddOrderItem_shopCart",actionId:"AjaxAddOrderItem",url:getAbsoluteURL()+"AjaxOrderChangeServiceItemAdd",formId:"",successHandler:function(serviceResponse){document.location.href=appendWcCommonRequestParameters("AjaxOrderItemDisplayView?storeId="+ServicesDeclarationJS.storeId+"&catalogId="+ServicesDeclarationJS.catalogId+"&langId="+ServicesDeclarationJS.langId);},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){if(serviceResponse.errorMessageKey=="_ERR_NO_ELIGIBLE_TRADING"){MessageHelper.displayErrorMessage(MessageHelper.messages["ERROR_CONTRACT_EXPIRED_GOTO_ORDER"]);}else if(serviceResponse.errorMessageKey=="_ERR_RETRIEVE_PRICE"){MessageHelper.displayErrorMessage(MessageHelper.messages["ERROR_RETRIEVE_PRICE"]);}else{MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxDeleteOrderItem",actionId:"AjaxDeleteOrderItem",url:getAbsoluteURL()+"AjaxRESTOrderItemDelete",formId:"",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();MessageHelper.displayStatusMessage(MessageHelper.messages["SHOPCART_REMOVEITEM"]);if(CheckoutHelperJS.pendingOrderDetailsPage)
{CheckoutHelperJS.getOrderPaymentsInJSON('OrderReviewDelete');}
CheckoutHelperJS.setGiftCookieOnOrderItemDelete(serviceResponse.orderItemId);document.cookie="comiccon1=; path=/; domain=.mattel.com;expires=Thu, 01 Jan 1970 00:00:01 GMT";if($('input[name^="catEntryId_"]').length>0){document.cookie="comiccon1=-1; path=/; domain=.mattel.com; expires=Tue, 01 Aug 2017 00:00:01 GMT";$('input[name^="catEntryId_"]').each(function(){if($.inArray($(this).val(),comicconIds)>=0){document.cookie="comiccon1=1; path=/; domain=.mattel.com; expires=Tue, 01 Aug 2017 00:00:01 GMT";}});}},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxDeleteOrderItemBeforeEditCustomDoll",actionId:"AjaxDeleteOrderItem",url:getAbsoluteURL()+"AjaxRESTOrderItemDelete",formId:"",successHandler:function(serviceResponse){CheckoutHelperJS.redirectToMJDConfigurator();},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxDeleteOrderItemForShippingBillingPage",actionId:"AjaxDeleteOrderItemForShippingBillingPage",url:getAbsoluteURL()+"AjaxRESTOrderItemDelete",formId:"",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();MessageHelper.displayStatusMessage(MessageHelper.messages["SHOPCART_REMOVEITEM"]);},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxDeleteOrderItemFromCart",actionId:"AjaxDeleteOrderItem",url:getAbsoluteURL()+"AjaxRESTOrderItemDelete",formId:"",successHandler:function(serviceResponse){if(CheckoutHelperJS.shoppingCartPage&&CheckoutHelperJS.sflItemAdded){document.location.href=appendWcCommonRequestParameters("AjaxOrderItemDisplayView?storeId="+ServicesDeclarationJS.storeId+"&catalogId="+ServicesDeclarationJS.catalogId+"&langId="+ServicesDeclarationJS.langId);}},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxDeleteOrderItem1",actionId:"AjaxDeleteOrderItem",url:getAbsoluteURL()+"AjaxRESTOrderItemDelete",formId:"",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();MessageHelper.displayStatusMessage(MessageHelper.messages["SHOPCART_REMOVEITEM"]);if(!CheckoutHelperJS.pendingOrderDetailsPage)
{setDeleteCartCookie();if(CheckoutHelperJS.shoppingCartPage){document.location.href=appendWcCommonRequestParameters("AjaxOrderItemDisplayView?storeId="+ServicesDeclarationJS.storeId+"&catalogId="+ServicesDeclarationJS.catalogId+"&langId="+ServicesDeclarationJS.langId);}}
else
{cursor_clear();var currentOrder=CheckoutHelperJS.tempPaymentInstructions;if(currentOrder.paymentInstruction!=null&&currentOrder.paymentInstruction.length>=1){if(!submitRequest()){return;}
cursor_wait();var params=[];params["piId"]=new Array();for(var i=0;i<currentOrder.paymentInstruction.length;i++){params["piId"].push(currentOrder.paymentInstruction[i].piId);}
params["storeId"]=CheckoutHelperJS.storeId;params["catalogId"]=CheckoutHelperJS.catalogId;params["langId"]=CheckoutHelperJS.langId;params.orderId=currentOrder.orderId;wc.service.invoke('AjaxDeletePaymentInstructionsFromOrderReview',params);}
else
{document.location.href=appendWcCommonRequestParameters("AjaxOrderItemDisplayView?storeId="+ServicesDeclarationJS.storeId+"&catalogId="+ServicesDeclarationJS.catalogId+"&langId="+ServicesDeclarationJS.langId+"&orderId="+serviceResponse.orderId+"&fromPage=OrderReview");}}
document.cookie="comiccon1=; path=/; domain=.mattel.com;expires=Thu, 01 Jan 1970 00:00:01 GMT";CheckoutHelperJS.setGiftCookieOnOrderItemDelete(serviceResponse.orderItemId);},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxDeleteWCSSetOrderItem1",actionId:"AjaxDeleteOrderItem",url:getAbsoluteURL()+"AjaxOrderChangeServiceItemUpdate",formId:"",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();MessageHelper.displayStatusMessage(MessageHelper.messages["SHOPCART_REMOVEITEM"]);if(!CheckoutHelperJS.pendingOrderDetailsPage)
{setDeleteCartCookie();if(CheckoutHelperJS.shoppingCartPage){document.location.href=appendWcCommonRequestParameters("AjaxOrderItemDisplayView?storeId="+ServicesDeclarationJS.storeId+"&catalogId="+ServicesDeclarationJS.catalogId+"&langId="+ServicesDeclarationJS.langId);}}
else
{cursor_clear();var currentOrder=CheckoutHelperJS.tempPaymentInstructions;if(currentOrder.paymentInstruction!=null&&currentOrder.paymentInstruction.length>=1){if(!submitRequest()){return;}
cursor_wait();var params=[];params["piId"]=new Array();for(var i=0;i<currentOrder.paymentInstruction.length;i++){params["piId"].push(currentOrder.paymentInstruction[i].piId);}
params["storeId"]=CheckoutHelperJS.storeId;params["catalogId"]=CheckoutHelperJS.catalogId;params["langId"]=CheckoutHelperJS.langId;params.orderId=currentOrder.orderId;wc.service.invoke('AjaxDeletePaymentInstructionsFromOrderReview',params);}
else
{document.location.href=appendWcCommonRequestParameters("AjaxOrderItemDisplayView?storeId="+ServicesDeclarationJS.storeId+"&catalogId="+ServicesDeclarationJS.catalogId+"&langId="+ServicesDeclarationJS.langId+"&orderId="+serviceResponse.orderId+"&fromPage=OrderReview");}}
document.cookie="comiccon1=; path=/; domain=.mattel.com;expires=Thu, 01 Jan 1970 00:00:01 GMT";CheckoutHelperJS.setGiftCookieOnOrderItemDelete(serviceResponse.orderItemId);},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxDeleteWCSSetOrderItem",actionId:"AjaxDeleteOrderItem",url:getAbsoluteURL()+"AjaxOrderChangeServiceItemUpdate",formId:"",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();MessageHelper.displayStatusMessage(MessageHelper.messages["SHOPCART_REMOVEITEM"]);if(CheckoutHelperJS.pendingOrderDetailsPage)
{CheckoutHelperJS.getOrderPaymentsInJSON('OrderReviewDelete');}
if(!CheckoutHelperJS.pendingOrderDetailsPage)
{setDeleteCartCookie();if(CheckoutHelperJS.shoppingCartPage){document.location.href=appendWcCommonRequestParameters("AjaxOrderItemDisplayView?storeId="+ServicesDeclarationJS.storeId+"&catalogId="+ServicesDeclarationJS.catalogId+"&langId="+ServicesDeclarationJS.langId);}}
CheckoutHelperJS.setGiftCookieOnOrderItemDelete(serviceResponse.orderItemId);document.cookie="comiccon1=; path=/; domain=.mattel.com;expires=Thu, 01 Jan 1970 00:00:01 GMT";if($('input[name^=catEntryId_').length>0){document.cookie="comiccon1=-1; domain=.mattel.com; path=/; expires=Tue, 01 Aug 2017 00:00:01 GMT";$('input[name^=catEntryId_').each(function(){if($.inArray($(this).val(),comicconIds)>=0){document.cookie="comiccon1=1; domain=.mattel.com; path=/; expires=Tue, 01 Aug 2017 00:00:01 GMT";}});}},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxUpdateOrderItem",actionId:"AjaxUpdateOrderItem",url:getAbsoluteURL()+"AjaxRESTOrderItemUpdate",formId:"",successHandler:function(serviceResponse){if(serviceResponse.xitem_field1!=null&&serviceResponse.xitem_field1!='undefined'){if(serviceResponse.xitem_field1[0]=="1"){if(dojo.byId('giftingMessage')){dojo.addClass("giftingMessage","hide");}}}
MessageHelper.hideAndClearMessage();MessageHelper.hideFormErrorHandle();if(dijit.byId("MattelGiftCartPagingDisplay")!=undefined){var params={};params.storeId=serviceResponse.storeId[0];params.catalogId=serviceResponse.catalogId[0];params.langId=serviceResponse.langId[0];if(giftReceipt.checked){params["giftReceipt"]="1";}else{params["giftReceipt"]="0";}
wc.render.updateContext("MattelGiftCartPaginationDisplay_Context",params);}
if(CheckoutHelperJS.pendingOrderDetailsPage)
{CheckoutHelperJS.getOrderPaymentsInJSON('OrderReviewUpdate');}
cursor_clear();},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){if(serviceResponse.errorMessageKey=="_ERR_RETRIEVE_PRICE"){MessageHelper.displayErrorMessage(MessageHelper.messages["ERROR_RETRIEVE_PRICE_QTY_UPDATE"]);}
else if(serviceResponse.errorMessageKey=="_ERR_USER_AUTHORITY"){location.reload();}
else{MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}}
else{if(serviceResponse.errorMessageKey=="_ERR_USER_AUTHORITY"){location.reload();}
else if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxUpdateOrderItem1",actionId:"AjaxUpdateOrderItem",url:getAbsoluteURL()+"AjaxRESTOrderItemUpdate",formId:"",successHandler:function(serviceResponse){if(!CheckoutHelperJS.pendingOrderDetailsPage)
{if(CheckoutHelperJS.shoppingCartPage){document.location.href=appendWcCommonRequestParameters("AjaxOrderItemDisplayView?storeId="+ServicesDeclarationJS.storeId+"&catalogId="+ServicesDeclarationJS.catalogId+"&langId="+ServicesDeclarationJS.langId);}}
else
{if(dijit.byId("ShopCartDisplay")!=undefined){params.storeId=serviceResponse.storeId[0];params.catalogId=serviceResponse.catalogId[0];params.langId=serviceResponse.langId[0];params.productId=serviceResponse.productId[0];wc.render.updateContext("ShopCartPaginationDisplay_Context",params);}
CheckoutHelperJS.getOrderPaymentsInJSON('OrderReviewUpdate');cursor_clear();}},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){if(serviceResponse.errorMessageKey=="_ERR_RETRIEVE_PRICE"){MessageHelper.displayErrorMessage(MessageHelper.messages["ERROR_RETRIEVE_PRICE_QTY_UPDATE"]);}
else if(serviceResponse.errorMessageKey=="_ERR_USER_AUTHORITY"){location.reload();}
else{MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}}
else{if(serviceResponse.errorMessageKey=="_ERR_USER_AUTHORITY"){location.reload();}
else if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxUpdateOrderShippingInfo",actionId:"AjaxUpdateOrderShippingInfo",url:getAbsoluteURL()+"AjaxRESTOrderShipInfoUpdate",formId:"",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();cursor_clear();},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxPrepareOrderForSubmit",actionId:"AjaxPrepareOrderForSubmit",url:getAbsoluteURL()+"AjaxRESTOrderPrepare",formId:"",successHandler:function(serviceResponse){CheckoutHelperJS.setOrderPrepared("true");CheckoutHelperJS.checkoutOrder(CheckoutHelperJS.getSavedParameter('tempOrderId'),CheckoutHelperJS.getSavedParameter('tempUserType'),CheckoutHelperJS.getSavedParameter('tempEmailAddresses'),CheckoutHelperJS.getSavedParameter('tempIsQuote'));},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxSubmitOrder",actionId:"AjaxSubmitOrder",url:getAbsoluteURL()+"AjaxRESTOrderSubmit",formId:"",successHandler:function(serviceResponse){nullCartTotalCookie(serviceResponse.orderId);var shipmentTypeId=CheckoutHelperJS.getShipmentTypeId();document.location.href=appendWcCommonRequestParameters("OrderShippingBillingConfirmationView?storeId="+ServicesDeclarationJS.storeId+"&catalogId="+ServicesDeclarationJS.catalogId+"&langId="+ServicesDeclarationJS.langId+"&orderId="+serviceResponse.orderId+"&shipmentTypeId="+shipmentTypeId);},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){if(serviceResponse.errorMessage=='PLUGIN_PAYMENT_INSUFFICIENT_FUNDS'||serviceResponse.errorMessage=='PLUGIN_AUTHORIZATION_FAILED')
{MessageHelper.displayErrorMessage(MessageHelper.messages[serviceResponse.errorMessage]);}
else if(serviceResponse.errorMessage=='_ERR_PAYPAL_PAYMENT_APPROVAL_EXPIRED')
{MessageHelper.displayErrorMessage(MessageHelper.messages['PAYPAL_PAYMENT_APPROVAL_EXPIRED']);}
else
{MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxSubmitQuote",actionId:"AjaxSubmitQuote",url:getAbsoluteURL()+"AjaxSubmitQuote",formId:"",successHandler:function(serviceResponse){var redirectURL="OrderShippingBillingConfirmationView?storeId="+ServicesDeclarationJS.storeId
+"&catalogId="+ServicesDeclarationJS.catalogId
+"&langId="+ServicesDeclarationJS.langId
+"&orderId="+CheckoutHelperJS.getOrderId()
+"&shipmentTypeId="+CheckoutHelperJS.getShipmentTypeId()
+"&isQuote=true"
+"&quoteId="+serviceResponse.outOrderId
if(serviceResponse.outExternalQuoteId!=undefined&&serviceResponse.outExternalQuoteId!=null){redirectURL+=redirectURL+"&externalQuoteId="+serviceResponse.outExternalQuoteId;}
document.location.href=appendWcCommonRequestParameters(redirectURL);},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxAddAddressForPerson",actionId:"AjaxAddAddressForPerson",url:getAbsoluteURL()+"AjaxPersonChangeServiceAddressAdd",formId:"",successHandler:function(serviceResponse){AddressHelper.updateOrderAfterAddressUpdate();MessageHelper.hideAndClearMessage();cursor_clear();},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxUpdateAddressForPerson",actionId:"AjaxUpdateAddressForPerson",url:getAbsoluteURL()+"AjaxPersonChangeServiceAddressUpdate",formId:"",successHandler:function(serviceResponse){AddressHelper.updateOrderAfterAddressUpdate();MessageHelper.hideAndClearMessage();cursor_clear();},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxUpdateOrderAfterAddressUpdate",actionId:"AjaxUpdateOrderAfterAddressUpdate",url:getAbsoluteURL()+"AjaxRESTOrderItemUpdate",formId:"",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();cursor_clear();},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxInterestItemAdd",actionId:"AjaxInterestItemAdd",url:getAbsoluteURL()+"AjaxInterestItemAdd",formId:"",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();cursor_clear();MessageHelper.displayStatusMessage(MessageHelper.messages["WISHLIST_ADDED"]);if(categoryDisplayJS)
categoryDisplayJS.selectedAttributes=[];},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxInterestItemAdd_shopCart",actionId:"AjaxInterestItemAdd",url:getAbsoluteURL()+"AjaxInterestItemAdd",formId:"",successHandler:function(serviceResponse){document.location.href=appendWcCommonRequestParameters("AjaxOrderItemDisplayView?storeId="+ServicesDeclarationJS.storeId+"&catalogId="+ServicesDeclarationJS.catalogId+"&langId="+ServicesDeclarationJS.langId);},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxInterestItemDelete",actionId:"AjaxInterestItemDelete",url:getAbsoluteURL()+"AjaxInterestItemDelete",formId:"",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxInterestItemListMessage",actionId:"AjaxInterestItemListMessage",url:getAbsoluteURL()+"AjaxInterestItemListMessage",formId:"",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxPromotionCodeManage",actionId:"AjaxPromotionCodeManage",url:getAbsoluteURL()+"AjaxPromotionCodeManage",formId:"PromotionCodeForm",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();var params=[];params.storeId=ServicesDeclarationJS.storeId;params.catalogId=ServicesDeclarationJS.catalogId;params.langId=ServicesDeclarationJS.langId;if(document.getElementById("orderItem_1")!=null&&document.getElementById("orderItem_1")!='undefined'){params.orderItemId=document.getElementById("orderItem_1").value;}else if(document.getElementById("orderItemIdforPromo")!=null&&document.getElementById("orderItemIdforPromo")!='undefined'){params.orderItemId=document.getElementById("orderItemIdforPromo").value;}
if(document.getElementById("qty_1")!=null&&document.getElementById("qty_1")!='undefined'){params.quantity=document.getElementById("qty_1").value;}else if(document.getElementById("qtyforPromo")!=null&&document.getElementById("qtyforPromo")!='undefined'){params.quantity=document.getElementById("qtyforPromo").value;}
if(CheckoutHelperJS.shoppingCartPage){params.calculationUsage="-1,-2,-5,-6,-7";}else{params.calculationUsage="-1,-2,-3,-4,-5,-6,-7";}
params.calculateOrder="1";wc.service.invoke("AjaxUpdateOrderItem",params);},failureHandler:function(serviceResponse){var errPromoEmailFlag=false;if(serviceResponse.errorMessageKey=='_ERR_INVALID_PROMO_EMAIL'||serviceResponse.errorMessageKey=='_ERR_ENTER_PROMO_EMAIL'){errPromoEmailFlag=true;}
if(serviceResponse.errorMessageKey!=null&&errPromoEmailFlag){if(serviceResponse.errorMessageKey=='_ERR_ENTER_PROMO_EMAIL'){dojo.byId("promoCodeEmailValue").style.display='block';if(sfIndicator=='AG'){dojo.byId("promoCode").disabled=true;dojo.byId("WC_PromotionCodeDisplay_links_1").display='none';}}
MessageHelper.formErrorHandleClient("promoCodeEmailValue",MessageHelper.messages[serviceResponse.errorMessageKey]);}
else if(serviceResponse.errorMessageKey=='_ERR_GENERIC'){MessageHelper.displayErrorMessage(MessageHelper.messages['_ERR_GENERIC_PROMO']);}
else if(serviceResponse.errorMessageKey=="_ERR_USER_AUTHORITY"){location.reload();}
else{if(serviceResponse.errorMessageKey&&!errPromoEmailFlag){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);dojo.byId("promoCodeEmailValue").style.display='none';if(sfIndicator=='AG'){dojo.byId("promoCode").disabled=false;dojo.byId("WC_PromotionCodeDisplay_links_1").display='block';dojo.byId("promoCode").name="promoCode";dojo.byId("rewardCode").name="rewardCode";}}}
cursor_clear();}}),wc.service.declare({id:"AjaxPromotionCodeDelete",actionId:"AjaxPromotionCodeManage",url:getAbsoluteURL()+"AjaxRESTPromotionCodeRemove",formId:"",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();var params=[];params.storeId=ServicesDeclarationJS.storeId;params.catalogId=ServicesDeclarationJS.catalogId;params.langId=ServicesDeclarationJS.langId;if(document.getElementById("orderItem_1")!=null&&document.getElementById("orderItem_1")!='undefined'){params.orderItemId=document.getElementById("orderItem_1").value;}else if(document.getElementById("orderItemIdforPromo")!=null&&document.getElementById("orderItemIdforPromo")!='undefined'){params.orderItemId=document.getElementById("orderItemIdforPromo").value;}
if(document.getElementById("qty_1")!=null&&document.getElementById("qty_1")!='undefined'){params.quantity=document.getElementById("qty_1").value;}else if(document.getElementById("qtyforPromo")!=null&&document.getElementById("qtyforPromo")!='undefined'){params.quantity=document.getElementById("qtyforPromo").value;}
CheckoutHelperJS.promoCode=serviceResponse.promoCode;if(CheckoutHelperJS.shoppingCartPage){params.calculationUsage="-1,-2,-5,-6,-7";}else{params.calculationUsage="-1,-2,-3,-4,-5,-6,-7";}
params.calculateOrder="1";wc.service.invoke("AjaxUpdateOrderItem",params);},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxCouponsAdd",actionId:"AjaxCouponsAddRemove",url:getAbsoluteURL()+"AjaxRESTCouponsAdd",formId:"",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();var params=[];params.storeId=this.storeId;params.catalogId=this.catalogId;params.langId=this.langId;params.orderItemId="";params.orderId=serviceResponse.orderId;if(CheckoutHelperJS.shoppingCartPage){params.calculationUsage="-1,-2,-5,-6,-7";}else{params.calculationUsage="-1,-2,-3,-4,-5,-6,-7";}
params.calculateOrder="1";wc.service.invoke("AjaxUpdateOrderItem",params);},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else if(serviceResponse.errorMessageKey=="_ERR_USER_AUTHORITY"){location.reload();}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxCouponsRemove",actionId:"AjaxCouponsAddRemove",url:getAbsoluteURL()+"AjaxRESTCouponsRemove",formId:"",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();var params=[];params.storeId=this.storeId;params.catalogId=this.catalogId;params.langId=this.langId;params.orderItemId="";params.orderId=serviceResponse.orderId;if(CheckoutHelperJS.shoppingCartPage){params.calculationUsage="-1,-2,-5,-6,-7";}else{params.calculationUsage="-1,-2,-3,-4,-5,-6,-7";}
params.calculateOrder="1";wc.service.invoke("AjaxUpdateOrderItem",params);},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AddBillingAddress",actionId:"AddBillingAddress",url:getAbsoluteURL()+"AjaxPersonChangeServiceAddressAdd",formId:"",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"ScheduleOrder",actionId:"ScheduleOrder",url:getAbsoluteURL()+"AjaxRESTScheduleOrder",formId:"",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();var originalOrderId=document.getElementById("orderIdToSchedule").value;var newOrderId=serviceResponse.orderId;nullCartTotalCookie(serviceResponse.orderId);var shipmentTypeId=CheckoutHelperJS.getShipmentTypeId();var purchaseOrderNumber="";if(document.forms["purchaseOrderNumberInfo"].purchase_order_number.value!=null){purchaseOrderNumber=document.forms["purchaseOrderNumberInfo"].purchase_order_number.value;}
var url="RESTOrderCancel?orderId="+originalOrderId+"&storeId="+ServicesDeclarationJS.storeId+"&catalogId="+ServicesDeclarationJS.catalogId+"&langId="+ServicesDeclarationJS.langId+"&URL=OrderShippingBillingConfirmationView%3ForderId%3D"+newOrderId+"%26originalOrderId%3D"+originalOrderId+"%26shipmentTypeId%3D"+shipmentTypeId+"%26purchaseOrderNumber%3D"+purchaseOrderNumber;document.location.href=appendWcCommonRequestParameters(url);},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"SubmitRecurringOrder",actionId:"SubmitRecurringOrder",url:getAbsoluteURL()+"AjaxRESTSubmitRecurringOrSubscription",formId:"",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();nullCartTotalCookie(serviceResponse.orderId);var shipmentTypeId=CheckoutHelperJS.getShipmentTypeId();var url="OrderShippingBillingConfirmationView?storeId="+ServicesDeclarationJS.storeId+"&catalogId="+ServicesDeclarationJS.catalogId+"&langId="+ServicesDeclarationJS.langId+"&orderId="+serviceResponse.orderId+"&shipmentTypeId="+shipmentTypeId;document.location.href=appendWcCommonRequestParameters(url);cursor_clear();},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxUpdateRewardOption",actionId:"AjaxUpdateRewardOption",url:getAbsoluteURL()+"AjaxRESTOrderRewardOptionUpdate",formId:"",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();if(dijit.byId("MattelGiftCartPagingDisplay")!=undefined){var params={};params.storeId=serviceResponse.storeId;params.catalogId=serviceResponse.catalogId;params.langId=serviceResponse.langId;if(giftReceipt.checked){params["giftReceipt"]="1";}else{params["giftReceipt"]="0";}
wc.render.updateContext("MattelGiftCartPaginationDisplay_Context",params);}
cursor_clear();},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxOrderCreate",actionId:"AjaxOrderCreate",url:getAbsoluteURL()+"AjaxOrderCreate",formId:"",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();MessageHelper.displayStatusMessage(MessageHelper.messages["ORDER_CREATED"]);cursor_clear();},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){if(serviceResponse.errorCode=="CMN0409E")
{MessageHelper.displayErrorMessage(MessageHelper.messages["ORDER_NOT_CREATED"]);}
else
{MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxSingleOrderCancel",actionId:"AjaxSingleOrderCancel",url:getAbsoluteURL()+"AjaxRESTOrderCancel",formId:"",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();MessageHelper.displayStatusMessage(MessageHelper.messages["ORDERS_CANCELLED"]);cursor_clear();},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){if(serviceResponse.errorCode=="CMN0409E")
{MessageHelper.displayErrorMessage(MessageHelper.messages["ORDER_NOT_CANCELLED"]);}
else
{MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxOrderCancel",actionId:"AjaxOrderCancel",url:getAbsoluteURL()+"AjaxRESTOrderCancel",formId:"",successHandler:function(serviceResponse){savedOrdersJS.cancelSavedOrder(false);},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){if(serviceResponse.errorCode=="CMN0409E")
{MessageHelper.displayErrorMessage(MessageHelper.messages["ORDER_NOT_CANCELLED"]);}
else
{MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxSingleOrderSave",actionId:"AjaxSingleOrderSave",url:getAbsoluteURL()+"AjaxOrderCopy",formId:"",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();if(savedOrdersJS.isOrderDetailsPageValue)
{MessageHelper.displayStatusMessage(MessageHelper.messages["PENDING_ORDER_SAVED"]);}
else
{MessageHelper.displayStatusMessage(MessageHelper.messages["ORDERS_SAVED"]);}
var inputElement=document.getElementById('OrderDescription_input');if(inputElement!=null&&inputElement!='undefined')
{dojo.removeClass(inputElement,'savedOrderDetailsInputBorderWarning');dojo.addClass(inputElement,'savedOrderDetailsInputBorder');document.getElementById('OldOrderDescription').value=inputElement.value;}
cursor_clear();if(savedOrdersJS.updateCartRequired)
{savedOrdersJS.updateCartRequired=false;CheckoutHelperJS.updateShoppingCart(document.ShopCartForm);}},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){if(serviceResponse.errorCode=="CMN0409E"||serviceResponse.errorCode=="CMN1024E")
{if(serviceResponse.errorCode=="CMN1024E"&&serviceResponse.systemMessage!="")
{MessageHelper.displayErrorMessage(serviceResponse.systemMessage);}
else
{if(savedOrdersJS.isOrderDetailsPageValue)
{MessageHelper.displayStatusMessage(MessageHelper.messages["PENDING_ORDER_NOT_SAVED"]);}
else
{MessageHelper.displayErrorMessage(MessageHelper.messages["ORDER_NOT_SAVED"]);}}}
else
{MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxOrderSave",actionId:"AjaxOrderSave",url:getAbsoluteURL()+"AjaxOrderCopy",formId:"",successHandler:function(serviceResponse){savedOrdersJS.saveOrder(false);},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){if(serviceResponse.errorCode=="CMN0409E")
{MessageHelper.displayErrorMessage(MessageHelper.messages["ORDER_NOT_SAVED"]);}
else
{MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxSetPendingOrder",actionId:"AjaxSetPendingOrder",url:getAbsoluteURL()+"AjaxRESTSetPendingOrder",formId:"",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();MessageHelper.displayStatusMessage(MessageHelper.messages["ORDER_SET_CURRENT"]);savedOrdersJS.determinePageForward("AjaxSetPendingOrder");cursor_clear();},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){if(serviceResponse.errorCode=="CMN0409E"||serviceResponse.errorCode=="CMN1024E")
{MessageHelper.displayErrorMessage(MessageHelper.messages["ORDER_NOT_SET_CURRENT"]);}
else
{MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxUpdatePendingOrder",actionId:"AjaxUpdatePendingOrder",url:getAbsoluteURL()+"AjaxRESTSetPendingOrder",formId:"",successHandler:function(serviceResponse){savedOrdersJS.determinePageForward("AjaxUpdatePendingOrder");cursor_clear();},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){if(serviceResponse.errorCode=="CMN0409E")
{MessageHelper.displayErrorMessage(MessageHelper.messages["ORDER_NOT_SET_CURRENT"]);}
else
{MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxSingleOrderCopy",actionId:"AjaxSingleOrderCopy",url:getAbsoluteURL()+"AjaxOrderCopy",formId:"",successHandler:function(serviceResponse){var params=[];params.storeId=this.storeId;params.catalogId=this.catalogId;params.langId=this.langId;params.URL="";params.updatePrices="1";params.orderId=serviceResponse.orderId;params.calculationUsageId="-1";wc.service.invoke("AjaxSingleOrderCalculate",params);MessageHelper.hideAndClearMessage();},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){if(serviceResponse.errorCode=="CMN0409E")
{MessageHelper.displayErrorMessage(MessageHelper.messages["ORDER_NOT_COPIED"]);}
else
{MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxOrderCopy",actionId:"AjaxOrderCopy",url:getAbsoluteURL()+"AjaxOrderCopy",formId:"",successHandler:function(serviceResponse){var params=[];params.storeId=this.storeId;params.catalogId=this.catalogId;params.langId=this.langId;params.URL="";params.updatePrices="1";params.orderId=serviceResponse.orderId;params.calculationUsageId="-1";wc.service.invoke("AjaxOrderCalculate",params);MessageHelper.hideAndClearMessage();},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){if(serviceResponse.errorCode=="CMN0409E")
{MessageHelper.displayErrorMessage(MessageHelper.messages["ORDER_NOT_COPIED"]);}
else
{MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxSingleOrderCalculate",actionId:"AjaxSingleOrderCalculate",url:getAbsoluteURL()+"AjaxRESTOrderCalculate",formId:"",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();MessageHelper.displayStatusMessage(MessageHelper.messages["ORDER_COPIED"]);cursor_clear();},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){if(serviceResponse.errorCode=="CMN0409E")
{MessageHelper.displayErrorMessage(MessageHelper.messages["ORDER_NOT_COPIED"]);}
else
{MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxCurrentOrderCalculate",actionId:"AjaxCurrentOrderCalculate",url:getAbsoluteURL()+"AjaxRESTOrderCalculate",formId:"",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();MessageHelper.displayStatusMessage(MessageHelper.messages["ORDER_SET_CURRENT"]);cursor_clear();},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){if(serviceResponse.errorCode=="CMN0409E")
{MessageHelper.displayErrorMessage(MessageHelper.messages["ORDER_NOT_COPIED"]);}
else
{MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxOrderCalculate",actionId:"AjaxOrderCalculate",url:getAbsoluteURL()+"AjaxRESTOrderCalculate",formId:"",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();savedOrdersJS.copyOrder(false);},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){if(serviceResponse.errorCode=="CMN0409E")
{MessageHelper.displayErrorMessage(MessageHelper.messages["ORDER_NOT_COPIED"]);}
else
{MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxPromoOrderCalculate",actionId:"AjaxPromoOrderCalculate",url:getAbsoluteURL()+"AjaxRESTOrderCalculate",formId:"",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();cursor_clear();},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){if(serviceResponse.errorCode=="CMN0409E")
{MessageHelper.displayErrorMessage(MessageHelper.messages["ORDER_NOT_COPIED"]);}
else
{MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxRewardOrderCalculate",actionId:"AjaxRewardOrderCalculate",url:getAbsoluteURL()+"AjaxRESTOrderCalculate",formId:"",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();cursor_clear();},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxPunchoutPay",actionId:"AjaxPunchoutPay",url:"PunchoutPaymentRepay",formId:"",successHandler:function(serviceResponse){PunchoutJS.handleResponse(serviceResponse.orderId);MessageHelper.hideAndClearMessage();cursor_clear();},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxCategorySubscribe",actionId:"AjaxCategorySubscribe",url:"AjaxRESTMarketingTriggerProcessServiceEvaluate",formId:"",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();MessageHelper.displayStatusMessage(MessageHelper.messages["SUBSCRIPTION_UPDATED"]);},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"MattelAjaxUpdateShippingAddress",actionId:"MattelAjaxUpdateShippingAddress",url:getAbsoluteURL()+"AjaxPersonChangeServiceAddressUpdate",formId:"",successHandler:function(serviceResponse){CheckoutHelperJS.updateAddressIdForOrderItem(serviceResponse.addressId);resetRequest();cursor_clear();wc.render.updateContext('shippingAddressDropDownBoxContext',{'shippingAddress':serviceResponse.addressId});try{CheckoutHelperJS.displayShippingModeByCountry(document.getElementsByName("country")[0]);CheckoutHelperJS.displayShippingModeByState(document.getElementsByName("country")[0].value,document.getElementsByName('state')[0].value);}catch(e){console.log("Error:"+e);}},failureHandler:function(serviceResponse){if(serviceResponse.errorMessageKey=='_ERR_COMMAND_EXCEPTION'){cursor_clear();CheckoutHelperJS.showingAVSDialog(serviceResponse);}
else{if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}}),wc.service.declare({id:"MattelAjaxUpdateAddressForPerson",actionId:"MattelAjaxUpdateAddressForPerson",url:getAbsoluteURL()+"AjaxPersonChangeServiceAddressUpdate",formId:"",successHandler:function(serviceResponse){cursor_clear();var avsDialog=dijit.byId('AVSDialog');;if(avsDialog!=undefined&&avsDialog.open)
{avsDialog.hide();}
if(document.getElementById('sameAsShipping'))
{CheckoutHelperJS.clickBillingSameAsShipping('1');}
else
{CheckoutHelperJS.showHideDivs('mainContents','editAddressContents');}
if(CheckoutHelperJS.isChanged){CheckoutHelperJS.isChanged=false;if(!AddressHelper.addressAdded)
CheckoutPayments.processBillingCheckout("PaymentForm");else
AddressHelper.addressAdded=false;}
CheckoutPayments.applyPaymentBillingAddressUpdate(serviceResponse.addressId,serviceResponse.nickName);},failureHandler:function(serviceResponse){var savedAddressId='';if(AddressHelper.savedaddressId!=null&&AddressHelper.savedaddressId!=undefined&&AddressHelper.savedaddressId!=''){savedAddressId=AddressHelper.savedaddressId;}
if(serviceResponse.errorMessageKey=='_ERR_COMMAND_EXCEPTION'){cursor_clear();CheckoutHelperJS.showingAVSDialog(serviceResponse);}
else{var errorMessageProduced='The value of the parameter "addressId" is not correct.';if(serviceResponse.errorMessage){if(serviceResponse.errorMessage.indexOf(errorMessageProduced)>=0)
MessageHelper.displayErrorMessage('The value of the parameter "addressId : '+savedAddressId+' "is not correct.');else
MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}}),wc.service.declare({id:"AddPaymentBillingAddress",actionId:"AddPaymentBillingAddress",url:getAbsoluteURL()+"AjaxPersonChangeServiceAddressAdd",formId:"",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();cursor_clear();var avsDialog=dijit.byId('AVSDialog');;if(avsDialog!=undefined&&avsDialog.open)
{avsDialog.hide();}
if(CheckoutHelperJS.isChanged){CheckoutHelperJS.isChanged=false;if(!AddressHelper.addressAdded)
CheckoutPayments.processBillingCheckout("PaymentForm");else
AddressHelper.addressAdded=false;}
wc.render.updateContext('billingAddressDropDownBoxContext',{'billingAddress1':serviceResponse.addressId});},failureHandler:function(serviceResponse){cursor_clear();if(serviceResponse.errorMessageKey=='_ERR_COMMAND_EXCEPTION'){CheckoutHelperJS.showingAVSDialog(serviceResponse);}
else{if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}}),wc.service.declare({id:"AjaxMattelCreateFedexSelfServiceCmd",actionId:"AjaxMattelCreateFedexSelfServiceCmd",url:"MattelCreateFedexSelfServiceCmd",formId:"fedexform",successHandler:function(serviceResponse){window.location=serviceResponse.pdfString;},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){var parameters={};parameters.errorMessage=serviceResponse.errorMessage;}}}),wc.service.declare({id:"RetailStoreAvailability",actionId:"RetailStoreAvailability",url:"RetailStoreAvailability",formId:"",uniqueId:"",successHandler:function(serviceResponse){dojo.removeClass("stockAvailability"+this.uniqueId,"hide");var stock_status_id="stock_status"+this.uniqueId;if(serviceResponse.serviceStatus==1){var element=document.getElementById(stock_status_id);element.innerHTML="Unable to access inventory";dojo.addClass(stock_status_id,"unavailable");dojo.removeClass(stock_status_id,"available");}
else if(serviceResponse.itemAvailabilityDetailsList.length==0){var element=document.getElementById(stock_status_id);element.innerHTML="Unable to access inventory";dojo.addClass(stock_status_id,"unavailable");dojo.removeClass(stock_status_id,"available");}
else{for(var i=0,len=serviceResponse.itemAvailabilityDetailsList.length;i<len;i++){if(serviceResponse.itemAvailabilityDetailsList[i].availabilityStatus=='A'||serviceResponse.itemAvailabilityDetailsList[i].availabilityStatus=='N')
{var element=document.getElementById(stock_status_id);element.innerHTML="Available";dojo.addClass(stock_status_id,"available");dojo.removeClass(stock_status_id,"unavailable");}
else if(serviceResponse.itemAvailabilityDetailsList[i].availabilityStatus=='M')
{var element=document.getElementById(stock_status_id);element.innerHTML="Limited";dojo.addClass(stock_status_id,"available");dojo.removeClass(stock_status_id,"unavailable");}
else if(serviceResponse.itemAvailabilityDetailsList[i].availabilityStatus=='B')
{var element=document.getElementById(stock_status_id);element.innerHTML="Backordered";dojo.addClass(stock_status_id,"available");dojo.removeClass(stock_status_id,"unavailable");}
else if(serviceResponse.itemAvailabilityDetailsList[i].availabilityStatus=='T')
{var element=document.getElementById(stock_status_id);element.innerHTML="No longer available";dojo.addClass(stock_status_id,"unavailable");dojo.removeClass(stock_status_id,"available");}
else if(serviceResponse.itemAvailabilityDetailsList[i].availabilityStatus=="S")
{var element=document.getElementById(stock_status_id);element.innerHTML="Unavailable";dojo.addClass(stock_status_id,"unavailable");dojo.removeClass(stock_status_id,"available");}
if(serviceResponse.serviceStatus==1)
{var element=document.getElementById(stock_status_id);element.innerHTML="Unable to access inventory";dojo.addClass(stock_status_id,"unavailable");dojo.removeClass(stock_status_id,"available");}}}
dojo.removeClass(dojo.query(".location_select_label")[0],"hide");},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){var parameters={};parameters.errorMessage=serviceResponse.errorMessage;}}}),wc.service.declare({id:"GetGiftMessageForOrderItemCmd",actionId:"GetGiftMessageForOrderItemCmd",url:"GetGiftMessageForOrderItemCmd",formId:"",successHandler:function(serviceResponse){var notes=serviceResponse.Notes;if(notes!=null&&notes!=undefined){var parsedNotes=JSON.parse(notes);document.getElementById('mattel-gift-line4_'+serviceResponse.orderItemId).value=parsedNotes.giftMsgTo;document.getElementById('mattel-gift-line5_'+serviceResponse.orderItemId).value=parsedNotes.giftMsgFrom;document.getElementById('mattel-gift-line1_'+serviceResponse.orderItemId).value=parsedNotes.giftMsg1;document.getElementById('mattel-gift-line2_'+serviceResponse.orderItemId).value=parsedNotes.giftMsg2;document.getElementById('mattel-gift-line3_'+serviceResponse.orderItemId).value=parsedNotes.giftMsg3;}},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){var parameters={};parameters.errorMessage=serviceResponse.errorMessage;}}}),wc.service.declare({id:"MattelCheckLoyaltyAccount",actionId:"MattelCheckLoyaltyAccount",url:"MattelCheckLoyaltyAccount",formId:"",successHandler:function(serviceResponse){$('#findRewardsButton').addClass('hide');if(!serviceResponse.membershipAccountFound){$('#rewardsErrorMessage').removeClass('hide');}
else if(serviceResponse.membershipAccountFound&&serviceResponse.userType=='G'){$('#rewardsAccountSignup').removeClass('hide');var form=document.forms['RegisterReward'];form['logonId'].value=WCParamJS.storeId+"|"+serviceResponse.emailId;form['logonIdVerify'].value=WCParamJS.storeId+"|"+serviceResponse.emailId;form['logonIdDisplay'].value=serviceResponse.emailId;form['logonIdVerifyDisplay'].value=serviceResponse.emailId;form['firstName'].value=serviceResponse.firstName;form['lastName'].value=serviceResponse.lastName;if(serviceResponse.phone!=null&&serviceResponse.phone!=undefined){form['phone1'].value=serviceResponse.phone;}
$('#createNewRewardsAccount').removeClass('hide');}
else if(serviceResponse.membershipAccountFound&&serviceResponse.userType=='R'){$('#rewardsErrorMessageAlreadyRegistered').removeClass('hide');var emailID=dojo.byId('emailId_already_reg_error');emailID.innerHTML=serviceResponse.emailId;}
cursor_clear();var rewardsForm=document.forms['Rewards'];rewardsForm.member_id.disabled=true;},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"MattelCheckRewardEnrollment",actionId:"MattelCheckRewardEnrollment",url:"MattelCheckLoyaltyAccount",formId:"",successHandler:function(serviceResponse){if(serviceResponse.membershipAccountFound){console.info("This email"+serviceResponse.emailId+"is already associated with an existing AG Rewards account");MessageHelper.formErrorHandleClient(document.getElementById("Register").logonIdDisplay.id,"This email address is already associated with an existing AG Rewards account.Please enter a different email address.");cursor_clear();}else{if(document.getElementById("Register")!=null)
document.getElementById("Register").submit();else
{if(document.getElementById("confirmationPage_Register")!=null)
document.getElementById("confirmationPage_Register").submit();}
cursor_clear();}}}),wc.service.declare({id:"MattelGetCatalogEntryDetailsByIDAddOns",actionId:"MattelGetCatalogEntryDetailsByIDAddOns",url:getAbsoluteURL()+"GetCatalogEntryDetailsByIDView",formId:"",successHandler:function(serviceResponse){console.info("catEntry Id: "+serviceResponse.catalogEntry);console.info(serviceResponse.catalogEntry);console.info(serviceResponse.counter);MattelAddOnServicesJS.updateAddOnPrice(serviceResponse.catalogEntry,serviceResponse.counter);},failureHandler:function(serviceResponse){console.info(serviceResponse);if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"MattelEnableDeletedShippingAddressCmd",actionId:"MattelEnableDeletedShippingAddressCmd",url:"MattelEnableDeletedShippingAddressCmd",formId:"",successHandler:function(serviceResponse){console.log("The shipping address has been re-enabled");},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){var parameters={};parameters.errorMessage=serviceResponse.errorMessage;}}}),wc.service.declare({id:"AjaxCheckUserMembershipStatus",actionId:"AjaxCheckUserMembershipStatus",url:getAbsoluteURL()+"AjaxCheckUserMembershipStatus",formId:"",successHandler:function(serviceResponse){if(serviceResponse.userType=='Guest'){var url="AjaxLogonForm?langId="+WCParamJS.langId
+"&storeId="+WCParamJS.storeId
+"&catalogId="+WCParamJS.catalogId
+"&collectorAccount=true"
+"&partNumber="+serviceResponse.partNumber
+"&from=membership"
+"&tier="+serviceResponse.tier;document.location.href=appendWcCommonRequestParameters(url);}
else if(serviceResponse.userType=='OneStore'){CollectorMembershipJS.showDialog(serviceResponse.partNumber);}
else if(serviceResponse.userType=='Collectors'){CollectorMembershipJS.showDialog(serviceResponse.partNumber,true);}
cursor_clear();},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxUserRegistrationUpdate",actionId:"AjaxUserRegistrationUpdate",url:getAbsoluteURL()+"AjaxUserRegistrationUpdate",formId:"",successHandler:function(serviceResponse){var params=[];CollectorMembershipDialog.onClose();if(ServicesDeclarationJS.partNumber!=''&&ServicesDeclarationJS.partNumber!='TIER1'){params.storeId=WCParamJS.storeId;params.catalogId=WCParamJS.catalogId;params.langId=WCParamJS.langId;params.orderId=".";params.inventoryValidation="true";params.partNumber=ServicesDeclarationJS.partNumber;params.quantity=1;cursor_clear();wc.service.invoke("AddOrderItem1",params);}else{MessageHelper.displayStatusMessage("Your registration has been completed.");}},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"MattelProductSwappingCmd",actionId:"MattelProductSwappingCmd",url:getAbsoluteURL()+"MattelProductSwappingCmd",formId:"",successHandler:function(serviceResponse){console.log('Success');},failureHandler:function(serviceResponse){console.log('Failure');}}),wc.service.declare({id:"CheckPromotionCodeValidity",actionId:"AjaxPromotionCodeManage",url:getAbsoluteURL()+"AjaxPromotionCodeManage",formId:"PromotionCodeForm",successHandler:function(serviceResponse){if(!serviceResponse.promotionValid){var params=[];params.storeId=ServicesDeclarationJS.storeId;params.catalogId=ServicesDeclarationJS.catalogId;params.langId=ServicesDeclarationJS.langId;if(document.getElementById("orderItem_1")!=null&&document.getElementById("orderItem_1")!='undefined'){params.orderItemId=document.getElementById("orderItem_1").value;}else if(document.getElementById("orderItemIdforPromo")!=null&&document.getElementById("orderItemIdforPromo")!='undefined'){params.orderItemId=document.getElementById("orderItemIdforPromo").value;}
if(document.getElementById("qty_1")!=null&&document.getElementById("qty_1")!='undefined'){params.quantity=document.getElementById("qty_1").value;}else if(document.getElementById("qtyforPromo")!=null&&document.getElementById("qtyforPromo")!='undefined'){params.quantity=document.getElementById("qtyforPromo").value;}
CheckoutHelperJS.promoCode=serviceResponse.promoCode;if(CheckoutHelperJS.shoppingCartPage){params.calculationUsage="-1,-2,-5,-6,-7";}else{params.calculationUsage="-1,-2,-3,-4,-5,-6,-7";}
params.calculateOrder="1";wc.service.invoke("AjaxUpdateOrderItem",params);MessageHelper.displayErrorMessage(MessageHelper.messages['_ERR_PROMO_VALID']);$('a#singleOrderSummary').attr("style","");}
else{CheckoutHelperJS.checkoutOrder(serviceResponse.promoOrderId,serviceResponse.promoUserType,serviceResponse.promoaddressListForMailNotification,serviceResponse.promoIsQuote);}},failureHandler:function(serviceResponse){var errPromoEmailFlag=false;if(serviceResponse.errorMessageKey=='_ERR_INVALID_PROMO_EMAIL'||serviceResponse.errorMessageKey=='_ERR_ENTER_PROMO_EMAIL'){errPromoEmailFlag=true;}
if(serviceResponse.errorMessageKey!=null&&errPromoEmailFlag){if(serviceResponse.errorMessageKey=='_ERR_ENTER_PROMO_EMAIL'){dojo.byId("promoCodeEmailValue").style.display='block';if(sfIndicator=='AG'){dojo.byId("promoCode").disabled=true;dojo.byId("WC_PromotionCodeDisplay_links_1").display='none';}}
MessageHelper.formErrorHandleClient("promoCodeEmailValue",MessageHelper.messages[serviceResponse.errorMessageKey]);}
else if(serviceResponse.errorMessageKey=='_ERR_GENERIC'){MessageHelper.displayErrorMessage(MessageHelper.messages['_ERR_PROMO_VALID']);}
else if(serviceResponse.errorMessageKey=="_ERR_USER_AUTHORITY"){location.reload();}
else{if(serviceResponse.errorMessageKey&&!errPromoEmailFlag){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);dojo.byId("promoCodeEmailValue").style.display='none';if(sfIndicator=='AG'){dojo.byId("promoCode").disabled=false;dojo.byId("WC_PromotionCodeDisplay_links_1").display='block';dojo.byId("promoCode").name="promoCode";dojo.byId("rewardCode").name="rewardCode";}}}
cursor_clear();var params=[];params.storeId=ServicesDeclarationJS.storeId;params.catalogId=ServicesDeclarationJS.catalogId;params.langId=ServicesDeclarationJS.langId;if(document.getElementById("orderItem_1")!=null&&document.getElementById("orderItem_1")!='undefined'){params.orderItemId=document.getElementById("orderItem_1").value;}else if(document.getElementById("orderItemIdforPromo")!=null&&document.getElementById("orderItemIdforPromo")!='undefined'){params.orderItemId=document.getElementById("orderItemIdforPromo").value;}
if(document.getElementById("qty_1")!=null&&document.getElementById("qty_1")!='undefined'){params.quantity=document.getElementById("qty_1").value;}else if(document.getElementById("qtyforPromo")!=null&&document.getElementById("qtyforPromo")!='undefined'){params.quantity=document.getElementById("qtyforPromo").value;}
CheckoutHelperJS.promoCode=serviceResponse.promoCode;if(CheckoutHelperJS.shoppingCartPage){params.calculationUsage="-1,-2,-5,-6,-7";}else{params.calculationUsage="-1,-2,-3,-4,-5,-6,-7";}
params.calculateOrder="1";wc.service.invoke("AjaxUpdateOrderItem",params);$('a#singleOrderSummary').attr("style","");}}),wc.service.declare({id:"globalLoginAjaxLogon",actionId:"globalLoginAjaxLogon",url:getAbsoluteURL()+"AjaxLogon",formId:"",successHandler:function(serviceResponse){var errorMessage="";if(serviceResponse.ErrorCode!=null){var errMessage;if(serviceResponse.passwordRetries==4){errMessage=MessageHelper.messages["ERROR_FOR_LAST_TWO_ATTEMPT"];}else{errMessage=MessageHelper.messages["ERROR_FOR_INVALID_CREDENTIALS"];}
if(document.getElementById('logonErrorMessageForAjax')!=null){document.getElementById('logonErrorMessageForAjax').style.display='block';document.getElementById('logonErrorMessageForAjax').innerHTML=errMessage;}
cursor_clear();}else{try{if(typeof utag!=='undefined'&&utag!=null&&typeof tealium_event!=='undefined'&&tealium_event!=null){utag.link(tealium_event.sign_in);}}catch(err){console.debug(err);}
var url=serviceResponse.URL[0].replace(/&amp;/g,'&');var languageId=serviceResponse.langId;if(languageId!=null&&document.getElementById('langSEO'+languageId)!=null){var browserURL=document.location.href;var currentLangSEO='/'+document.getElementById('currentLanguageSEO').value+'/';if(browserURL.indexOf(currentLangSEO)!=-1){var preferLangSEO='/'+document.getElementById('langSEO'+languageId).value+'/';var query=url.substring(url.indexOf('?')+1,url.length);var parameters=dojo.queryToObject(query);if(parameters["URL"]!=null){var redirectURL=parameters["URL"];var query2=redirectURL.substring(redirectURL.indexOf('?')+1,redirectURL.length);var parameters2=dojo.queryToObject(query2);if(parameters2["URL"]!=null){var finalRedirectURL=parameters2["URL"];if(finalRedirectURL.indexOf(currentLangSEO)!=-1){finalRedirectURL=finalRedirectURL.replace(currentLangSEO,preferLangSEO);parameters2["URL"]=finalRedirectURL;}
query2=dojo.objectToQuery(parameters2);redirectURL=redirectURL.substring(0,redirectURL.indexOf('?'))+'?'+query2;}else{redirectURL=redirectURL.toString().replace(currentLangSEO,preferLangSEO);}
parameters["URL"]=redirectURL;}
query=dojo.objectToQuery(parameters);url=url.substring(0,url.indexOf('?'))+'?'+query;}else{if(url.indexOf('?')!=-1){var query=url.substring(url.indexOf('?')+1,url.length);var parameters=dojo.queryToObject(query);if(parameters["langId"]!=null){parameters["langId"]=languageId;var query2=dojo.objectToQuery(parameters);url=url.substring(0,url.indexOf('?'))+'?'+query2;}else{url=url+"&langId="+languageId;}}else{url=url+"?langId="+languageId;}}
url=url+"&storeId="
+WCParamJS.storeId+"&catalogId="+WCParamJS.catalogId;}
else{if(url.indexOf('?')!=-1){var query=url.substring(url.indexOf('?')+1,url.length);var parameters=dojo.queryToObject(query);if(parameters["langId"]==null){url=url+"&langId="+languageId;}
if(parameters["storeId"]==null){url=url+"&storeId="+WCParamJS.storeId;}
if(parameters["catalogId"]==null){url=url+"&catalogId="+WCParamJS.catalogId;}}else{url=url+"?langId="+WCParamJS.langId+"&storeId="+WCParamJS.storeId+"&catalogId="+WCParamJS.catalogId;}}
if(serviceResponse.mergeCartQtyExceeded=="true")
url=url+"&mergeCartQtyExceeded=true";window.location=url;}},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"ContactMediaReqService",actionId:"ContactUsCustomerService",url:getAbsoluteURL()+"MattelMediaReqEmailCmd",formId:"",successHandler:function(serviceResponse){console.info("SUCESS*******************************");$('#Mediaform').remove();$('.sectionarea2').remove();$('#SuccessMsg').css('display','block');cursor_clear();},failureHandler:function(serviceResponse){console.info(serviceResponse);if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxCheckUserType",actionId:"AjaxCheckUserType",url:getAbsoluteURL()+"AjaxCheckUserMembershipStatus",formId:"",successHandler:function(serviceResponse){if(serviceResponse.userType=='Guest'){var url="AjaxLogonForm?langId="+WCParamJS.langId
+"&storeId="+WCParamJS.storeId
+"&catalogId="+WCParamJS.catalogId;document.location.href=appendWcCommonRequestParameters(url);}else{cursor_clear();var contextValues=shoppingListJS.setCommonParams();contextValues.productName=serviceResponse.productName[0];contextValues.messageType='';contextValues.sfIndicator=serviceResponse.sfIndicator;if(serviceResponse.fromPage[0]=='categoryPage'||serviceResponse.fromPage[0]=='wishlist'){contextValues.productId=serviceResponse.productId[0];wc.render.updateContext('HaveItWantItWishlistDisplay_Context',contextValues);}else{var resolvedCatEntry=productDisplayJS.resolveSKUBeforeAdd2List("entitledItem_"+serviceResponse.productId[0]);if(resolvedCatEntry){contextValues.productId=resolvedCatEntry;wc.render.updateContext('HaveItWantItWishlistDisplay_Context',contextValues);}}}}})});if(typeof(SearchJS)=="undefined"||SearchJS==null||!SearchJS){SearchJS={autoSuggestTimer:-1,autoSuggestKeystrokeDelay:400,autoSuggestHover:false,autoSuggestPreviousTerm:"",autoSuggestURL:"",autoSelectOption:-1,historyIndex:-1,retrievedCachedSuggestions:false,TOTAL_SUGGESTED:4,TOTAL_HISTORY:2,AUTOSUGGEST_THRESHOLD:0,DYNAMIC_AUTOSUGGEST_THRESHOLD:0,CACHED_AUTOSUGGEST_OFFSET:1000,END_OF_LIST:false,STATIC_CONTENT_SECTION_DIV:["autoSuggestStatic_1","autoSuggestStatic_2","autoSuggestStatic_3"],staticContentHeaderHistory:"",CachedSuggestionsURL:"",SearchAutoSuggestServletURL:"",searchDepartmentHoverTimeout:"",searchSuggestionHoverTimeout:"",mouseDownConnectHandle:null,searchTerm:"",searchDepartmentSelect:function(categoryId,lel){byId('searchDepartmentLabel').innerHTML=lel.innerHTML;byId('search_categoryId').value=categoryId;this.hideSearchDepartmentList();return false;},cancelEvent:function(e){if(e.stopPropagation){e.stopPropagation();}
if(e.preventDefault){e.preventDefault();}
e.cancelBubble=true;e.cancel=true;e.returnValue=false;},searchDepartmentKeyPressed:function(event,pos,size,categoryId,item){if(event.keyCode==13){this.searchDepartmentSelect(categoryId,item);var scrElement=document.getElementById("mobileSearchDropdown");if(scrElement!=null&&scrElement.style.display=='block'){dojo.byId("MobileSimpleSearchForm_SearchTerm").focus();}else{document.CatalogSearchForm.searchTerm.focus();}}else if(event.keyCode==38){if(pos!=0){dojo.byId('searchDepartmentList_'+(pos-1)).focus();this.cancelEvent(event);}}else if(event.keyCode==40){if(pos!=size){dojo.byId('searchDepartmentList_'+(pos+1)).focus();this.cancelEvent(event);}}else if(event.keyCode==27){var scrElement=document.getElementById("mobileSearchDropdown");if(scrElement!=null&&scrElement.style.display=='block'){dojo.byId("MobileSimpleSearchForm_SearchTerm").focus();}else{document.CatalogSearchForm.searchTerm.focus();}
this.hideSearchDepartmentList();}else if(event.shiftKey&&event.keyCode==9){var scrElement=document.getElementById("mobileSearchDropdown");if(scrElement!=null&&scrElement.style.display=='block'){dojo.byId("MobileSimpleSearchForm_SearchTerm").focus();}else{document.CatalogSearchForm.searchTerm.focus();}
this.cancelEvent(event);this.hideSearchDepartmentList();}else if(event.keyCode==9){dojo.byId('search_submit').focus();this.cancelEvent(event);this.hideSearchDepartmentList();}
return false;},hideSearchDepartmentList:function(){byId('searchDepartmentList').style.display="none";},init:function(){dojo.connect(document.CatalogSearchForm.searchTerm,"onfocus",SearchJS,SearchJS._onFocus);dojo.connect(document.CatalogSearchForm.searchTerm,"onkeydown",SearchJS,SearchJS._onKeyDown);dojo.connect(document.CatalogSearchForm.searchTerm,"onkeyup",SearchJS,SearchJS._onKeyUp);dojo.connect(document.getElementById("searchDropdown"),"onkeyup",SearchJS,SearchJS._onKeyTab);this.staticContentHeaderHistory=storeNLS["HISTORY"];},showSearchComponent:function(){var srcElement=document.getElementById("searchDropdown");if(srcElement!=null){srcElement.style.display='block';}},hideSearchComponent:function(){var srcElement=document.getElementById("searchDropdown");if(srcElement!=null){srcElement.style.display='none';}},_showMobileSearchComponent:function(){var srcElement=document.getElementById("mobileSearchDropdown");if(srcElement!=null){if(srcElement.style.display=="block"){DepartmentJS.close('mobileSearchDropdown');srcElement.style.display='none';}
else
{dojo.query(".subDeptDropdown ").forEach(function(node){DepartmentJS.close(node.id);});DepartmentJS.close("departmentsDropdown");srcElement.style.display='block';}}},setCachedSuggestionsURL:function(url){this.CachedSuggestionsURL=getAbsoluteURL()+url;},setAutoSuggestURL:function(url){this.SearchAutoSuggestServletURL=getAbsoluteURL()+url;},_onFocus:function(evt){this.showSearchComponent();this.retrieveCachedSuggestions();},_MobileonFocus:function(evt){this.showSearchComponent();this.retrieveCachedSuggestions();},_MobileonBlur:function(evt){clearTimeout(this.searchSuggestionHoverTimeout);this.searchSuggestionHoverTimeout=setTimeout("SearchJS.showAutoSuggest(false)",100);},_onKeyPress:function(evt){return evt.keyCode!=dojo.keys.ENTER;},_onKeyDown:function(evt){if(evt.keyCode==dojo.keys.ENTER){this._handleEnterKey();this.cancelEvent(evt);}
else if(evt.keyCode=='9'||evt.which=='9'){clearTimeout(this.searchSuggestionHoverTimeout);this.searchSuggestionHoverTimeout=setTimeout("SearchJS.showAutoSuggest(false)",200);}},_onKeyUp:function(evt){var srcElement=document.getElementById("searchDropdown");srcElement.style.display='block';this.doAutoSuggest(evt,this.SearchAutoSuggestServletURL,document.CatalogSearchForm.searchTerm.value);},_onKeyTab:function(evt){if(evt.keyCode=='9'||evt.which=='9'){dojo.byId("searchFilterButton").focus();}},_MobileonKeyUp:function(evt){var srcElement=document.getElementById("mobileSearchDropdown");srcElement.style.display='block';this.doAutoSuggest(evt,this.SearchAutoSuggestServletURL,dojo.byId("MobileSimpleSearchForm_SearchTerm").value);},_handleEnterKey:function(){document.CatalogSearchForm.searchTerm.value=trim(document.CatalogSearchForm.searchTerm.value);if(document.CatalogSearchForm.searchTerm.value.length>0){if(this.END_OF_LIST){this.gotoAdvancedSearch(byId("advancedSearch").href);}
else if(this.autoSuggestURL!=""&&this.autoSuggestURL!=(document.location.href+"#")){document.location.href=appendWcCommonRequestParameters(this.autoSuggestURL);}
else{document.CatalogSearchForm.searchTerm.value=trim(document.CatalogSearchForm.searchTerm.value);submitSpecifiedForm(document.CatalogSearchForm);}}},_onClick:function(evt){document.CatalogSearchForm.searchTerm.value=trim(document.CatalogSearchForm.searchTerm.value);if(document.CatalogSearchForm.searchTerm.value.length>0){if(typeof TealeafWCJS!="undefined"){TealeafWCJS.processDOMEvent(evt);}
submitSpecifiedForm(document.CatalogSearchForm);}
return false;},_MobileonClick:function(evt){document.MobileCatalogSearchForm.searchTerm.value=trim(document.MobileCatalogSearchForm.searchTerm.value);if(document.MobileCatalogSearchForm.searchTerm.value.length>0){if(typeof TealeafWCJS!="undefined"){TealeafWCJS.processDOMEvent(evt);}
submitSpecifiedForm(document.MobileCatalogSearchForm);}
return false;},doDynamicAutoSuggest:function(url,searchTerm,showHeader){if(this.autoSuggestTimer!=-1){clearTimeout(this.autoSuggestTimer);this.autoSuggestTimer=-1;};this.autoSuggestTimer=setTimeout(function(){wc.render.getRefreshControllerById("AutoSuggestDisplayController").url=url+"&term="+encodeURIComponent(searchTerm)+"&showHeader="+showHeader;console.debug("update autosuggest "+url);wc.render.updateContext("AutoSuggest_Context",{});this.autoSuggestTimer=-1;},this.autoSuggestKeystrokeDelay);},doDynamicFavouriteDollAutoSuggest:function(url,searchTerm,showHeader){if(this.autoSuggestTimer!=-1){clearTimeout(this.autoSuggestTimer);this.autoSuggestTimer=-1;};this.autoSuggestTimer=setTimeout(function(){wc.render.getRefreshControllerById("AutoSuggestProductDisplayController").url=url+"&term="+encodeURIComponent(searchTerm)+"&showHeader="+showHeader;console.debug("update autosuggest Product"+url);wc.render.updateContext("AutoSuggestProduct_Context",{});this.autoSuggestTimer=-1;},this.autoSuggestKeystrokeDelay);},gotoAdvancedSearch:function(url){var searchTerm=byId("SimpleSearchForm_SearchTerm").value;document.location.href=appendWcCommonRequestParameters(url)+'&searchTerm='+searchTerm;},showAutoSuggest:function(display){var autoSuggest_Result_div=document.getElementById("autoSuggest_Result_div");if(dojo.isIE<7){var autoSuggest_content_div=document.getElementById("autoSuggest_content_div");var autoSuggestDropDownIFrame=document.getElementById("autoSuggestDropDownIFrame");}
if(autoSuggest_Result_div!=null&&typeof autoSuggest_Result_div!='undefined'){if(display){switch(sfIndicator){case'AG':{var delta=42;break;}
case'BA':{var delta=42;break;}
case'FP':{var delta=41;break;}
case'HW':{var delta=23;break;}
case'SM':{var delta=36;break;}
default:{break}}
if(Modernizr.touch)$('.search-dropdown-menu').height($(autoSuggest_Result_div).height()+delta);autoSuggest_Result_div.style.display="block";if(dojo.isIE<7){autoSuggestDropDownIFrame.style.height=autoSuggest_content_div.scrollHeight;autoSuggestDropDownIFrame.style.display="block";}
this.registerMouseDown();}
else{if(dojo.isIE<7){autoSuggestDropDownIFrame.style.display="none";autoSuggestDropDownIFrame.style.height=0;}
if(Modernizr.touch)$('.search-dropdown-menu').removeAttr('style');autoSuggest_Result_div.style.display="none";this.unregisterMouseDown();}}
else{if(Modernizr.touch)$('.search-dropdown-menu').removeAttr('style');this.unregisterMouseDown();}},showProductAutoSuggest:function(display){var autoSuggest_Result_div=document.getElementById("autoSuggestProduct_Result_div");if(dojo.isIE<7){var autoSuggest_content_div=document.getElementById("autoSuggestProduct_Result_div");var autoSuggestDropDownIFrame=document.getElementById("autoSuggestDropDownIFrame");}
if(autoSuggest_Result_div!=null&&typeof autoSuggest_Result_div!='undefined'){if(display){switch(sfIndicator){case'AG':{var delta=42;break;}
case'BA':{var delta=42;break;}
case'FP':{var delta=41;break;}
case'HW':{var delta=23;break;}
case'SM':{var delta=36;break;}
default:{break}}
if(Modernizr.touch)$('.search-dropdown-menu').height($(autoSuggest_Result_div).height()+delta);autoSuggest_Result_div.style.display="block";if(dojo.isIE<7){autoSuggestDropDownIFrame.style.height=autoSuggest_content_div.scrollHeight;autoSuggestDropDownIFrame.style.display="block";}
this.registerMouseDown();}
else{if(dojo.isIE<7){autoSuggestDropDownIFrame.style.display="none";autoSuggestDropDownIFrame.style.height=0;}
if(Modernizr.touch)$('.search-dropdown-menu').removeAttr('style');autoSuggest_Result_div.style.display="none";this.unregisterMouseDown();}}
else{if(Modernizr.touch)$('.search-dropdown-menu').removeAttr('style');this.unregisterMouseDown();}},showAutoSuggestIfResults:function(){var scrElement=document.getElementById("mobileSearchDropdown");if(typeof(staticContent)!="undefined"&&document.getElementById(this.STATIC_CONTENT_SECTION_DIV[0]).innerHTML==""&&document.getElementById("autoSuggestHistory").innerHTML==""&&document.getElementById("dynamicAutoSuggestTotalResults")==null){this.showAutoSuggest(false);}
else if(scrElement!=null&&scrElement.style.display=='block')
{if(document.getElementById("MobileSimpleSearchForm_SearchTerm").value.length<=this.AUTOSUGGEST_THRESHOLD)
{this.showAutoSuggest(false);}
else
{this.showAutoSuggest(true);}}
else{if(document.CatalogSearchForm.searchTerm.value.length<=this.AUTOSUGGEST_THRESHOLD)
{this.showAutoSuggest(false);}
else
{this.showAutoSuggest(true);}}},showProductAutoSuggestIfResults:function(){var scrElement=document.getElementById("mobileSearchDropdown");if(typeof(staticContent)!="undefined"&&document.getElementById(this.STATIC_CONTENT_SECTION_DIV[0]).innerHTML==""&&document.getElementById("autoSuggestHistory").innerHTML==""&&document.getElementById("dynamicAutoSuggestTotalResults")==null){this.showAutoSuggest(false);}
else if(scrElement!=null&&scrElement.style.display=='block')
{if(document.getElementById("MobileSimpleSearchForm_SearchTerm").value.length<=this.AUTOSUGGEST_THRESHOLD)
{this.showProductAutoSuggest(false);}
else
{this.showProductAutoSuggest(true);}}
else{if(document.FavouriteDollSearchForm.favouriteDollSearchTerm.value.length<=this.AUTOSUGGEST_THRESHOLD)
{this.showProductAutoSuggest(false);}
else
{this.showProductAutoSuggest(true);}}},selectAutoSuggest:function(term){var scrElement=document.getElementById("mobileSearchDropdown");if(scrElement!=null&&scrElement.style.display=='block'){var searchBox=document.getElementById("MobileSimpleSearchForm_SearchTerm");}else{var searchBox=document.CatalogSearchForm.searchTerm;}
searchBox.value=term;searchBox.focus();this.autoSuggestPreviousTerm=term;if(typeof TealeafWCJS!="undefined"){TealeafWCJS.createExplicitChangeEvent(searchBox);}
submitSpecifiedForm(document.CatalogSearchForm);try{if(tealium_event&&typeof utag!='undefined'&&utag!=null&&typeof tealium_event!=='undefined'&&tealium_event!=null){tealium_event.auto_suggest.search_keyword=searchTerm;tealium_event.auto_suggest.search_keyword_displayed=term;utag.link(tealium_event.auto_suggest);}}catch(err){console.debug(err);}},highLightSelection:function(state,index){var selection=document.getElementById("autoSelectOption_"+index);if(selection!=null&&typeof selection!='undefined'){if(state){selection.className="autoSuggestSelected";var scrElement=document.getElementById("mobileSearchDropdown");if(scrElement!=null&&scrElement.style.display=='block'){var searchBox=document.getElementById("MobileSimpleSearchForm_SearchTerm");}else{var searchBox=document.CatalogSearchForm.searchTerm;}
searchBox.setAttribute("aria-activedescendant","suggestionItem_"+index);var totalDynamicResults=document.getElementById("dynamicAutoSuggestTotalResults");if((totalDynamicResults!=null&&typeof totalDynamicResults!='undefined'&&index<totalDynamicResults.value)||(index>=this.historyIndex)){searchBox.value=selection.title;this.autoSuggestPreviousTerm=selection.title;}
this.autoSuggestURL=selection.href;}
else{selection.className="";}
return true;}
else{return false;}},enableAutoSelect:function(index){this.highLightSelection(false,this.autoSelectOption);var item=document.getElementById('autoSelectOption_'+index);item.className="autoSuggestSelected";this.autoSelectOption=index;},resetAutoSuggestKeyword:function(){var originalKeyedSearchTerm=document.getElementById("autoSuggestOriginalTerm");if(originalKeyedSearchTerm!=null&&typeof originalKeyedSearchTerm!='undefined'){var scrElement=document.getElementById("mobileSearchDropdown");if(scrElement!=null&&scrElement.style.display=='block')
{var searchBox=document.getElementById("MobileSimpleSearchForm_SearchTerm");}else{var searchBox=document.CatalogSearchForm.searchTerm;}
searchBox.value=originalKeyedSearchTerm.value;this.autoSuggestPreviousTerm=originalKeyedSearchTerm.value;}},clearAutoSuggestResults:function(){for(var i=0;i<staticContent.length;i++){document.getElementById(this.STATIC_CONTENT_SECTION_DIV[i]).innerHTML="";}
this.autoSuggestPreviousTerm="";this.autoSuggestURL="";document.getElementById("autoSuggestDynamic_Result_div").innerHTML="";this.showAutoSuggest(false);},doAutoSuggest:function(event,url,searchTerm){if(searchTerm.length<=this.AUTOSUGGEST_THRESHOLD){this.showAutoSuggest(false);}
if(event.keyCode==dojo.keys.ENTER){return;}
if(event.keyCode==dojo.keys.TAB){this.autoSuggestHover=true;return;}
if(event.keyCode==dojo.keys.ESCAPE){this.showAutoSuggest(false);return;}
if(event.keyCode==dojo.keys.UP_ARROW){var totalDynamicResults=document.getElementById("dynamicAutoSuggestTotalResults");if(this.END_OF_LIST){dojo.removeClass("autoSuggestAdvancedSearch","autoSuggestSelected");this.END_OF_LIST=false;this.autoSelectOption--;if(!this.highLightSelection(true,this.autoSelectOption)){if(this.autoSelectOption==this.CACHED_AUTOSUGGEST_OFFSET&&totalDynamicResults!=null&&typeof totalDynamicResults!='undefined'){this.autoSelectOption=totalDynamicResults.value-1;this.highLightSelection(true,this.autoSelectOption);}}}
else if(this.highLightSelection(true,this.autoSelectOption-1)){this.highLightSelection(false,this.autoSelectOption);if(this.autoSelectOption==this.historyIndex){this.resetAutoSuggestKeyword();}
this.autoSelectOption--;}
else if(this.autoSelectOption==this.CACHED_AUTOSUGGEST_OFFSET&&totalDynamicResults!=null&&typeof totalDynamicResults!='undefined'){this.highLightSelection(false,this.CACHED_AUTOSUGGEST_OFFSET);this.autoSelectOption=totalDynamicResults.value-1;this.highLightSelection(true,this.autoSelectOption);}
else{this.highLightSelection(false,this.autoSelectOption);this.autoSelectOption=-1;var originalKeyedSearchTerm=document.getElementById("autoSuggestOriginalTerm");this.resetAutoSuggestKeyword();}
return;}
if(event.keyCode==dojo.keys.DOWN_ARROW){if(this.highLightSelection(true,this.autoSelectOption+1)){this.highLightSelection(false,this.autoSelectOption);this.autoSelectOption++;}
else if(this.autoSelectOption<this.CACHED_AUTOSUGGEST_OFFSET&&this.highLightSelection(true,this.CACHED_AUTOSUGGEST_OFFSET)){this.highLightSelection(false,this.autoSelectOption);this.autoSelectOption=this.CACHED_AUTOSUGGEST_OFFSET;this.resetAutoSuggestKeyword();}
else if(!this.END_OF_LIST){dojo.addClass("autoSuggestAdvancedSearch","autoSuggestSelected");this.highLightSelection(false,this.autoSelectOption);this.autoSelectOption++;this.END_OF_LIST=true;var scrElement=document.getElementById("mobileSearchDropdown");if(scrElement!=null&&scrElement.style.display=='block'){var searchBox=document.getElementById("MobileSimpleSearchForm_SearchTerm");}else{var searchBox=document.CatalogSearchForm.searchTerm;}
searchBox.setAttribute("aria-activedescendant","advancedSearch");}
return;}
if(searchTerm.length>this.AUTOSUGGEST_THRESHOLD&&searchTerm==this.autoSuggestPreviousTerm){return;}
else{this.autoSuggestPreviousTerm=searchTerm;}
if(searchTerm.length<=this.AUTOSUGGEST_THRESHOLD){return;};if(this.autoSuggestTimer!=-1){clearTimeout(this.autoSuggestTimer);this.autoSuggestTimer=-1;}
if(searchTerm!=""){this.autoSelectOption=-1;var hasResults=this.doStaticAutoSuggest(searchTerm);if(searchTerm.length>this.DYNAMIC_AUTOSUGGEST_THRESHOLD){var showHeader=true;this.doDynamicAutoSuggest(url,searchTerm,showHeader);}
else{document.getElementById("autoSuggestDynamic_Result_div").innerHTML="";}}
else{this.clearAutoSuggestResults();}},tokenizeForBidi:function(displayName,searchName,searchTerm,searchTermLower){var tokens=displayName.split(" > ");var html="";var str="";if(tokens.length>0){html=html+"<div class='category_list'>";for(i=0;i<tokens.length;i++){if(i!=0){html=html+"<span class='gt'>&nbsp; > &nbsp;</span>";}
if(i==tokens.length-1){var index=searchName.toLowerCase().indexOf(searchTermLower);var subStringBefore=searchName.substr(0,index);var subStringAfter=searchName.substr(index+searchTerm.length);var highLighted="<span class='highlight'>"+searchTerm+"</span>";str=subStringBefore+highLighted+subStringAfter;}
else{str=tokens[i];}
html=html+str;}
html=html+"</div>";}
return html;},doStaticAutoSuggest:function(searchTerm){var resultList=["","","","","",""];var emptyCell=0;var searchTermLower=searchTerm.toLowerCase();var listCount=this.CACHED_AUTOSUGGEST_OFFSET;var divStart="<div class='list_section'><div";var divEnd="</div></div>";for(var i=0;i<staticContent.length;i++){var count=0;for(var j=0;j<staticContent[i].length;j++){var searchName=staticContent[i][j][0];var searchURL=staticContent[i][j][1];var displayName=staticContent[i][j][2];var index=searchName.toLowerCase().indexOf(searchTermLower);if(index!=-1){var htmlDisplayName=this.tokenizeForBidi(displayName,searchName,searchTerm,searchTermLower);resultList[i]=resultList[i]+"<ul class='autoSuggestDivNestedList'><li id='suggestionItem_"+listCount+"' role='listitem' tabindex='-1'><a id='autoSelectOption_"+listCount+"' title='"+searchName+"' onmouseout='this.className=\"\"; this.autoSuggestURL=\"\";' onclick='SearchJS.hideSearchComponent();' onmouseover='SearchJS.enableAutoSelect("+listCount+"); this.autoSuggestURL=this.href;' href=\""+searchURL+"\">"+htmlDisplayName+"</a></li></ul>";count++;listCount++;if(count>=this.TOTAL_SUGGESTED){break;}}}}
for(var i=0;i<staticContent.length;i++){document.getElementById(this.STATIC_CONTENT_SECTION_DIV[i]).innerHTML="";if(resultList[i]!=""){var heading="<ul class='autoSuggestDivNestedList'><li class='heading'><span>"+staticContentHeaders[i]+"</span></li></ul>";document.getElementById(this.STATIC_CONTENT_SECTION_DIV[emptyCell]).innerHTML=heading+divStart+" role='list' title='"+staticContentHeaders[i]+"' aria-label='"+staticContentHeaders[i]+"'>"+resultList[i]+divEnd;emptyCell++;}}
var historyList="";var searchHistorySection=document.getElementById("autoSuggestHistory");searchHistorySection.innerHTML="";var historyArray=new Array();this.historyIndex=listCount;var searchHistoryCookie=getCookie("searchTermHistory");if(typeof(searchHistoryCookie)!='undefined'){var termsArray=searchHistoryCookie.split("|");var count=0;for(var i=termsArray.length-1;i>0;i--){var theTerm=termsArray[i];var theLowerTerm=theTerm.toLowerCase();if(theLowerTerm.match("^"+searchTermLower)==searchTermLower){var repeatedTerm=false;for(var j=0;j<historyArray.length;j++){if(historyArray[j]==theLowerTerm){repeatedTerm=true;break;}}
if(!repeatedTerm){if(count>=this.TOTAL_HISTORY){break;}
historyList=historyList+"<ul class='autoSuggestDivNestedList'><li id='suggestionItem_"+listCount+"' role='listitem' tabindex='-1'><a href='#' onmouseout='this.className=\"\"' onmouseover='SearchJS.enableAutoSelect("+listCount+");' onclick='SearchJS.selectAutoSuggest(this.title); return false;' title='"+theTerm+"' id='autoSelectOption_"+listCount+"'><strong>"+searchTerm+"</strong>"+theTerm.substring(searchTerm.length,theTerm.length)+"</a></li></ul>";historyArray.push(theLowerTerm);count++;listCount++;}}}}
if(historyList!=""){var heading="<ul class='autoSuggestDivNestedList'><li class='heading'><span>"+this.staticContentHeaderHistory+"</span></li></ul>"
searchHistorySection.innerHTML=heading+divStart+" title='"+this.staticContentHeaderHistory+"'>"+historyList+divEnd;emptyCell++;}
if(emptyCell>0){this.showAutoSuggest(true);return true;}
return false;},retrieveCachedSuggestions:function(){if(!this.retrievedCachedSuggestions){wc.render.getRefreshControllerById("AutoSuggestCachedSuggestionsController").url=this.CachedSuggestionsURL;console.debug("update cache sugg "+this.CachedSuggestionsURL);wc.render.updateContext("CachedSuggestions_Context",{});}},updateSearchTermHistoryCookie:function(updatedSearchTerm){var cookieKey="searchTermHistory";var cookieValue="|"+updatedSearchTerm;var searchTermHistoryCookie=getCookie(cookieKey);if(typeof(searchTermHistoryCookie)!='undefined'){cookieValue=dojo.cookie(cookieKey)+cookieValue;}
dojo.cookie(cookieKey,cookieValue,{path:'/'});},updateSearchTermHistoryCookieAndRedirect:function(updatedSearchTerm,redirectURL){this.updateSearchTermHistoryCookie(updatedSearchTerm);document.location.href=appendWcCommonRequestParameters(redirectURL);},isValidNumber:function(n){return!isNaN(parseFloat(n))&&isFinite(n)&&n>=0;},validateForm:function(form){form["minPrice"].value=trim(form["minPrice"].value);form["maxPrice"].value=trim(form["maxPrice"].value);var minValue=form["minPrice"].value;var maxValue=form["maxPrice"].value;var minIsValid=this.isValidNumber(minValue);var maxIsValid=this.isValidNumber(maxValue);if(minValue.length>0&&!minIsValid){MessageHelper.formErrorHandleClient(form["minPrice"].id,MessageHelper.messages["EDPPaymentMethods_AMOUNT_NAN"]);return false;}
else if(maxValue.length>0&&!maxIsValid){MessageHelper.formErrorHandleClient(form["maxPrice"].id,MessageHelper.messages["EDPPaymentMethods_AMOUNT_NAN"]);return false;}
else if(minValue.length>0&&maxValue.length>0&&parseFloat(minValue)>parseFloat(maxValue)){MessageHelper.formErrorHandleClient(form["maxPrice"].id,MessageHelper.messages["ERROR_PRICE_RANGE"]);return false;}
form["searchTerm"].value=trim(form["searchTerm"].value);form["filterTerm"].value=trim(form["filterTerm"].value);form["manufacturer"].value=trim(form["manufacturer"].value);var searchTerm=form["searchTerm"].value;var filterTerm=form["filterTerm"].value;var manufacturer=form["manufacturer"].value;if(searchTerm.length==0&&filterTerm.length==0&&manufacturer.length==0){MessageHelper.formErrorHandleClient(form["searchTerm"].id,MessageHelper.messages["ERROR_EMPTY_SEARCH_FIELDS"]);return false;}
processAndSubmitForm(form);},registerMouseDown:function(){if(this.mouseDownConnectHandle==null){this.mouseDownConnectHandle=dojo.connect(document.documentElement,"onmousedown",this,"handleMouseDown");}},unregisterMouseDown:function(){if(this.mouseDownConnectHandle!=null){dojo.disconnect(this.mouseDownConnectHandle);this.mouseDownConnectHandle=null;}},handleMouseDown:function(evt){var node=evt.target;if(node!=document.documentElement){var searchDropdown=document.getElementById("searchDropdown");var searchTerm=document.CatalogSearchForm.searchTerm;var close=true;while(node){if(node==searchDropdown||node==searchTerm){close=false;break;}
node=node.parentNode;}
if(close){this.showAutoSuggest(false);}}},addFavouriteDollProduct:function(productDescription){productDescription=productDescription.replace('|apos|',"'");if(dojo.byId('searchForDoll')){dojo.byId('searchForDoll').value=productDescription;}
this.clearProductAutoSuggestResults();},showHide:function(showDiv,hideDiv){var showElement=document.getElementById(showDiv);if(showElement!=null){showElement.style.display='block';}
var hideElement=document.getElementById(hideDiv);if(hideElement!=null){hideElement.style.display='none';}},clearProductAutoSuggestResults:function(){for(var i=0;i<staticContent.length;i++){document.getElementById(this.STATIC_CONTENT_SECTION_DIV[i]).innerHTML="";}
this.autoSuggestPreviousTerm="";this.autoSuggestURL="";document.getElementById("autoSuggestProductDynamic_Result_div").innerHTML="";this.showProductAutoSuggest(false);},};dojo.addOnLoad(function(){wc.render.declareContext("AutoSuggest_Context",null,"");wc.render.declareContext("AutoSuggestProduct_Context",null,"");wc.render.declareContext("CachedSuggestions_Context",null,"");wc.render.declareRefreshController({id:"AutoSuggestCachedSuggestionsController",renderContext:wc.render.getContextById("CachedSuggestions_Context"),url:"",formId:"",renderContextChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;widget.refreshGet(renderContext.properties);},postRefreshHandler:function(widget){var controller=this;var renderContext=this.renderContext;var response=document.getElementById('cachedSuggestions');if(response==null){document.getElementById("autoSuggestCachedSuggestions_div").innerHTML="";}
else{var scripts=response.getElementsByTagName("script");var j=scripts.length;for(var i=0;i<j;i++){var newScript=document.createElement('script');newScript.type="text/javascript";newScript.text=scripts[i].text;document.getElementById('autoSuggestCachedSuggestions_div').appendChild(newScript);}
SearchJS.retrievedCachedSuggestions=true;var scrElement=document.getElementById("mobileSearchDropdown");if(scrElement!=null&&scrElement.style.display=='block')
{searchTerm=document.getElementById("MobileSimpleSearchForm_SearchTerm").value;}
else
{searchTerm=document.CatalogSearchForm.searchTerm.value;}
if(searchTerm.length>SearchJS.AUTOSUGGEST_THRESHOLD){SearchJS.doStaticAutoSuggest(searchTerm);}}}});wc.render.declareRefreshController({id:"AutoSuggestDisplayController",renderContext:wc.render.getContextById("AutoSuggest_Context"),url:"",formId:"",renderContextChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;widget.refreshGet(renderContext.properties);},postRefreshHandler:function(widget){var controller=this;var renderContext=this.renderContext;var response=document.getElementById('suggestedKeywordResults');var productsResponse=document.getElementById('suggestedProductsResults');if(response==null&&productsResponse==null){document.getElementById("autoSuggestDynamic_Result_div").innerHTML="";}
SearchJS.showAutoSuggestIfResults();if(typeof tealium_event!='undefined'){if(typeof utag!='undefined'){var numberOfSuggestions=document.getElementById('dynamicAutoSuggestTotalResults').value;var keyword=document.getElementById('autoSuggestOriginalTerm').value;tealium_event.auto_suggest.number_of_results.push(numberOfSuggestions);tealium_event.auto_suggest.search_term.push(keyword);tealium_event.auto_suggest.search_keyword=keyword;utag.link(tealium_event.auto_suggest);}}}});wc.render.declareRefreshController({id:"AutoSuggestProductDisplayController",renderContext:wc.render.getContextById("AutoSuggestProduct_Context"),url:"",formId:"",renderContextChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;widget.refreshGet(renderContext.properties);},postRefreshHandler:function(widget){var controller=this;var renderContext=this.renderContext;var productsResponse=document.getElementById('suggestedProductsResults');if(productsResponse==null){document.getElementById("autoSuggestProductDynamic_Result_div").innerHTML="";}
SearchJS.showProductAutoSuggestIfResults();}});});}
var order_updated={'AjaxAddOrderItem':'AjaxAddOrderItem','AddOrderItem':'AddOrderItem','AjaxAddOrderItemWithShipingInfo':'AjaxAddOrderItemWithShipingInfo','AjaxDeleteOrderItem':'AjaxDeleteOrderItem','AjaxUpdateOrderItem':'AjaxUpdateOrderItem','AjaxUpdateOrderShippingInfo':'AjaxUpdateOrderShippingInfo','AjaxOrderCalculate':'AjaxOrderCalculate','AjaxLogoff':'AjaxLogoff','AjaxSetPendingOrder':'AjaxSetPendingOrder','AjaxUpdatePendingOrder':'AjaxUpdatePendingOrder','AjaxSingleOrderCancel':'AjaxSingleOrderCancel','AjaxUpdateRewardOption':'AjaxUpdateRewardOption','mattelAddOnServicesSave':'mattelAddOnServicesSave','AddGiftCardToCart':'AddGiftCardToCart','AddOrderItem1':'AddOrderItem1','CollectionsOrderItemAdd':'CollectionsOrderItemAdd'};var dropdownUpdated=false;var dropdownInit=false;var timer;var widgetId="";var piURL="";var MattelPIRelatedProductsRefreshViewURL="";var productAddedList=new Object();dojo.addOnLoad(function(){wc.render.declareContext("MiniShoppingCartContext",{status:"init"},"");wc.render.declareContext("MiniShopCartContentsContext",{status:"init",relativeId:"",contentId:"",contentType:""},"");wc.render.declareContext("MiniShopCartDropDownContext",null,"");});function showMiniShopCartDropDownEvent(event,relativeId,contentId,contentType){console.debug(event.keyCode);if(event.keyCode==dojo.keys.DOWN_ARROW||event.keyCode==dojo.keys.ENTER){showMiniShopCartDropDown(relativeId,contentId,contentType);dojo.stopEvent(event);}}
function toggleMiniShopCartDropDownEvent(event,relativeId,contentId,contentType){console.debug(event.keyCode);if(event.keyCode==dojo.keys.DOWN_ARROW||event.keyCode==dojo.keys.ENTER){toggleMiniShopCartDropDown(relativeId,contentId,contentType);dojo.stopEvent(event);}}
function showMiniShopCartDropDown(relativeId,contentId,contentType){if(!dropdownInit){dropdownInit=true;if(!dropdownUpdated){destroyDialog();var params={};params["status"]='load';params["relativeId"]=relativeId;params["contentId"]=contentId;params["contentType"]=contentType;params["page_view"]='dropdown';wc.render.updateContext("MiniShopCartContentsContext",params);}else{positionMiniShopCartDropDown(relativeId,contentId,contentType);}}}
function toggleMiniShopCartDropDown(relativeId,contentId,contentType){if(dojo.hasClass(relativeId,"selected")){var content=dijit.byId(contentId);if(content){content.hide();}}
else{showMiniShopCartDropDown(relativeId,contentId,contentType);}}
function positionMiniShopCartDropDown(relativeId,contentId,contentType){var dialog=null;var otherDialog=null;if(contentType=='orderItemsList'||contentType=='orderItemsListAutoClose'){dialog=dropDownDlg;otherDialog=productAddedDropDownDlg;}else if(contentType=='orderItemAdded'){dialog=productAddedDropDownDlg;otherDialog=dropDownDlg;}
var show=function(){deactivate(document.getElementById("header"));dojo.addClass("widget_minishopcart","selected");if(dojo.byId("grayOut")!=null){dojo.byId("grayOut").style.display="block";}
dojo.disconnect(this._modalconnects[0]);};var hide=function(){dojo.removeClass("widget_minishopcart","selected");if(dojo.byId("grayOut")!=null){dojo.byId("grayOut").style.display="none";}
$('#MiniShopCartProductAdded .catalogEntryRecommendationWidget').each(function(){var catalogEntryRecommendationWidget=dijit.byId($(this)[0].id);if(catalogEntryRecommendationWidget!=null)catalogEntryRecommendationWidget.destroy();});};if(!dialog){var pane=document.getElementById(contentId);var dialogTitleElement=document.getElementById(contentId+"_ACCE_Label");if(dialogTitleElement!=null){dialog=new wc.widget.WCDialog({title:dialogTitleElement.innerHTML,onShow:show,onHide:hide,autoClose:false},pane);}else{dialog=new wc.widget.WCDialog({onShow:show,onHide:hide,autoClose:false},pane);}
var page=dojo.byId('page');if(typeof page!==undefined&&page!==null){dialog.placeAt(page);}}
var status=null;if(otherDialog){status=otherDialog.displayStatus;}
if(!dialog.displayStatus&&(status==null||!status)){dialog.closeOnTimeOut=false;dialog.autoClose=false;if(contentType=='orderItemsList'||contentType=='orderItemsListAutoClose'){dropdownDisplayed=true;if(contentType=='orderItemsListAutoClose'){dialog.autoClose=true;}
dropDownDlg=dialog;setTimeout(dojo.hitch(dropDownDlg,"show",null),0);}else if(contentType=='orderItemAdded'){var miniShopCart=dojo.byId("MiniShopCartProductAddedWrapper");miniShopCart.style.display="block";window.productAddedDropDownDlg=dialog;window.productAddedDropDownDlg.show();}
setTimeout(dojo.hitch(this,"showUnderlayWrapper",""),0);}
if(dojo.isIE<7)
{dialog.style.display="block";}
dropdownInit=false;}
function setMiniShopCartControllerURL(url,piURL,MattelPIRelatedProductsRefreshViewURL,widgetId){wc.render.getRefreshControllerById('MiniShoppingCartController').url=url;this.piURL=piURL;this.MattelPIRelatedProductsRefreshViewURL=MattelPIRelatedProductsRefreshViewURL;this.widgetId=widgetId;}
dojo.addOnLoad(function(){wc.render.declareRefreshController({id:"MiniShoppingCartController",renderContext:wc.render.getContextById("MiniShoppingCartContext"),url:"",formId:"",modelChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;if(message.actionId in order_updated||message.actionId=='AjaxDeleteOrderItemForShippingBillingPage'){var param=[];if(message.actionId=='CollectionsOrderItemAdd'||message.actionId=='AddOrderItem'||message.actionId=='AjaxAddOrderItem'||message.actionId=='mattelAddOnServicesSave'||message.actionId=='AddGiftCardToCart'||message.actionId=='AddOrderItem1'){if(message.orderItem!=null&&message.orderItem[0].orderItemId!=null){var addedOrderItemIdString="";for(var i=0;i<message.orderItem.length;i++){if(addedOrderItemIdString!=""){addedOrderItemIdString+=",";}
addedOrderItemIdString+=message.orderItem[i].orderItemId;}
param.addedOrderItemId=addedOrderItemIdString;}else{param.addedOrderItemId=message.orderItemId+"";}
if(message.productoperationType=="addon"){param.addedOrderItemId=message.parentOrderItemId+"";}
var AddOnServicesShow=document.getElementById('addOnMerchAssoc_'+message.catEntryId_1);if(AddOnServicesShow!=undefined&&AddOnServicesShow!=null&&AddOnServicesShow!=''){if(AddOnServicesShow.value=='true'&&message.actionId=='mattelAddOnServicesSave')
showDropdown=true;}else{showDropdown=true;}
if(!(typeof isBundleAddtoCart==='undefined')&&isBundleAddtoCart=='true'){showDropdown=false;isBundleAddtoCart=false;}
var isUpdate=document.getElementById('isShopCartPage');if(isUpdate!=null){var update=isUpdate.value;if(update=='true'){showDropdown=false;}}}
param.deleteCartCookie=true;if(message.addedFromSKUList!=null&&message.addedFromSKUList[0]!=null){param.addedFromSKUList=message.addedFromSKUList[0];}
removePIWidgetofMiniCart();widget.refresh(param);}},renderContextChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;if(controller.testForChangedRC(["status"])){renderContext.properties.deleteCartCookie=true;widget.refresh(renderContext.properties);}
var displayMiniCart=renderContext.properties.displayMiniCart;if(displayMiniCart&&displayMiniCart!=undefined&&displayMiniCart!=null){positionMiniShopCartDropDown("widget_minishopcart",'MiniShopCartProductAdded','orderItemAdded');if(MattelPIRelatedProductsRefreshViewURL!=""&&piURL!=""&&widgetId!=""){var updatePIURL=document.getElementById("miniCartPartNumbersForPI");if(updatePIURL!=undefined&&updatePIURL!=""&&updatePIURL!=null){piURL=updatePIURL.value;}
PIProductRecommendationsJS.getPIData(piURL,MattelPIRelatedProductsRefreshViewURL,widgetId);}
if(MattelPIRelatedProductsRefreshViewURL!=""&&widgetId!=""){var adobeFeatureCheck=document.getElementById("isAdobeFeatureEnabled");if(adobeFeatureCheck!=null&&adobeFeatureCheck!=undefined&&adobeFeatureCheck!=""){var skuIds="";var fromPage="";var adobePIurl="";var adobeSkuIdsElement=document.getElementById("adobeSkuIdsElement")
var adobeClientURLElement=document.getElementById("adobeClientURLElement")
var pageTypeElement=document.getElementById("pageTypeElement")
if(adobeSkuIdsElement!=null&&adobeSkuIdsElement!=undefined&&adobeSkuIdsElement!=""){skuIds=adobeSkuIdsElement.value;}
if(adobeClientURLElement!=null&&adobeClientURLElement!=undefined&&adobeClientURLElement!=""){adobePIurl=adobeClientURLElement.value;}
if(pageTypeElement!=null&&pageTypeElement!=undefined&&pageTypeElement!=""){fromPage=pageTypeElement.value;}
PIProductRecommendationsJS.getPIAdobeRestData(skuIds,fromPage,adobePIurl,widgetId,MattelPIRelatedProductsRefreshViewURL);}}}},postRefreshHandler:function(widget){var controller=this;var renderContext=this.renderContext;destroyDialog("MiniShopCartProductAdded");dijit.registry.remove("mattelPIRelatedProducts_area_MiniShopCartDisplay");dijit.registry.remove("catalogEntryRecommendationWidget___MiniShopCartDisplay_");var amazonEnabled=document.getElementById("AmazonMiniCartPayButton");if(typeof AmazonPayments!="undefined"&&typeof amazonEnabled!="undefined"){AmazonPayments.Widgets.Button.show();}
if(showDropdown){if(getCookie("comiccon1")>0){$('#WC_CheckoutLogonf_div_9 .continue_checkout .button_primary').attr('href',"/shop/MattelBillingDetailsView?catalogId=10103&langId=-1&storeId=10151");}
positionMiniShopCartDropDown("widget_minishopcart",'MiniShopCartProductAdded','orderItemAdded');showDropdown=false;if(MattelPIRelatedProductsRefreshViewURL!=""&&piURL!=""&&widgetId!=""){var updatePIURL=document.getElementById("miniCartPartNumbersForPI");if(updatePIURL!=undefined&&updatePIURL!=""&&updatePIURL!=null){piURL=updatePIURL.value;}
PIProductRecommendationsJS.getPIData(piURL,MattelPIRelatedProductsRefreshViewURL,widgetId);}
if(MattelPIRelatedProductsRefreshViewURL!=""&&widgetId!=""){var adobeFeatureCheck=document.getElementById("isAdobeFeatureEnabled");if(adobeFeatureCheck!=null&&adobeFeatureCheck!=undefined&&adobeFeatureCheck!=""){var skuIds="";var fromPage="";var adobePIurl="";var adobeSkuIdsElement=document.getElementById("adobeSkuIdsElement")
var adobeClientURLElement=document.getElementById("adobeClientURLElement")
var pageTypeElement=document.getElementById("pageTypeElement")
if(adobeSkuIdsElement!=null&&adobeSkuIdsElement!=undefined&&adobeSkuIdsElement!=""){skuIds=adobeSkuIdsElement.value;}
if(adobeClientURLElement!=null&&adobeClientURLElement!=undefined&&adobeClientURLElement!=""){adobePIurl=adobeClientURLElement.value;}
if(pageTypeElement!=null&&pageTypeElement!=undefined&&pageTypeElement!=""){fromPage=pageTypeElement.value;}
PIProductRecommendationsJS.getPIAdobeRestData(skuIds,fromPage,adobePIurl,widgetId,MattelPIRelatedProductsRefreshViewURL);}}}
updateCartCookie();populateProductAddedDropdown();resetDeleteCartCookie();}})
wc.render.declareRefreshController({id:"MiniShopCartContentsController",renderContext:wc.render.getContextById("MiniShopCartContentsContext"),url:"",formId:"",modelChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;if(message.actionId in order_updated||message.actionId=='AjaxDeleteOrderItemForShippingBillingPage'){dropdownUpdated=false;}},renderContextChangedHandler:function(message,widget){var controller=this;var renderContext=this.renderContext;if(!dropdownUpdated){renderContext.properties.fetchCartContents=true;dropdownUpdated=true;widget.refresh(renderContext.properties);}},postRefreshHandler:function(widget){var controller=this;var renderContext=this.renderContext;positionMiniShopCartDropDown(renderContext.properties.relativeId,renderContext.properties.contentId,renderContext.properties.contentType);}})});function updateCartCookie(){if(document.getElementById("currentOrderQuantity")!=null&&document.getElementById("currentOrderAmount")!=null&&document.getElementById("currentOrderCurrency")!=null&&document.getElementById("currentOrderId")!=null&&document.getElementById("currentOrderLanguage")!=null){var cartQuantity=document.getElementById("currentOrderQuantity").value;var cartAmount=document.getElementById("currentOrderAmount").value;var cartCurrency=document.getElementById("currentOrderCurrency").value;var cartLanguage=document.getElementById("currentOrderLanguage").value;var cartOrderId=document.getElementById("currentOrderId").value;var currentOrderLocked=document.getElementById("currentOrderLocked").value;var parts=location.hostname.split('.');while(parts.length>2)
var subdomain=parts.shift();var upperleveldomain=parts.join('.');var orderIdCookie=getCookie("WC_CartOrderId_"+WCParamJS.storeId);if(orderIdCookie!=null){dojo.cookie("WC_CartOrderId_"+WCParamJS.storeId,null,{expires:-1,path:'/',domain:upperleveldomain});var cartTotalCookie=getCookie("WC_CartTotal_"+orderIdCookie);if(cartTotalCookie!=null){dojo.cookie("WC_CartTotal_"+orderIdCookie,null,{expires:-1,path:'/',domain:upperleveldomain});}}
dojo.cookie("WC_CartOrderId_"+WCParamJS.storeId,cartOrderId,{path:'/',domain:upperleveldomain});if(cartOrderId!=""){dojo.cookie("WC_CartTotal_"+cartOrderId,cartQuantity+";"+cartAmount+";"+cartCurrency+";"+cartLanguage+";"+currentOrderLocked,{path:'/',domain:upperleveldomain});}}}
function setProductAddedList(newProductAddedList){productAddedList=newProductAddedList;}
function populateProductAddedDropdown(){var search='"';var replaceStr='\\\\"';for(productId in productAddedList){var productDetails=productAddedList[productId];if(document.getElementById('MiniShopCartAddedProdName_'+productId)!=null&&productDetails[0]!=null){document.getElementById('MiniShopCartAddedProdName_'+productId).innerHTML=productDetails[0];}
if(document.getElementById('MiniShopCartAddedProdImgSrc_'+productId)!=null&&productDetails[1]!=null){document.getElementById('MiniShopCartAddedProdImgSrc_'+productId).src=productDetails[1];document.getElementById('MiniShopCartAddedProdImgSrc_'+productId).alt=productDetails[0];}
if(document.getElementById('MiniShopCartAddedProdPrice_'+productId)!=null&&productDetails[2]!=null){document.getElementById('MiniShopCartAddedProdPrice_'+productId).innerHTML=productDetails[2];}
if(document.getElementById('MiniShopCartAddedProdQty_'+productId)!=null&&productDetails[3]!=null){document.getElementById('MiniShopCartAddedProdQty_'+productId).innerHTML=productDetails[3];}
if(document.getElementById('MiniShopCartAddedProdAttr_'+productId)!=null&&productDetails[4]!=null){document.getElementById('MiniShopCartAddedProdAttr_'+productId).innerHTML="";for(attrName in productDetails[4]){attrValue=productDetails[4][attrName]
if(attrValue!=null&&attrValue!='undefined'){attrValue=attrValue.replace(replaceStr,search).replace(/&amp;/g,"&").replace(/&#039;/g,"'").replace(/&#034;/g,'"');}
document.getElementById('MiniShopCartAddedProdAttr_'+productId).innerHTML+='<div>'
+attrName+': '+attrValue+'</div>';}}}
dojo.topic.publish("ProductInfo_Reset");}
function loadMiniCart(contextCurrency,langId){var updateCart=false;var orderIdCookie=getCookie("WC_CartOrderId_"+WCParamJS.storeId);var itemsKey=null;if(checkDeleteCartCookie()){updateCart=true;}else if(orderIdCookie!=undefined&&orderIdCookie==""){var subtotal=document.getElementById("minishopcart_subtotal");var formattedSubtotal=null;if(dojo.locale=='iw-il'){formattedSubtotal=dojo.currency.format(document.getElementById("currentOrderAmount").value,{symbol:'symbol',currency:contextCurrency,locale:'he'});}else{formattedSubtotal=dojo.currency.format(document.getElementById("currentOrderAmount").value,{symbol:'symbol',currency:contextCurrency});}
if(formattedSubtotal!=null){formattedSubtotal=formattedSubtotal.replace('symbol',shoppingActionsJS.currencySymbol);}else{formattedSubtotal=document.getElementById("currentOrderAmount").value;}
if(subtotal!=null){subtotal.innerHTML="\n "
+formattedSubtotal
+"\n ";}
var items=document.getElementById("minishopcart_total");if(items!=null){var itemsMsg=document.getElementById("currentOrderQuantity").value;if(itemsKey!=null){itemsMsg=dojo.string.substitute(itemsKey,{0:document.getElementById("currentOrderQuantity").value});}
items.innerHTML="\n "
+itemsMsg
+"\n ";}}else if(orderIdCookie!=undefined&&orderIdCookie!=""){var cartCookie=getCookie("WC_CartTotal_"+orderIdCookie);if(cartCookie!=undefined&&cartCookie!=null&&cartCookie!=""){var orderInfo=cartCookie.split(";");if(orderInfo!=null&&orderInfo.length>3){if(orderInfo[2]==contextCurrency&&orderInfo[3]==langId){var subtotal=document.getElementById("minishopcart_subtotal");if(subtotal!=null){var formattedSubtotal=null;if(dojo.locale=='iw-il'){formattedSubtotal=dojo.currency.format(orderInfo[1].toString(),{symbol:'symbol',currency:contextCurrency,locale:'he'});}else{formattedSubtotal=dojo.currency.format(orderInfo[1].toString(),{symbol:'symbol',currency:contextCurrency});}
if(formattedSubtotal!=null){formattedSubtotal=formattedSubtotal.replace('symbol',shoppingActionsJS.currencySymbol);}else{formattedSubtotal=orderInfo[1].toString();}
subtotal.innerHTML="\n "
+formattedSubtotal
+"\n ";}
var currentOrderLocked=false;if(orderInfo[4]!=null&&orderInfo[4]=='true'){var currentOrderLocked=true;}
var items=document.getElementById("minishopcart_total");var lock=document.getElementById("minishopcart_lock");if(items!=null){var itemsMsg=orderInfo[0].toString();if(itemsKey!=null){itemsMsg=dojo.string.substitute(itemsKey,{0:orderInfo[0].toString()});}
items.innerHTML="\n "
+itemsMsg
+"\n ";var domClass=require("dojo/dom-class");if(currentOrderLocked){domClass.add(items,"nodisplay");domClass.remove(lock,"nodisplay");}else{domClass.remove(items,"nodisplay");domClass.add(lock,"nodisplay");}}}else{updateCart=true;}}else{updateCart=true;}}else{updateCart=true;}}else{updateCart=true;}
if(updateCart==true){wc.render.updateContext('MiniShoppingCartContext',{'status':'load'});}}
function handleMiniCartHover(){dojo.connect(document.getElementById("widget_minishopcart"),"onmouseover",function(){timer=setTimeout(function(){showMiniShopCartDropDown('widget_minishopcart','quick_cart_container','orderItemsListAutoClose')},1000);});dojo.connect(document.getElementById("widget_minishopcart"),"onmouseout",function(){clearTimeout(timer);});}
function setDeleteCartCookie(){dojo.cookie("WC_DeleteCartCookie_"+WCParamJS.storeId,true,{path:'/'});}
function checkDeleteCartCookie(){var deleteCartCookieVal=getCookie("WC_DeleteCartCookie_"+WCParamJS.storeId);if(deleteCartCookieVal!=undefined&&deleteCartCookieVal!=""){if(deleteCartCookieVal=='true'){return true;}}
return false;}
function resetDeleteCartCookie(){var deleteCartCookieVal=getCookie("WC_DeleteCartCookie_"+WCParamJS.storeId);if(deleteCartCookieVal!=null){dojo.cookie("WC_DeleteCartCookie_"+WCParamJS.storeId,null,{expires:-1,path:'/'});}}
function removePIWidgetofMiniCart(){try{if(!('remove'in Element.prototype)){Element.prototype.remove=function(){if(this.parentNode){this.parentNode.removeChild(this);}};}
dijit.registry.remove("mattelPIRelatedProducts_area_MiniShopCartDisplay");document.getElementById("mattelPIRelatedProducts_area_MiniShopCartDisplay").remove();}catch(e){console.debug("Exception :"+e);}}
dojo.addOnLoad(function(){dojo.topic.subscribe("ProductInfo_Added",setProductAddedList);});if(typeof(DepartmentJS)=="undefined"||DepartmentJS==null||!DepartmentJS){DepartmentJS={init:function(){dojo.query(".col8 > .deptContainer > li").forEach(function(node)
{dojo.connect(node,"onclick",DepartmentJS,DepartmentJS._show);dojo.connect(node,"onclick",DepartmentJS,DepartmentJS._toggleDept);dojo.connect(node,"onclick",DepartmentJS,DepartmentJS._borderTog);dojo.connect(node,"onclick",DepartmentJS,DepartmentJS._swapGrad);});dojo.query("#departmentsDropdownBP3down > ul > li div.tabOpen").forEach(function(node)
{dojo.connect(node,"onclick",DepartmentJS,DepartmentJS._expandDept);dojo.connect(node,"onclick",DepartmentJS,DepartmentJS._flipSign);});dojo.connect(dojo.byId("qLinkClose"),"onclick",DepartmentJS,DepartmentJS._closeqLinkDropDown);dojo.connect(dojo.byId("qLinkA"),"onclick",DepartmentJS,DepartmentJS._showQLink);dojo.connect(dojo.byId("qLinkBC"),"onclick",DepartmentJS,DepartmentJS._showQLink);dojo.connect(dojo.byId("navMore"),"onclick",DepartmentJS,DepartmentJS._showAllDeptDropDown);dojo.connect(window,"onresize",DepartmentJS,DepartmentJS._reset);dojo.connect(window,"onresize",DepartmentJS,DepartmentJS._calculateWidth);dojo.connect(dojo.byId("navDepartments"),"onclick",DepartmentJS,DepartmentJS._showNavDeptDropDown);},_reset:function(evt){var srcElement=document.getElementById("deptContainerNode");srcElement.style.width='';if(window.matchMedia){if(window.matchMedia("(max-width: 600px)").matches){DepartmentJS.clearAll();}else{DepartmentJS.close("departmentsDropdownBP3down");DepartmentJS.toggleOff('navDeptArrow');}}else{if(!(document.documentElement.clientWidth>600)){DepartmentJS.clearAll();}else{DepartmentJS.close("departmentsDropdownBP3down");DepartmentJS.toggleOff('navDeptArrow');}}},_closeqLinkDropDown:function(evt){DepartmentJS.close('qLinkDropdown');var quickLinkElement=document.getElementById("quickLinks");quickLinkElement.style.display=="block";},_showQLink:function(evt){var srcElement=document.getElementById("qLinkDropdown");if(srcElement!=null){if(srcElement.style.display=="block"){DepartmentJS.close('searchDropdown');srcElement.style.display='none';}
else
{dojo.query(".subDeptDropdown ").forEach(function(node){DepartmentJS.close(node.id);});DepartmentJS.close("departmentsDropdown");DepartmentJS.close('mobileSearchDropdown');DepartmentJS.close('searchDropdown');DepartmentJS.close('qLinkDropdown');srcElement.style.display='block';}}
DepartmentJS._toggleDrop('qLinkArrow');},_showDeptLink:function(evt){var srcElement=document.getElementById("navDropdownDepartments");if(srcElement!=null){if(srcElement.style.display=="block"){DepartmentJS.close('searchDropdown');srcElement.style.display='none';}
else
{dojo.query(".subDeptDropdown ").forEach(function(node){DepartmentJS.close(node.id);});DepartmentJS.close("departmentsDropdown");DepartmentJS.close('mobileSearchDropdown');DepartmentJS.close('searchDropdown');DepartmentJS.close('qLinkDropdown');srcElement.style.display='block';}}},_showMobileSearchComponent:function(evt){var srcElement=document.getElementById("mobileSearchDropdown");if(srcElement!=null){if(srcElement.style.display=="block"){DepartmentJS.close('searchDropdown');srcElement.style.display='none';}
else
{dojo.query(".subDeptDropdown ").forEach(function(node){DepartmentJS.close(node.id);});DepartmentJS.close("departmentsDropdown");DepartmentJS.close('mobileSearchDropdown');DepartmentJS.close('searchDropdown');DepartmentJS.close('qLinkDropdown');srcElement.style.display='block';}}},_show:function(evt){var deptDropdown=evt.currentTarget.id.replace("nav","navDropdown");var position=evt.currentTarget.id.replace("nav","");var columns=0;var srcElement=document.getElementById(deptDropdown);if(srcElement!=null){if(srcElement.style.display=="block"){DepartmentJS.close('searchDropdown');srcElement.style.display='none';}
else
{dojo.query(".subDeptDropdown ").forEach(function(node){DepartmentJS.close(node.id);});dojo.query("#"+deptDropdown+" ul ").forEach(function(node){columns++;});if(columns==0){columns=1;}
var curr_width=27;for(var i=1;i<position;i++)
{curr_width=document.getElementById("nav"+i).offsetWidth+curr_width+4;}
DepartmentJS.close("departmentsDropdown");DepartmentJS.close('mobileSearchDropdown');DepartmentJS.close('searchDropdown');DepartmentJS.close('qLinkDropdown');srcElement.style.display='block';srcElement.style.width=240*columns+'px';srcElement.style.left=curr_width+'px';}}},_expandDept:function(evt){var deptDropdown=evt.currentTarget.id.replace("Tog","Expand");var srcElement=document.getElementById(deptDropdown);if(srcElement!=null){if(srcElement.style.display=="block"){DepartmentJS.close('searchDropdown');srcElement.style.display='none';}
else
{dojo.query(".subDeptDropdown ").forEach(function(node){DepartmentJS.close(node.id);});DepartmentJS.close("departmentsDropdown");DepartmentJS.close('mobileSearchDropdown');DepartmentJS.close('searchDropdown');DepartmentJS.close('qLinkDropdown');srcElement.style.display='block';}}},_calculateWidth:function(evt){var div_width=0;var new_width=0;var srcElement=document.getElementById("deptContainerNode");var deptContainerWidth=srcElement.offsetWidth;var deptDropDown=document.getElementById("departmentsDropdown");dojo.query(".col8 > .deptContainer > li").forEach(function(node)
{div_width=div_width+node.offsetWidth+4;if(div_width<=(srcElement.offsetWidth-27)){new_width=div_width;}});srcElement.style.width=new_width+2+'px';deptDropDown.style.left=new_width+23+'px';if(new_width==0)
{deptDropDown.style.left='';}},_showAllDeptDropDown:function(evt){var srcElement=document.getElementById("departmentsDropdown");if(srcElement!=null){if(srcElement.style.display=="block"){DepartmentJS.close('searchDropdown');srcElement.style.display='none';}
else
{dojo.query(".subDeptDropdown ").forEach(function(node){DepartmentJS.close(node.id);});DepartmentJS.close("departmentsDropdown");srcElement.style.display='block';}}
DepartmentJS._toggleDrop('deptTog');srcElement=document.getElementById("deptBord");if(srcElement!=null){if(srcElement.style.borderColor=='rgb(241, 243, 243)'){dojo.query(".col8 > ul > li > .navBorder").forEach(function(node)
{DepartmentJS.borderTogOff(node.id);});srcElement.style.borderColor='#FBCC65';}
else{srcElement.style.borderColor='#f1f3f3';}}
DepartmentJS._swapGrad(evt);},_showNavDeptDropDown:function(ele){var srcElement=document.getElementById("departmentsDropdownBP3down");if(srcElement!=null){if(srcElement.style.display=="block"){DepartmentJS.close('searchDropdown');srcElement.style.display='none';}
else
{dojo.query(".subDeptDropdown ").forEach(function(node){DepartmentJS.close(node.id);});DepartmentJS.close('searchDropdown');DepartmentJS.close("departmentsDropdown");DepartmentJS.close('mobileSearchDropdown');DepartmentJS.close('qLinkDropdown');srcElement.style.display='block';}}
DepartmentJS._toggleDrop("navDeptArrow");},close:function(ele){var srcElement=document.getElementById(ele);if(srcElement!=null){srcElement.style.display='none';}},toggleOffAllDept:function(ele){var srcElement=document.getElementById(ele);if(srcElement!=null){srcElement.style.backgroundPosition='-77px -1px';}},toggleOff:function(ele){var srcElement=document.getElementById(ele);if(srcElement!=null){if(srcElement!=document.getElementById('deptTog')){if(srcElement.style.backgroundPosition=='-241px -21px'){srcElement.style.backgroundPosition='-121px -1px';}
else if(srcElement.style.backgroundPosition=='-281px -21px'){srcElement.style.backgroundPosition='-261px -21px';}
else if(srcElement.style.backgroundPosition=='-21px -21px'){srcElement.style.backgroundPosition='-101px -1px';}}
else{srcElement.style.backgroundPosition='-121px -1px';}}},_toggleDept:function(evt){var nodeId=evt.currentTarget.id;var togId=nodeId.replace("nav","Tog");DepartmentJS._toggleDrop(togId);},clearDropdownTog:function(ele){DepartmentJS.toggleOff('deptTog');DepartmentJS.toggleOff('navSearchArrow');dojo.query(".col8 > ul > li > .navBorder > .deptArrow").forEach(function(node)
{DepartmentJS.toggleOff(node.id);});DepartmentJS.toggleOff('qLinkArrow');DepartmentJS.toggleOff('cartDropdown');DepartmentJS.toggleOff('navDeptArrow');},_toggleDrop:function(ele){var srcElement=document.getElementById(ele);if(srcElement!=null){if(srcElement!=document.getElementById('deptTog')){if(srcElement.style.backgroundPosition=='-121px -1px'){DepartmentJS.clearDropdownTog();srcElement.style.backgroundPosition='-241px -21px';}
else if(srcElement.style.backgroundPosition=='-241px -21px'){srcElement.style.backgroundPosition='-121px -1px';}
else if(srcElement.style.backgroundPosition=='-261px -21px'){DepartmentJS.clearDropdownTog();srcElement.style.backgroundPosition='-281px -21px';}
else if(srcElement.style.backgroundPosition=='-281px -21px'){srcElement.style.backgroundPosition='-261px -21px';}
else if(srcElement.style.backgroundPosition=='-101px -1px'){DepartmentJS.clearDropdownTog();srcElement.style.backgroundPosition='-21px -21px';}
else if(srcElement.style.backgroundPosition=='-21px -21px'){srcElement.style.backgroundPosition='-101px -1px';}
else if(srcElement.style.backgroundPosition=='-201px -1px'){srcElement.style.backgroundPosition='-221px -1px';}
else if(srcElement.style.backgroundPosition=='-221px -1px'){srcElement.style.backgroundPosition='-201px -1px';}}
else{if(srcElement.style.backgroundPosition=='-121px -1px'){DepartmentJS.clearDropdownTog();srcElement.style.backgroundPosition='-281px -21px';}
else if(srcElement.style.backgroundPosition=='-281px -21px'){srcElement.style.backgroundPosition='-121px -1px';}}}},_swapGrad:function(evt){var nodeId=evt.currentTarget.id;var srcElement=document.getElementById(nodeId);if(srcElement!=null){if(srcElement.style.marginBottom=='4px'){dojo.query(".col8 > ul > li").forEach(function(node)
{DepartmentJS.swapGradBack(node.id);});if(dojo.isIE==8){return;}
srcElement.className="selectedMenu";srcElement.style.marginBottom="0px";}else{if(dojo.isIE==8){return;}
srcElement.className="";srcElement.style.marginBottom="4px";}}},_borderTog:function(evt){var nodeId=evt.currentTarget.id;var borderId=nodeId.replace("nav","Bord");var srcElement=document.getElementById(borderId);if(srcElement!=null){if(srcElement.style.borderColor=='rgb(241, 243, 243)'){dojo.query(".col8 > ul > li > .navBorder").forEach(function(node)
{DepartmentJS.borderTogOff(node.id);});srcElement.style.borderColor='#FBCC65';}
else{srcElement.style.borderColor='#f1f3f3';}}},swapGradBack:function(ele){var srcElement=document.getElementById(ele);if(srcElement!=null){if(dojo.isIE==8){return;}
srcElement.className="";srcElement.style.marginBottom="4px";}},borderTogOff:function(ele){var srcElement=document.getElementById(ele);if(srcElement!=null){srcElement.style.borderColor='#f1f3f3';}},_flipSign:function(evt){var nodeId=evt.currentTarget.id;var srcElement=document.getElementById(nodeId);if(srcElement!=null){if(srcElement.innerHTML=="[ + ]"){dojo.query("#departmentsDropdownBP3down > ul > a > li > div.tabOpen").forEach(function(node)
{flipOff(node.id);});srcElement.innerHTML="[ &#8211 ]";}
else{srcElement.innerHTML="[ + ]";}}},flipOff:function(ele){var srcElement=document.getElementById(ele);if(srcElement!=null){srcElement.innerHTML="[ + ]";}},clearAll:function(){DepartmentJS.close('qLinkDropdown');DepartmentJS.close('departmentsDropdown');DepartmentJS.close('mobileSearchDropdown');DepartmentJS.close('searchDropdown');dojo.query(".subDeptDropdown ").forEach(function(node){DepartmentJS.close(node.id);});dojo.query(".col8 > ul > li ").forEach(function(node)
{DepartmentJS.swapGradBack(node.id);});dojo.query(".col8 > ul > li > .navBorder").forEach(function(node)
{DepartmentJS.borderTogOff(node.id);});DepartmentJS.toggleOff('navSearchArrow');dojo.query(".col8 > ul > li > .navBorder > .deptArrow").forEach(function(node)
{DepartmentJS.toggleOff(node.id);});DepartmentJS.toggleOff("deptTog");}};}
dojo.require("dojox.xml.DomParser");if(typeof(QuickInfoJS)=="undefined"||QuickInfoJS==null||!QuickInfoJS){QuickInfoJS={productImgDimensions:"1000x1000",quickInfoImgDimensions:"330x330",catEntryParams:{},selectedAttributes:new Object(),catEntryQuantity:1,itemDetailsArr:new Object(),params:null,replaceOrderItemId:'',itemId:'',selectedSkuIndex:null,selectedThumbnailIndex:null,quickSellAssociationProductId:'',setReplaceOrderItemId:function(replaceOrderItemId){this.replaceOrderItemId=replaceOrderItemId;},setValues:function(productId){if(dojo.byId('catEntryParamsForJS')){this.catEntryParams=dojo.fromJson(dojo.byId('catEntryParamsForJS').value);}
else if(dojo.byId('catEntryParamsForJS_'+productId)){this.catEntryParams=dojo.fromJson(dojo.byId('catEntryParamsForJS_'+productId).value);}
this.catEntryParams.attributes=this.selectedAttributes;},setCatEntryQuantity:function(catEntryQuantity){this.catEntryQuantity=catEntryQuantity;},showDetails:function(productId,params,itemId,quantity,parentPage){this.parseScript();cursor_wait();var paramsRecViewTrig={};paramsRecViewTrig.DM_ReqCmd="ProductDisplay";paramsRecViewTrig.productId=productId;paramsRecViewTrig.storeId=WCParamJS.storeId;paramsRecViewTrig.catalogId=WCParamJS.catalogId;paramsRecViewTrig.langId=WCParamJS.langId;if(!submitRequest()){return;}
dojo.xhrPost({url:getAbsoluteURL()+"AjaxMarketingTriggerProcessServiceEvaluate",content:paramsRecViewTrig,load:function(result){float_labels();},error:function(errObj,ioArgs){cursor_clear();}});if(params){this.params=params;}else{this.params=null;}
this.selectedAttributes=new Object();this.selectedSkuIndex=null;this.selectedThumbnailIndex=null;this.close();var contextValues=this.setCommonParams();if(itemId){this.itemId=itemId;contextValues.updateAttributes="true";}else{this.itemId='';contextValues.updateAttributes="false";}
if(parentPage){contextValues.parentPage=parentPage;}
if(quantity){this.catEntryQuantity=quantity;}
contextValues.isGiftCard=params.isGiftCard;contextValues.productId=productId;if(GeolocationJS!=null&&GeolocationJS!=undefined){GeolocationJS.getAkamaiCountryCode();contextValues.countryCode=GeolocationJS.akamaiCountryCode;}
contextValues.href=document.getElementById(currentId).parentNode.querySelectorAll('.product_name')[0].querySelectorAll('a')[0].getAttribute('href');wc.render.updateContext('QuickInfoContext',contextValues);},parseScript:function(){if($("#quickInfoPopup")!=null){$("#quickInfoPopup").find("script").each(function(){var src=$(this).attr('src');if(src!=null){$.getScript(src).done(function(script,textStatus){console.log(textStatus);}).fail(function(jqxhr,settings,exception){console.log(exception);});}
eval($(this).text());});}},parseInventoryScript:function(){if($("#quickInfoPopup #Inventory_Availability_check")!=null){$("#quickInfoPopup #Inventory_Availability_check").find("script").each(function(){var src=$(this).attr('src');if(src!=null){$.getScript(src).done(function(script,textStatus){console.log(textStatus);}).fail(function(jqxhr,settings,exception){console.log(exception);});}
eval($(this).text());});}},parseQuickViewAttributes:function(){if($("#initialLoadHasAttributes")!=null){$("#initialLoadHasAttributes").find("script").each(function(){var src=$(this).attr('src');if(src!=null){$.getScript(src).done(function(script,textStatus){console.log(textStatus);}).fail(function(jqxhr,settings,exception){console.log(exception);});}
eval($(this).text());});}},toggleQuickViewCartButton:function(catentry_id){var link=dojo.byId("add2CartBtn");if(link!=null){if((catentry_id==""||catentry_id==null||catentry_id==undefined)&&link.href!="javascript:;"){dojo.addClass("add2CartBtn","inactiveLink");var href=link.href;link.setAttribute("rel",href);link.href="javascript:;"}
else if((catentry_id==""||catentry_id==null||catentry_id==undefined)&&link.href=="javascript:;"){}else{dojo.removeClass("add2CartBtn","inactiveLink");dojo.removeAttr(link,"style");var href=link.getAttribute("rel");link.removeAttribute("rel");link.href=href;}}},showInlineDetails:function(itemId){if(itemId){this.itemId=itemId;}},changeAttributes:function(orderItemId,productId,itemId,quantity){this.setReplaceOrderItemId(orderItemId);this.showDetails(productId,null,itemId,quantity);},changeImage:function(elementId,imgSrc){this.selectedThumbnailIndex=elementId-1;dojo.byId("quickInfoMainImage").src=this.getQuickInfoImage(this.catEntryParams.skus[this.selectedSkuIndex].fullImageAttachments[this.selectedThumbnailIndex].path);dojo.query(".widget_quick_info_popup .other_views li").removeClass("selected");dojo.addClass("quickInfoThumbnail"+elementId,"selected");},setSelectedAttribute:function(selectedAttributeName,selectedAttributeValue){this.selectedAttributes[selectedAttributeName]=selectedAttributeValue;},notifyAttributeChange:function(productId){dojo.publish('QuickInfo_attributesChanged',[dojo.toJson(this.selectedAttributes)]);this.setValues(productId);var catEntryId=this.resolveSKU();if(catEntryId!=-1){dojo.topic.publish('DefiningAttributes_Resolved',catEntryId,this.catEntryParams.id);dojo.topic.publish('DefiningAttributes_Resolved_'+this.catEntryParams.id,catEntryId,this.catEntryParams.id);}
else{dojo.topic.publish('DefiningAttributes_Resolved',null,null);}},selectItem:function(displayPriceRange,updateItemImageOnly){this.displayPriceRange=displayPriceRange;this.setValues();var catEntryId=this.resolveSKU();if(catEntryId==-1&&updateItemImageOnly){var skuId=-1;for(idx=0;idx<this.catEntryParams.skus.length;idx++){for(attribute in this.catEntryParams.skus[idx].attributes){if(this.catEntryParams.attributes&&this.catEntryParams.skus[idx].attributes[attribute]==this.catEntryParams.attributes[attribute]){skuId=this.catEntryParams.skus[idx].id;break;}}}
if(skuId!=-1){catEntryId=skuId;this.updateItemImageOnly=updateItemImageOnly;}}
if(catEntryId!=-1){if(this.itemDetailsArr[catEntryId]!=null&&this.itemDetailsArr[catEntryId]!='undefined'){this.displayItemDetails(this.itemDetailsArr[catEntryId]);}
else{var params=this.setCommonParams();params.catalogEntryId=catEntryId;wc.service.declare({id:"getCatalogEntryDetailsQI",actionId:"getCatalogEntryDetailsQI",url:getAbsoluteURL()+appendWcCommonRequestParameters("GetCatalogEntryDetailsByIDView"),formId:"",successHandler:function(serviceResponse,ioArgs){QuickInfoJS.setItemDetails(serviceResponse,ioArgs);$('#selectCountry').find("option").removeAttr('selected');$('#selectCountry').prop("selectedIndex",0);$('#selectCountry').find("option:first").attr('selected','selected');$('#stockAvailability').addClass("hide");$('#stockAvailability').parents('.location_select').find('.location_select_label').addClass("hide");$('.noDefattr').addClass("hide");},failureHandler:function(serviceResponse,ioArgs){console.debug("QuickInfoJS.selectItem: Unexpected error occurred during an xhrPost request.");}});wc.service.invoke("getCatalogEntryDetailsQI",params);}}},selectSwatch:function(selectedAttributeName,selectedAttributeValue,swatchId,swatchGrp,itemId){if(dojo.hasClass("quickInfoSwatch_"+selectedAttributeName+"_"+selectedAttributeValue,"color_swatch_disabled")){return false;}
this.setValues();var swatchNames=dojo.byId("WC_QuickInfo_SwatchNames").value.split("_");var currentSwatchPos=-1;for(var i=0;i<swatchNames.length;i++){if(swatchNames[i]==selectedAttributeName){currentSwatchPos=i;break;}}
var currentSwatchkey="quickInfoSwatch_"+selectedAttributeName+"_"+selectedAttributeValue;var currentSwatchkeyLink="WC_QuickInfo_Swatch_"+selectedAttributeName+"_"+selectedAttributeValue;var validSwatchArr=new Array();for(idx in this.catEntryParams.skus){var validItem=false;var entitledItem=this.catEntryParams.skus[idx];for(attribute in entitledItem.attributes){if(selectedAttributeName==attribute&&selectedAttributeValue==entitledItem.attributes[attribute]&&entitledItem.buyable){validItem=true;break;}}
if(validItem){for(attribute in entitledItem.attributes){var attributePos=-1;for(var i=0;i<swatchNames.length;i++){if(swatchNames[i]==attribute){attributePos=i;break;}}
if(attributePos>currentSwatchPos){validSwatchArr.push(attribute+"_"+entitledItem.attributes[attribute]);}}}}
var swatchesDisabled=new Array();var selectedSwatches=new Array();for(idx in this.catEntryParams.skus){var entitledItem=this.catEntryParams.skus[idx];for(attribute in entitledItem.attributes){var attributePos=-1;for(var i=0;i<swatchNames.length;i++){if(swatchNames[i]==attribute){attributePos=i;break;}}
if(attributePos>currentSwatchPos){var swatchSelection=attribute+"_"+entitledItem.attributes[attribute];var swatchId="quickInfoSwatch_"+swatchSelection;var swatchLinkId="WC_QuickInfo_Swatch_"+swatchSelection;var swatchListId="quickInfoSwatch_"+swatchSelection+"_list";var validSwatchArrPos=-1;for(var i=0;i<validSwatchArr.length;i++){if(validSwatchArr[i]==swatchSelection){validSwatchArrPos=i;break;}}
var swatchesDisabledPos=-1;for(var i=0;i<swatchesDisabled.length;i++){if(swatchesDisabled[i]==swatchSelection){swatchesDisabledPos=i;break;}}
if(validSwatchArrPos>-1){if(!dojo.hasClass(swatchId,"color_swatch_selected")){dojo.byId(swatchId).className="color_swatch";dojo.byId(swatchListId).className="color_swatch_wrapper";dojo.byId(swatchId).src=dojo.byId(swatchId).src.replace("_disabled.png","_enabled.png");document.getElementById(swatchLinkId).setAttribute("aria-disabled","false");}}
else if(swatchesDisabledPos==-1){swatchesDisabled.push(swatchSelection);if(dojo.hasClass(swatchId,"color_swatch_selected")){selectedSwatches.push(swatchId);}
dojo.byId(swatchId).className="color_swatch_disabled";dojo.byId(swatchListId).className="color_swatch_disabled";dojo.byId(swatchId).src=dojo.byId(swatchId).src.replace("_enabled.png","_disabled.png");document.getElementById(swatchLinkId).setAttribute("aria-disabled","true");}}
if(document.getElementById("WC_QuickInfo_Swatch_"+attribute+"_"+entitledItem.attributes[attribute])!=null){document.getElementById("WC_QuickInfo_Swatch_"+attribute+"_"+entitledItem.attributes[attribute]).setAttribute("aria-checked","false");}}}
for(idx in selectedSwatches){var selectedSwatch=selectedSwatches[idx];var idSelector="img[id^='"+selectedSwatch.substring(0,selectedSwatch.lastIndexOf("_"))+"']";var swatchSelected=false;dojo.query(idSelector).forEach(function(node,index,arr){if(!swatchSelected&&dojo.hasClass(node,"color_swatch")){var values=node.id.split("_");QuickInfoJS.selectSwatch(values[1],values[2],"quickInfoSwatch_"+values[1]+"_"+values[2],"quickInfoSwatch_"+values[1]+"_");QuickInfoJS.selectItem(true);swatchSelected=true;}});}
selector="img[id^='"+swatchGrp+"']";dojo.query(selector).forEach(function(node,index,arr){if(!dojo.hasClass(node,"color_swatch_disabled")){dojo.addClass(node,"color_swatch");if(dojo.hasClass(node,"color_swatch_selected")){dojo.removeClass(node,"color_swatch_selected");}}});selectorList="li[id^='"+swatchGrp+"']";dojo.query(selectorList).forEach(function(node,index,arr){if(!dojo.hasClass(node,"color_swatch_disabled")){dojo.addClass(node,"color_swatch_wrapper");if(dojo.hasClass(node,"color_swatch_selected")){dojo.removeClass(node,"color_swatch_selected");}}});dojo.byId(currentSwatchkey).className="color_swatch_selected";if(document.getElementById(currentSwatchkey+"_list")!=undefined){document.getElementById(currentSwatchkey+"_list").className="color_swatch_selected";}
dojo.byId("quickinfo_swatch_selection_"+selectedAttributeName).innerHTML=selectedAttributeValue;document.getElementById(currentSwatchkeyLink).setAttribute("aria-checked","true");this.setSelectedAttribute(selectedAttributeName,selectedAttributeValue);},setCommonParams:function(){var params=new Object();params.storeId=WCParamJS.storeId;params.catalogId=WCParamJS.catalogId;params.langId=WCParamJS.langId;return params;},setItemDetails:function(serviceResponse,ioArgs){QuickInfoJS.itemDetailsArr[serviceResponse.catalogEntry.catalogEntryIdentifier.uniqueID]=serviceResponse.catalogEntry;QuickInfoJS.displayItemDetails(serviceResponse.catalogEntry);},displayItemDetails:function(catalogEntry){if(null!=this.catEntryParams){for(idx in this.catEntryParams.skus){if(null!=this.catEntryParams.skus[idx]&&(this.catEntryParams.skus[idx].id==catalogEntry.catalogEntryIdentifier.uniqueID)){var angleImageAreaList=dojo.query("div[id^='quickinfoAngleImagesArea']");if(angleImageAreaList!=null){var angleImageArea=angleImageAreaList[0];}
if(this.catEntryParams.skus[idx].thumbnailAttachments!=null&&this.catEntryParams.skus[idx].thumbnailAttachments.length>0){var thumbnailAreaList=dojo.query("ul[id^='quickInfoAngleImagesAreaList']");if(thumbnailAreaList!=null){var thumbnailArea=thumbnailAreaList[0];if(angleImageArea!=null){angleImageArea.style.display="block";}
for(idx2=1;idx2<=this.catEntryParams.skus[idx].thumbnailAttachments.length;idx2++){var angleThumbnail=document.createElement("li");var angleThumbnailLink=document.createElement("a");var angleThumbnailImg=document.createElement("img");angleThumbnail.id="quickInfoThumbnail"+idx2;angleThumbnailLink.href="javaScript:QuickInfoJS.changeImage("+idx2+",'"+this.catEntryParams.skus[idx].fullImageAttachments[idx2-1].path+"', \"\");";angleThumbnailLink.id="WC_QuickInfo_Link_thumbnail_"+idx2;angleThumbnailLink.className="tlignore";if(this.catEntryParams.skus[idx].thumbnailAttachments[idx2-1].shortDesc!='undefined'&&this.catEntryParams.skus[idx].thumbnailAttachments[idx2-1].shortDesc!=null){angleThumbnailLink.title=this.catEntryParams.skus[idx].thumbnailAttachments[idx2-1].shortDesc;}
angleThumbnailImg.src=this.catEntryParams.skus[idx].thumbnailAttachments[idx2-1].path;if(this.catEntryParams.skus[idx].thumbnailAttachments[idx2-1].shortDesc!='undefined'&&this.catEntryParams.skus[idx].thumbnailAttachments[idx2-1].shortDesc!=null){angleThumbnailImg.alt=this.catEntryParams.skus[idx].thumbnailAttachments[idx2-1].shortDesc;}
if(idx2==1){dojo.empty(thumbnailArea);}
angleThumbnailLink.appendChild(angleThumbnailImg);angleThumbnail.appendChild(angleThumbnailLink);thumbnailArea.appendChild(angleThumbnail);}}}else{if(angleImageArea!=null){angleImageArea.style.display="none";}}
if(null==this.selectedThumbnailIndex){this.selectedThumbnailIndex=0;}
this.selectedSkuIndex=idx;var imagePath=this.getQuickInfoImage(catalogEntry.description[0].fullImage,catalogEntry.description[0].imagePrefix);if(null!=imagePath&&imagePath.length!=0){dojo.byId("quickInfoMainImage").src=imagePath;}
if(document.getElementById("ProductInfoImage_"+this.catEntryParams.id)!=null){document.getElementById("ProductInfoImage_"+this.catEntryParams.id).value=imagePath;}}}}
if(this.updateItemImageOnly){this.updateItemImageOnly=false;return;}
dojo.html.set(dojo.query(".widget_quick_info_popup .main_header")[0],catalogEntry.description[0].name);if(document.getElementById("ProductInfoName_"+this.catEntryParams.id)!=null){document.getElementById("ProductInfoName_"+this.catEntryParams.id).value=catalogEntry.description[0].name;}
if(catalogEntry.listPriced&&catalogEntry.listPrice>catalogEntry.offerPrice){if(null!=dojo.query(".widget_quick_info_popup .old_price")[0]){dojo.html.set(dojo.query(".widget_quick_info_popup .old_price")[0],catalogEntry.listPrice);}else{var oldPriceTag="<span class='old_price'>"+catalogEntry.listPrice+"</span>";var priceTag=dojo.query(".widget_quick_info_popup .price")[0];dojo.place(oldPriceTag,priceTag,"before");}}else if(null!=dojo.query(".widget_quick_info_popup .old_price")[0]){dojo.query(".widget_quick_info_popup .old_price").orphan();}
dojo.html.set(dojo.query(".widget_quick_info_popup .price")[1],catalogEntry.offerPrice.replace(/\$/g,''));dojo.html.set(dojo.query(".widget_quick_info_popup .sku")[0],storeNLS['SKU']+" "+catalogEntry.catalogEntryIdentifier.externalIdentifier.partNumber);if(document.getElementById("ProductInfoPrice_"+this.catEntryParams.id)!=null){document.getElementById("ProductInfoPrice_"+this.catEntryParams.id).value=catalogEntry.offerPrice;}},validate:function(){if(this.catEntryParams.type=='ProductBean'&&(null==this.catEntryParams.attributes||"undefined"==this.catEntryParams.attributes)){MessageHelper.displayErrorMessage(storeNLS['ERR_RESOLVING_SKU']);return false;}else if(!isPositiveInteger(this.catEntryQuantity)){MessageHelper.displayErrorMessage(storeNLS['QUANTITY_INPUT_ERROR']);return false;}
return true;},AddQuickSellItems:function(){var quickSellItemslength=document.getElementById('quickSellItemslength_'+this.quickSellAssociationProductId).value;for(var i=1;i<=quickSellItemslength;i++){var maItem=document.getElementById('maName_'+this.quickSellAssociationProductId+'_'+i).checked;if(maItem){if(dojo.byId("quickSellItem_"+this.quickSellAssociationProductId+"_"+i)!=null){var quicksellItemJSON=dojo.fromJson(dojo.byId("quickSellItem_"+this.quickSellAssociationProductId+"_"+i).innerHTML);for(var j in quicksellItemJSON){var quicksellItem=quicksellItemJSON[j];this.quickSellItems.push(quicksellItem.catentry_id);this.quickSellItemsQuantity.push(quicksellItem.quantity);}}}}},add2ShopCart:function(customParams){if(browseOnly){MessageHelper.displayErrorMessage(storeNLS['ERROR_ADD2CART_BROWSE_ONLY']);return;}
this.setValues();if(!this.validate()){return;}
if(null==this.params){this.params=this.setCommonParams();this.params.orderId=".";this.params.inventoryValidation="true";this.params.calculateOrder="1";}
var productId='';if(this.catEntryParams.type.toLowerCase()=='itembean'||this.catEntryParams.type.toLowerCase()=='packagebean'||this.catEntryParams.type.toLowerCase()=='dynamickitbean'){updateParamObject(this.params,"catEntryId",this.catEntryParams.id,false,-1);updateParamObject(this.params,"quantity",this.catEntryQuantity,false,-1);productId=this.catEntryParams.id;}else{var sku=this.resolveSKU();if(-1==sku){if(null!=document.getElementById("QuickViewAttributeCount")){var count=document.getElementById("QuickViewAttributeCount").value;while(count>0){var errMsgDivId="QuickViewErrMsg_"+count;var quickInfoAttrValueID="quickInfoAttrValue_"+count;if(document.getElementById(quickInfoAttrValueID).value==''){document.getElementById(errMsgDivId).style.display='block';console.log("consoleeeeee"+count);}else{document.getElementById(errMsgDivId).style.display='none';}
count--;}}else{MessageHelper.displayErrorMessage(storeNLS['ERR_RESOLVING_SKU']);}
return;}else{updateParamObject(this.params,"catEntryId",sku,false,-1);updateParamObject(this.params,"quantity",this.catEntryQuantity,false,-1);}
productId=sku;}
this.quickSellAssociationProductId=productId;if(typeof(comicconIds)!="undefined"&&comicconIds.length>0){document.cookie="comiccon1=; path=/; domain=.mattel.com;expires=Thu, 01 Jan 1970 00:00:01 GMT";var comicConFound=-1;$.ajax({url:"/wcs/resources/store/10151/cart/@self",async:false,}).always(function(data){$(data.orderItem).each(function(index){if($.inArray(data.orderItem[index].productId,comicconIds)>=0){comicConFound=1;}})
if($.inArray(productId,comicconIds)>=0&&(data.orderItem==undefined)){comicConFound=1;}
document.cookie="comiccon1="+comicConFound+"; path=/; domain=.mattel.com; expires=Tue, 01 Aug 2017 00:00:01 GMT";});if(getCookie("comiccon1")!=undefined){if(getCookie("comiccon1")>0&&$.inArray(productId,comicconIds)<0){MessageHelper.displayErrorMessage(storeNLS['COMICCON_NA_1']);this.close();return;}
else if(getCookie("comiccon1")<0&&$.inArray(productId,comicconIds)>=0){MessageHelper.displayErrorMessage(storeNLS['COMICCON_NA_2']);this.close();return;}}}
var shopCartService="AddOrderItem";if(customParams!=null&&customParams!='undefined'){for(i in customParams){this.params[i]=customParams[i];}
if(customParams['catalogEntryType']=='dynamicKit'){shopCartService="AddPreConfigurationToCart";}}
if(this.params['catalogEntryType']=='dynamicKit'){shopCartService="AddPreConfigurationToCart";}
if(document.getElementById('quickSellItemslength_'+this.quickSellAssociationProductId)){this.quickSellItems=[];this.quickSellItemsQuantity=[];this.AddQuickSellItems();var quickSellItemsCount=document.getElementById('quickSellItemslength_'+this.quickSellAssociationProductId).value;if(quickSellItemsCount!=0){for(var i=0;i<this.quickSellItems.length;i++){updateParamObject(this.params,"catEntryId",this.quickSellItems[i],false,-1);updateParamObject(this.params,"quantity",this.quickSellItemsQuantity[i],false,-1);}}}
if(shoppingActionsJS.storeId!=null&&shoppingActionsJS.catalogId!=null){this.params['storeId']=shoppingActionsJS.storeId;this.params['catalogId']=shoppingActionsJS.catalogId;}
shoppingActionsJS.saveAddedProductInfo(this.catEntryQuantity,this.catEntryParams.id,productId,this.selectedAttributes);this.close();if(!submitRequest()){return;}
cursor_wait();wc.service.invoke(shopCartService,this.params);},resolveSKU:function(){var catentry_id="";this.toggleQuickViewCartButton(catentry_id);if(this.catEntryParams.skus.length==1){this.toggleQuickViewCartButton(this.catEntryParams.skus[0].id);$("#selectedCatalogEntry").val(this.catEntryParams.skus[0].id);return this.catEntryParams.skus[0].id;}
for(idx=0;idx<this.catEntryParams.skus.length;idx++){var matches=0;var attributeCount=0;for(attribute in this.catEntryParams.skus[idx].attributes){attributeCount++;if(this.catEntryParams.attributes&&this.catEntryParams.skus[idx].attributes[attribute]==this.catEntryParams.attributes[attribute]){matches++;}else{break;}}
if(0!=matches&&matches==attributeCount){this.toggleQuickViewCartButton(this.catEntryParams.skus[idx].id);$("#selectedCatalogEntry").val(this.catEntryParams.skus[idx].id);return this.catEntryParams.skus[idx].id;}}
return-1;},showQuickInfoButton:function(id){var quickInfoBtn=dojo.byId(id);if(quickInfoBtn!=null&&quickInfoBtn!='undefined'){quickInfoBtn.style.visibility="visible";}},hideQuickInfoButton:function(id){var quickInfoBtn=dojo.byId(id);if(quickInfoBtn!=null&&quickInfoBtn!='undefined'){quickInfoBtn.style.visibility="";}},shiftTabHideQuickInfoButton:function(id,event){if((event.shiftKey)&&(event.keyCode==dojo.keys.TAB)){this.hideQuickInfoButton(id);}},close:function(focusElement){dijit.byId('quickInfoPopup').hide();if(focusElement!=null&&focusElement!='undefined'&&document.getElementById(focusElement)){document.getElementById(focusElement).focus();}},setFocus:function(event){if(event.keyCode==dojo.keys.ESCAPE&&dojo.byId('catEntryParamsForJS')){var catEntryParams=dojo.byId("catEntryParamsForJS").value;var catEntryId=dojo.fromJson(catEntryParams).id;if(document.getElementById('catalogEntry_img'+catEntryId)){document.getElementById('catalogEntry_img'+catEntryId).focus();}}},selectDefaultSwatch:function(){var swatchElement=dojo.query("a[id^='WC_QuickInfo_Swatch_']")[0];if(swatchElement){eval(dojo.attr(swatchElement,"href"));}},replaceCartItem:function(productId){this.setValues(productId);if(!this.validate()){return;}
var catalogEntryId=this.resolveSKU();if(-1==catalogEntryId){MessageHelper.displayErrorMessage(storeNLS['ERR_RESOLVING_SKU']);return;}
this.close();var addressId="";var shipModeId="";var physicalStoreId="";var typeId=dojo.byId("shipmentTypeId");if(null!=dojo.byId("addressId_all")&&null!=dojo.byId("shipModeId_all")){if(null==typeId||typeId.value!="1"){addressId=dojo.byId("addressId_all").value;}else if(null!=dojo.byId("physicalStoreId")){physicalStoreId=dojo.byId("physicalStoreId").value;}
shipModeId=dojo.byId("shipModeId_all").value;}else if(null!=dojo.byId("MS_ShipmentAddress_"+this.replaceOrderItemId)&&null!=dojo.byId("MS_ShippingMode_"+this.replaceOrderItemId)){addressId=dojo.byId("MS_ShipmentAddress_"+this.replaceOrderItemId).value;shipModeId=dojo.byId("MS_ShippingMode_"+this.replaceOrderItemId).value;}
if(this.replaceOrderItemId!=""&&categoryDisplayJS){shoppingActionsJS.replaceItemAjaxHelper(catalogEntryId,this.catEntryQuantity,this.replaceOrderItemId,addressId,shipModeId,physicalStoreId);}else{console.error("categoryDisplayJS not defined");}},setSelAttributes:function(itemId,productId){this.showInlineDetails(itemId);this.setValues(itemId);this.selectCurrentAttributes(itemId);},selectInlineSwatch:function(selectedAttributeName,selectedAttributeValue,swatchId,swatchGrp,productId){if(dojo.hasClass("quickInfoSwatch_"+selectedAttributeName+"_"+selectedAttributeValue+"_"+productId,"color_swatch_disabled")){return false;}
this.setValues(productId);var swatchNames=dojo.byId("WC_QuickInfo_SwatchNames_"+productId).value.split("_");var currentSwatchPos=-1;for(var i=0;i<swatchNames.length;i++){if(swatchNames[i]==selectedAttributeName){currentSwatchPos=i;break;}}
var currentSwatchkey="quickInfoSwatch_"+selectedAttributeName+"_"+selectedAttributeValue+"_"+productId;var currentSwatchkeyLink="WC_QuickInfo_Swatch_"+selectedAttributeName+"_"+selectedAttributeValue+"_"+productId;var validSwatchArr=new Array();for(idx in this.catEntryParams.skus){var validItem=false;var entitledItem=this.catEntryParams.skus[idx];for(attribute in entitledItem.attributes){if(selectedAttributeName==attribute&&selectedAttributeValue==entitledItem.attributes[attribute]&&entitledItem.buyable){validItem=true;break;}}
if(validItem){for(attribute in entitledItem.attributes){var attributePos=-1;for(var i=0;i<swatchNames.length;i++){if(swatchNames[i]==attribute){attributePos=i;break;}}
if(attributePos>currentSwatchPos){validSwatchArr.push(attribute+"_"+entitledItem.attributes[attribute]+"_"+productId);}}}}
var swatchesDisabled=new Array();var selectedSwatches=new Array();for(idx in this.catEntryParams.skus){var entitledItem=this.catEntryParams.skus[idx];for(attribute in entitledItem.attributes){var attributePos=-1;for(var i=0;i<swatchNames.length;i++){if(swatchNames[i]==attribute){attributePos=i;break;}}
if(attributePos>currentSwatchPos){var swatchSelection=attribute+"_"+entitledItem.attributes[attribute]+"_"+productId;var swatchId="quickInfoSwatch_"+swatchSelection;var swatchLinkId="WC_QuickInfo_Swatch_"+swatchSelection;var validSwatchArrPos=-1;for(var i=0;i<validSwatchArr.length;i++){if(validSwatchArr[i]==swatchSelection){validSwatchArrPos=i;break;}}
var swatchesDisabledPos=-1;for(var i=0;i<swatchesDisabled.length;i++){if(swatchesDisabled[i]==swatchSelection){swatchesDisabledPos=i;break;}}
if(validSwatchArrPos>-1){if(!dojo.hasClass(swatchId,"color_swatch_selected")){dojo.byId(swatchId).className="color_swatch";dojo.byId(swatchId).src=dojo.byId(swatchId).src.replace("_disabled.png","_enabled.png");document.getElementById(swatchLinkId).setAttribute("aria-disabled","false");}}
else if(swatchesDisabledPos==-1){swatchesDisabled.push(swatchSelection);if(dojo.hasClass(swatchId,"color_swatch_selected")){selectedSwatches.push(swatchId);}
dojo.byId(swatchId).className="color_swatch_disabled";dojo.byId(swatchId).src=dojo.byId(swatchId).src.replace("_enabled.png","_disabled.png");document.getElementById(swatchLinkId).setAttribute("aria-disabled","true");}}
if(document.getElementById("WC_QuickInfo_Swatch_"+attribute+"_"+entitledItem.attributes[attribute]+"_"+productId)!=null){document.getElementById("WC_QuickInfo_Swatch_"+attribute+"_"+entitledItem.attributes[attribute]+"_"+productId).setAttribute("aria-checked","false");}}}
for(idx in selectedSwatches){var selectedSwatch=selectedSwatches[idx];var idSelector="img[id^='"+selectedSwatch.substring(0,selectedSwatch.lastIndexOf("_"))+"']";var swatchSelected=false;dojo.query(idSelector).forEach(function(node,index,arr){if(!swatchSelected&&dojo.hasClass(node,"color_swatch")){var values=node.id.split("_");QuickInfoJS.selectSwatch(values[1],values[2],"quickInfoSwatch_"+values[1]+"_"+values[2]+"_"+productId,"quickInfoSwatch_"+values[1]+"_");QuickInfoJS.selectItem(true);swatchSelected=true;}});}
selector="img[id^='"+swatchGrp+"']";dojo.query(selector).forEach(function(node,index,arr){if(!dojo.hasClass(node,"color_swatch_disabled")){dojo.addClass(node,"color_swatch");if(dojo.hasClass(node,"color_swatch_selected")){dojo.removeClass(node,"color_swatch_selected");}}});selectorList="li[id^='"+swatchGrp+"']";dojo.query(selectorList).forEach(function(node,index,arr){if(!dojo.hasClass(node,"color_swatch_disabled")){dojo.addClass(node,"color_swatch_wrapper");if(dojo.hasClass(node,"color_swatch_selected")){dojo.removeClass(node,"color_swatch_selected");}}});dojo.byId(currentSwatchkey).className="color_swatch_selected";if(document.getElementById(currentSwatchkey+"_list")!=undefined){document.getElementById(currentSwatchkey+"_list").className="color_swatch_selected";}
dojo.byId("quickinfo_swatch_selection_SB_"+selectedAttributeName+"_"+productId).innerHTML=selectedAttributeValue;document.getElementById(currentSwatchkeyLink).setAttribute("aria-checked","true");this.setSelectedAttribute(selectedAttributeName,selectedAttributeValue);},selectCurrentAttributes:function(productItemId){for(idx=0;idx<this.catEntryParams.skus.length;idx++){var selectedSKU=this.catEntryParams.skus[idx];if(selectedSKU.id==this.itemId){for(attribute in selectedSKU.attributes){var selectNode=dojo.query("select[alt='"+attribute+"']")[0];if(selectNode){selectNode.value=selectedSKU.attributes[attribute];this.setSelectedAttribute(attribute,selectNode.value);}else{var attrValue=selectedSKU.attributes[attribute];var selectedSwatchNode=dojo.byId("quickInfoSwatch_"+attribute+"_"+attrValue);if(selectedSwatchNode!=null){this.selectSwatch(attribute,attrValue,"quickInfoSwatch_"+attribute+"_"+attrValue,"quickInfoSwatch_"+attribute+"_",productItemId);}}}
this.notifyAttributeChange();this.selectItem(true);return;}}},getQuickInfoImage:function(fullImage,imagePrefix){if(fullImage=="")return fullImage;if(imagePrefix==undefined){return fullImage.replace(this.productImgDimensions,this.quickInfoImgDimensions);}
else{return imagePrefix+fullImage.replace(this.productImgDimensions,this.quickInfoImgDimensions)+"?$osmedium$";}},toggleExpand:function(id){var attrDiv=dojo.byId("AttrSelection_"+id);if(attrDiv.className=="InlineEdit"){attrDiv.className="InlineEdit InlineClose"
attrDiv.style.display="block";dojo.byId("ExpandText_"+id).innerHTML="";}
else{attrDiv.className="InlineEdit"
attrDiv.style.display="none";dojo.byId("ExpandText_"+id).innerHTML="Edit/View";}},updateOrderItem:function(productId,orderItemId,orderId){var params={};params.storeId=WCParamJS.storeId;params.catalogId=WCParamJS.catalogId;params.langId=WCParamJS.langId;params.orderItemId=orderItemId;params.orderId=orderId;params.productId=productId;wc.service.invoke("AjaxUpdateOrderItem1",params);},redirectMoreWays:function(boxId,SKU,URL){var pdpUrl;if(dojo.byId(boxId)!=null){pdpUrl="/shop"+URL.substr(URL.indexOf("/en-us/")).replace(/\/([a-z]{2})\//i,"/$1/$1-where-to-buy/")+"?ps-sku="+SKU;window.open(pdpUrl,"_self");}},redirectSaleAlert:function(boxId){var pdpUrl;if(dojo.byId(boxId)!=null){pdpUrl=dojo.byId(boxId).href;if(pdpUrl.indexOf("?")>=0){pdpUrl=pdpUrl+"&sale=true";}else{pdpUrl=pdpUrl+"?sale=true";}
window.open(pdpUrl,"_self");}}}}
shoppingActionsJS={langId:"-1",storeId:"",catalogId:"",userType:"",baseItemAddedToCart:false,entitledItems:[],entitledItemJsonObject:null,selectedAttributesList:new Object(),moreInfoUrl:"",productFullName:"",isPopup:false,displayPriceRange:true,itemPriceJsonOject:[],allSwatchesArrayList:new Object(),skuImageId:"",cookieKeyPrefix:"CompareItems_",cookieDelimiter:";",maxNumberProductsAllowedToCompare:4,minNumberProductsAllowedToCompare:2,baseCatalogEntryId:0,selectedProducts:new Object(),productList:new Object(),currencySymbol:"",compareReturnName:"",searchTerm:"",search01:"'",search02:'"',replaceStr01:/\\\'/g,replaceStr02:/\\\"/g,ampersandChar:/&/g,ampersandEntityName:"&amp;",orderId:"",paypalRedirectViewURL:"",shipmentType:"",paymentMethod:"",paypalOrigin:"",shippingAddressId:"",recipientName:"",streetAddress:"",extendedAddress:"",locality:"",countryCodeAlpha2:"",postalCode:"",region:"",phone:"",amazonRedirectViewURL:"",productAddedList:new Object(),setCompareReturnName:function(compareReturnName){this.compareReturnName=compareReturnName;},setSearchTerm:function(searchTerm){this.searchTerm=searchTerm;},setCommonParameters:function(langId,storeId,catalogId,userType,currencySymbol){this.langId=langId;this.storeId=storeId;this.catalogId=catalogId;this.userType=userType;this.currencySymbol=currencySymbol;},setCustomParameters:function(orderId,shipmentType,paymentMethod,paypalRedirectViewURL,origin){this.orderId=orderId;this.shipmentType=shipmentType;this.paymentMethod=paymentMethod;this.paypalRedirectViewURL=paypalRedirectViewURL+'?langId='+this.langId+'&storeId='+this.storeId+'&catalogId='+this.catalogId+'&shipmentType='+this.shipmentType+'&paymentMethod='+this.paymentMethod;this.paypalOrigin=origin;},setShippingAddrFromPaymentPage:function(recipientName,streetAddress,extendedAddress,locality,countryCodeAlpha2,postalCode,region,phone,shippingAddressId)
{this.recipientName=recipientName;this.streetAddress=streetAddress;this.extendedAddress=extendedAddress;this.locality=locality;this.countryCodeAlpha2=countryCodeAlpha2;this.postalCode=postalCode;this.region=region;this.phone=phone;this.shippingAddressId=shippingAddressId;},setEntitledItems:function(entitledItemArray){this.entitledItems=entitledItemArray;},getCatalogEntryId:function(entitledItemId){var attributeArray=[];var selectedAttributes=this.selectedAttributesList[entitledItemId];for(attribute in selectedAttributes){attributeArray.push(attribute+"_"+selectedAttributes[attribute]);}
return this.resolveSKU(attributeArray);},getCatalogEntryIdforProduct:function(selectedAttributes){var attributeArray=[];for(attribute in selectedAttributes){attributeArray.push(attribute+"_"+selectedAttributes[attribute]);}
return this.resolveSKU(attributeArray);},getEntitledItemJsonObject:function(){return this.entitledItemJsonObject;},resolveSKU:function(attributeArray){console.debug("Resolving SKU >> "+attributeArray+">>"+this.entitledItems);var catentry_id="";var attributeArrayCount=attributeArray.length;if(this.entitledItems.length==1){return this.entitledItems[0].catentry_id;}
for(x in this.entitledItems){var catentry_id=this.entitledItems[x].catentry_id;var Attributes=this.entitledItems[x].Attributes;var attributeCount=0;for(index in Attributes){attributeCount++;}
if(attributeArrayCount==0&&attributeCount==0){return catentry_id;}
if(attributeCount!=0&&attributeArrayCount>=attributeCount){var matchedAttributeCount=0;for(attributeName in attributeArray){var attributeValue=attributeArray[attributeName];if(attributeValue in Attributes){matchedAttributeCount++;}}
if(attributeCount==matchedAttributeCount){console.debug("CatEntryId:"+catentry_id+" for Attribute: "+attributeArray);return catentry_id;}}}
return null;},setSelectedAttribute:function(selectedAttributeName,selectedAttributeValue,entitledItemId,skuImageId,imageField){console.debug(selectedAttributeName+" : "+selectedAttributeValue);var selectedAttributes=this.selectedAttributesList[entitledItemId];if(selectedAttributes==null){selectedAttributes=new Object();}
selectedAttributeValue=selectedAttributeValue.replace(this.replaceStr01,this.search01);selectedAttributeValue=selectedAttributeValue.replace(this.replaceStr02,this.search02);selectedAttributeValue=selectedAttributeValue.replace(this.ampersandChar,this.ampersandEntityName);selectedAttributes[selectedAttributeName]=selectedAttributeValue;this.moreInfoUrl=this.moreInfoUrl+'&'+selectedAttributeName+'='+selectedAttributeValue;this.selectedAttributesList[entitledItemId]=selectedAttributes;this.changeProdImage(entitledItemId,selectedAttributeName,selectedAttributeValue,skuImageId,imageField);},setSelectedAttributeOfProduct:function(productId,selectedAttributeName,selectedAttributeValue,isSingleSKU){var selectedAttributesForProduct=null;if(this.selectedProducts[productId]){selectedAttributesForProduct=this.selectedProducts[productId];}else{selectedAttributesForProduct=new Object();}
if(null!=selectedAttributeName&&''!=selectedAttributeName){selectedAttributesForProduct[selectedAttributeName]=selectedAttributeValue;}
this.selectedProducts[productId]=selectedAttributesForProduct;var entitledItemJSON=eval('('+dojo.byId("entitledItem_"+productId).innerHTML+')');this.setEntitledItems(entitledItemJSON);var catalogEntryId=this.getCatalogEntryIdforProduct(selectedAttributesForProduct);if(catalogEntryId==null){catalogEntryId=0;}else{this.changePrice("entitledItem_"+productId,false,true,productId);if(typeof MerchandisingAssociationJS!='undefined'){if(MerchandisingAssociationJS.baseItemParams!=null){if(MerchandisingAssociationJS.baseItemParams.type=='BundleBean'){for(idx=0;idx<MerchandisingAssociationJS.baseItemParams.components.length;idx++){if(productId==MerchandisingAssociationJS.baseItemParams.components[idx].productId){MerchandisingAssociationJS.baseItemParams.components[idx].id=catalogEntryId;}}}}}}
var productDetails=null;if(this.productList[productId]){productDetails=this.productList[productId];}else{productDetails=new Object();this.productList[productId]=productDetails;productDetails.baseItemId=productId;}
productDetails.id=catalogEntryId;if(productDetails.quantity){dojo.topic.publish("Quantity_Changed",dojo.toJson(productDetails));}
if(!isSingleSKU){if(catalogEntryId!=0){dojo.topic.publish('DefiningAttributes_Resolved_'+productId,catalogEntryId,productId);}
else{dojo.topic.publish('DefiningAttributes_Changed_'+productId,catalogEntryId,productId);}}},SetProductName:function(productId){if(document.getElementById("ProductInfoName_"+productId)!=null){this.productFullName=$("#ProductInfoName_"+productId).text();}},Add2ShopCartAjax:function(entitledItemId,quantity,isPopup,productId,customParams)
{if(browseOnly){MessageHelper.displayErrorMessage(storeNLS['ERROR_ADD2CART_BROWSE_ONLY']);return;}
var entitledItemJSON;if(dojo.byId(entitledItemId)!=null){entitledItemJSON=eval('('+dojo.byId(entitledItemId).innerHTML+')');}else{entitledItemJSON=this.getEntitledItemJsonObject();}
this.setEntitledItems(entitledItemJSON);var catalogEntryId=this.getCatalogEntryId(entitledItemId);if(catalogEntryId!=null){var productId=entitledItemId.substring(entitledItemId.indexOf("_")+1);this.AddItem2ShopCartAjax(catalogEntryId,quantity,customParams,productId);this.baseItemAddedToCart=true;if(dijit.byId('second_level_category_popup')!=null){hidePopup('second_level_category_popup');}}
else if(isPopup==true){dojo.byId('second_level_category_popup').style.zIndex='1';MessageHelper.formErrorHandleClient('addToCartLinkAjax',storeNLS['ERR_RESOLVING_SKU']);}else{MessageHelper.displayErrorMessage(storeNLS['ERR_RESOLVING_SKU']);this.baseItemAddedToCart=false;}},AddItem2ShopCartAjax:function(catEntryIdentifier,quantity,customParams,productId)
{if(browseOnly){MessageHelper.displayErrorMessage(storeNLS['ERROR_ADD2CART_BROWSE_ONLY']);return;}
var params=[];params.storeId=this.storeId;params.catalogId=this.catalogId;params.langId=this.langId;params.orderId=".";params.inventoryValidation="true";params.calculateOrder="0";var ajaxShopCartService="AddOrderItem";this.productAddedList=new Object();if(dojo.isArray(catEntryIdentifier)&&dojo.isArray(quantity)){for(var i=0;i<catEntryIdentifier.length;i++){if(!isPositiveInteger(quantity[i])){MessageHelper.displayErrorMessage(storeNLS['QUANTITY_INPUT_ERROR']);return;}
params["catEntryId_"+(i+1)]=catEntryIdentifier[i];params["quantity_"+(i+1)]=quantity[i];}}
else{if(!isPositiveInteger(quantity)){MessageHelper.displayErrorMessage(storeNLS['QUANTITY_INPUT_ERROR']);return;}
params.catEntryId=catEntryIdentifier;params.quantity=quantity;var selectedAttrList=new Object();for(attr in this.selectedAttributesList['entitledItem_'+productId]){selectedAttrList[attr]=this.selectedAttributesList['entitledItem_'+productId][attr];}
if(productId==undefined){this.saveAddedProductInfo(quantity,catEntryIdentifier,catEntryIdentifier,selectedAttrList);}else{this.saveAddedProductInfo(quantity,productId,catEntryIdentifier,selectedAttrList);}}
if(customParams!=null&&customParams!='undefined'){for(i in customParams){params[i]=customParams[i];}
if(customParams['catalogEntryType']=='dynamicKit'){ajaxShopCartService="AddPreConfigurationToCart";}}
var contractIdElements=document.getElementsByName('contractSelectForm_contractId');if(contractIdElements!=null&&contractIdElements!="undefined"){for(i=0;i<contractIdElements.length;i++){if(contractIdElements[i].checked){params.contractId=contractIdElements[i].value;break;}}}
if(!submitRequest()){return;}
cursor_wait();wc.service.invoke(ajaxShopCartService,params);this.baseItemAddedToCart=true;if(document.getElementById("headerShopCartLink")&&document.getElementById("headerShopCartLink").style.display!="none")
{document.getElementById("headerShopCart").focus();}
else
{if(document.getElementById("headerShopCart1")){document.getElementById("headerShopCart1").focus();}}},AddCollection2ShopCartAjax:function(collectionId,collectionQty,collectionProdId){if(browseOnly){MessageHelper.displayErrorMessage(storeNLS['ERROR_ADD2CART_BROWSE_ONLY']);return;}
var params=[];params.storeId=this.storeId;params.catalogId=this.catalogId;params.langId=this.langId;params.orderId=".";params.inventoryValidation="true";params.calculateOrder="0";params.catEntryId_1=collectionId;params.qty_1=collectionQty;params.quantity_1=collectionQty;var ajaxShopCartService="CollectionsOrderItemAdd";var resolvedSKUId=[];var resolvedSKUQty=[];resolvedSKUId=document.getElementsByClassName('resolvedSKU');resolvedSKUQty=document.getElementsByClassName('resolvedSKUQty');for(var i=0;i<resolvedSKUId.length;i++){params["childCatEntryIds_"+(i+1)]=resolvedSKUId[i].value;}
for(var i=0;i<resolvedSKUQty.length;i++){params["childCatEntryIdQtys_"+(i+1)]=resolvedSKUQty[i].value;}
if(!submitRequest()){return;}
cursor_wait();wc.service.invoke(ajaxShopCartService,params);},AddBundle2ShopCartAjax:function(){if(browseOnly){MessageHelper.displayErrorMessage(storeNLS['ERROR_ADD2CART_BROWSE_ONLY']);return;}
var ajaxShopCartService="AddOrderItem";var params=[];params.storeId=this.storeId;params.catalogId=this.catalogId;params.langId=this.langId;params.orderId=".";params.inventoryValidation="true";params.calculateOrder="0";var idx=1;this.productAddedList=new Object();for(productId in this.productList){var productDetails=this.productList[productId];var quantity=dojo.number.parse(productDetails.quantity);if(quantity==0){continue;}
if(productDetails.id==0){MessageHelper.displayErrorMessage(storeNLS['ERR_RESOLVING_SKU']);return;}
if(isNaN(quantity)||quantity<0){MessageHelper.displayErrorMessage(storeNLS['QUANTITY_INPUT_ERROR']);return;}
params["catEntryId_"+idx]=productDetails.id;params["quantity_"+idx++]=quantity;this.baseItemAddedToCart=true;this.saveAddedProductInfo(quantity,productId,productDetails.id,this.selectedProducts[productId]);}
if(!submitRequest()){return;}
cursor_wait();wc.service.invoke(ajaxShopCartService,params);},resetProductAddedList:function(){shoppingActionsJS.productAddedList=new Object();},saveAddedProductInfo:function(quantity,productId,skuId,attrList){var productName="";if(document.getElementById("ProductInfoName_"+productId)!=null){productName=document.getElementById("ProductInfoName_"+productId).value;}else if(document.getElementById("ProductInfoName_"+skuId)!=null){productName=document.getElementById("ProductInfoName_"+skuId).value;}
var productThumbnail="";if(document.getElementById("ProductInfoImage_"+productId)!=null){productThumbnail=document.getElementById("ProductInfoImage_"+productId).value;}else if(document.getElementById("ProductInfoImage_"+skuId)!=null){productThumbnail=document.getElementById("ProductInfoImage_"+skuId).value;}
var productPrice="";if(document.getElementById('ProductInfoPrice_'+productId)!=null){productPrice=document.getElementById('ProductInfoPrice_'+productId).value;}else if(document.getElementById('ProductInfoPrice_'+skuId)!=null){productPrice=document.getElementById('ProductInfoPrice_'+skuId).value;}
var productAdded=[productName,productThumbnail,productPrice,quantity,attrList];if(productId!=skuId){this.productAddedList[skuId]=productAdded;}else{this.productAddedList[productId]=productAdded;}
dojo.topic.publish("ProductInfo_Added",this.productAddedList);},setSKUImageId:function(skuImageId){this.skuImageId=skuImageId;},getImageForSKU:function(entitledItemId,imageField){var attributeArray=[];var selectedAttributes=this.selectedAttributesList[entitledItemId];for(attribute in selectedAttributes){attributeArray.push(attribute+"_"+selectedAttributes[attribute]);}
return this.resolveImageForSKU(attributeArray,imageField);},resolveImageForSKU:function(attributeArray,imageField){console.debug("Resolving SKU >> "+attributeArray+">>"+this.entitledItems);var imagePath="";var attributeArrayCount=attributeArray.length;for(x in this.entitledItems){if(null!=imageField){var imagePath=this.entitledItems[x][imageField];}else{var imagePath=this.entitledItems[x].ItemImage467;}
var Attributes=this.entitledItems[x].Attributes;var attributeCount=0;for(index in Attributes){attributeCount++;}
if(attributeArrayCount==0&&attributeCount==0){return imagePath;}
if(attributeCount!=0&&attributeArrayCount>=attributeCount){var matchedAttributeCount=0;for(attributeName in attributeArray){var attributeValue=attributeArray[attributeName];if(attributeValue in Attributes){matchedAttributeCount++;}}
if(attributeCount==matchedAttributeCount){console.debug("ItemImage:"+imagePath+" for Attribute: "+attributeArray);var imageArray=[];imageArray.push(imagePath);imageArray.push(this.entitledItems[x].ItemThumbnailImage);if(this.entitledItems[x].ItemAngleThumbnail!=null&&this.entitledItems[x].ItemAngleThumbnail!=undefined){imageArray.push(this.entitledItems[x].ItemAngleThumbnail);imageArray.push(this.entitledItems[x].ItemAngleFullImage);}
return imageArray;}}}
return null;},changeViewImages:function(itemAngleThumbnail,itemAngleFullImage){var imageCount=0;for(x in itemAngleThumbnail){var prodAngleCount=imageCount;imageCount++;if(null!=dojo.byId("WC_CachedProductOnlyDisplay_images_1_"+imageCount)){dojo.byId("WC_CachedProductOnlyDisplay_images_1_"+imageCount).src=itemAngleThumbnail[x];}
if(null!=dojo.byId("WC_CachedProductOnlyDisplay_links_1_"+imageCount)){dojo.byId("WC_CachedProductOnlyDisplay_links_1_"+imageCount).href="JavaScript:changeThumbNail('productAngleLi"+prodAngleCount+"','"+itemAngleFullImage[x]+"');";}
if(null!=dojo.byId("productAngleLi"+prodAngleCount)&&dojo.byId("productAngleLi"+prodAngleCount).className=="selected"){changeThumbNail("productAngleLi"+prodAngleCount,itemAngleFullImage[x]);}}},changeProdImage:function(entitledItemId,swatchAttrName,swatchAttrValue,skuImageId,imageField){if(dojo.byId(entitledItemId)!=null){entitledItemJSON=eval('('+dojo.byId(entitledItemId).innerHTML+')');}
this.setEntitledItems(entitledItemJSON);var productId=entitledItemId.substring(entitledItemId.indexOf("_")+1);var skuImage=null;var imageArr=shoppingActionsJS.getImageForSKU(entitledItemId,imageField);if(imageArr!=null){skuImage=imageArr[0];}
if(skuImageId!=undefined){this.setSKUImageId(skuImageId);}
if(skuImage!=null){if(dojo.byId(this.skuImageId)!=null){document.getElementById(this.skuImageId).src=skuImage;if(document.getElementById("ProductInfoImage_"+productId)!=null){document.getElementById("ProductInfoImage_"+productId).value=skuImage;}
var itemAngleThumbnail=imageArr[2];var itemAngleFullImage=imageArr[3];if(itemAngleThumbnail!=null&&itemAngleThumbnail!=undefined){shoppingActionsJS.changeViewImages(itemAngleThumbnail,itemAngleFullImage);}}}else{var imageFound=false;for(x in this.entitledItems){var Attributes=this.entitledItems[x].Attributes;if(null!=imageField){var itemImage=this.entitledItems[x][imageField];}else{var itemImage=this.entitledItems[x].ItemImage467;}
var itemAngleThumbnail=this.entitledItems[x].ItemAngleThumbnail;var itemAngleFullImage=this.entitledItems[x].ItemAngleFullImage;for(y in Attributes){var index=y.indexOf("_");var entitledSwatchName=y.substring(0,index);var entitledSwatchValue=y.substring(index+1);if(entitledSwatchName==swatchAttrName&&entitledSwatchValue==swatchAttrValue){if(null!=dojo.byId(this.skuImageId)){dojo.byId(this.skuImageId).src=itemImage;if(document.getElementById("ProductInfoImage_"+productId)!=null){document.getElementById("ProductInfoImage_"+productId).value=itemImage;}}
if(itemAngleThumbnail!=null&&itemAngleThumbnail!=undefined){shoppingActionsJS.changeViewImages(itemAngleThumbnail,itemAngleFullImage);}
imageFound=true;break;}}
if(imageFound){break;}}}},updateSwatchListView:function(){var swatchArray=dojo.query("a[id^='swatch_array_']");for(var i=0;i<swatchArray.length;i++){var swatchArrayElement=swatchArray[i];eval(dojo.attr(swatchArrayElement,"href"));}
var swatchSkuImage=dojo.query("a[id^='swatch_setSkuImage_']");for(var i=0;i<swatchSkuImage.length;i++){var swatchSkuImageElement=swatchSkuImage[i];eval(dojo.attr(swatchSkuImageElement,"href"));}
var swatchDefault=dojo.query("a[id^='swatch_selectDefault_']");for(var i=0;i<swatchDefault.length;i++){var swatchDefaultElement=swatchDefault[i];eval(dojo.attr(swatchDefaultElement,"href"));}},selectSwatch:function(selectedAttributeName,selectedAttributeValue,entitledItemId,doNotDisable,skuImageId,imageField){if(dojo.hasClass("swatch_"+entitledItemId+"_"+selectedAttributeValue,"color_swatch_disabled")){return;}
var selectedAttributes=this.selectedAttributesList[entitledItemId];for(attribute in selectedAttributes){if(attribute==selectedAttributeName){if(selectedAttributes[attribute]!=selectedAttributeValue){var swatchElement=dojo.byId("swatch_"+entitledItemId+"_"+selectedAttributes[attribute]);swatchElement.className="color_swatch";swatchElement.src=swatchElement.src.replace("_disabled.png","_enabled.png");dojo.byId("swatch_link_"+entitledItemId+"_"+selectedAttributes[attribute]).title=swatchElement.alt;}}
if(document.getElementById("swatch_link_"+entitledItemId+"_"+selectedAttributes[attribute])!=null){document.getElementById("swatch_link_"+entitledItemId+"_"+selectedAttributes[attribute]).setAttribute("aria-checked","false");}}
this.makeSwatchSelection(selectedAttributeName,selectedAttributeValue,entitledItemId,doNotDisable,skuImageId,imageField);},makeSwatchSelection:function(swatchAttrName,swatchAttrValue,entitledItemId,doNotDisable,skuImageId,imageField){this.setSelectedAttribute(swatchAttrName,swatchAttrValue,entitledItemId,skuImageId,imageField);document.getElementById("swatch_"+entitledItemId+"_"+swatchAttrValue).className="color_swatch_selected";document.getElementById("swatch_link_"+entitledItemId+"_"+swatchAttrValue).setAttribute("aria-checked","true");document.getElementById("swatch_selection_label_"+entitledItemId+"_"+swatchAttrName).className="header color_swatch_label";if(document.getElementById("swatch_selection_"+entitledItemId+"_"+swatchAttrName).style.display=="none"){document.getElementById("swatch_selection_"+entitledItemId+"_"+swatchAttrName).style.display="inline";}
document.getElementById("swatch_selection_"+entitledItemId+"_"+swatchAttrName).innerHTML=swatchAttrValue;this.updateSwatchImages(swatchAttrName,entitledItemId,doNotDisable,imageField);},addToAllSwatchsArray:function(swatchName,swatchValue,swatchImg1,entitledItemId){var swatchList=this.allSwatchesArrayList[entitledItemId];if(swatchList==null){swatchList=new Array();;}
if(!this.existInAllSwatchsArray(swatchName,swatchValue,swatchList)){var swatchRecord=new Array();swatchRecord[0]=swatchName;swatchRecord[1]=swatchValue;swatchRecord[2]=swatchImg1;swatchRecord[4]=document.getElementById("swatch_link_"+entitledItemId+"_"+swatchValue).onclick;swatchList.push(swatchRecord);this.allSwatchesArrayList[entitledItemId]=swatchList;}},existInAllSwatchsArray:function(swatchName,swatchValue,swatchList){for(var i=0;i<swatchList.length;i++){var attrName=swatchList[i][0];var attrValue=swatchList[i][1];if(attrName==swatchName&&attrValue==swatchValue){return true;}}
return false;},makeDefaultSwatchSelection:function(entitledItemId,doNotDisable){if(this.entitledItems.length==0){if(dojo.byId(entitledItemId)!=null){entitledItemJSON=eval('('+dojo.byId(entitledItemId).innerHTML+')');}
this.setEntitledItems(entitledItemJSON);}
for(x in this.entitledItems){var Attributes=this.entitledItems[x].Attributes;for(y in Attributes){var index=y.indexOf("_");var swatchName=y.substring(0,index);var swatchValue=y.substring(index+1);this.makeSwatchSelection(swatchName,swatchValue,entitledItemId,doNotDisable,imageField);}
break;}},updateSwatchImages:function(selectedAttrName,entitledItemId,doNotDisable,imageField){var swatchToUpdate=new Array();var selectedAttributes=this.selectedAttributesList[entitledItemId];var selectedAttrValue=selectedAttributes[selectedAttrName];var swatchList=this.allSwatchesArrayList[entitledItemId];for(var i=0;i<swatchList.length;i++){var attrName=swatchList[i][0];var attrValue=swatchList[i][1];var attrImg1=swatchList[i][2];var attrImg2=swatchList[i][3];var attrOnclick=swatchList[i][4];if(attrName!=doNotDisable&&attrName!=selectedAttrName){var swatchRecord=new Array();swatchRecord[0]=attrName;swatchRecord[1]=attrValue;swatchRecord[2]=attrImg1;swatchRecord[4]=attrOnclick;swatchRecord[5]=false;swatchToUpdate.push(swatchRecord);}}
for(x in this.entitledItems){var Attributes=this.entitledItems[x].Attributes;for(y in Attributes){var index=y.indexOf("_");var entitledSwatchName=y.substring(0,index);var entitledSwatchValue=y.substring(index+1);if(entitledSwatchName==selectedAttrName&&entitledSwatchValue==selectedAttrValue){for(z in Attributes){var index2=z.indexOf("_");var entitledSwatchName2=z.substring(0,index2);var entitledSwatchValue2=z.substring(index2+1);if(y!=z){for(i in swatchToUpdate){var swatchToUpdateName=swatchToUpdate[i][0];var swatchToUpdateValue=swatchToUpdate[i][1];if(entitledSwatchName2==swatchToUpdateName&&entitledSwatchValue2==swatchToUpdateValue){swatchToUpdate[i][5]=true;}}}}}}}
var disabledAttributes=[];for(i in swatchToUpdate){var swatchToUpdateName=swatchToUpdate[i][0];var swatchToUpdateValue=swatchToUpdate[i][1];var swatchToUpdateImg1=swatchToUpdate[i][2];var swatchToUpdateImg2=swatchToUpdate[i][3];var swatchToUpdateOnclick=swatchToUpdate[i][4];var swatchToUpdateEnabled=swatchToUpdate[i][5];if(swatchToUpdateEnabled){if(document.getElementById("swatch_"+entitledItemId+"_"+swatchToUpdateValue).className!="color_swatch_selected"){var swatchElement=dojo.byId("swatch_"+entitledItemId+"_"+swatchToUpdateValue);swatchElement.className="color_swatch";swatchElement.src=swatchElement.src.replace("_disabled.png","_enabled.png");dojo.byId("swatch_link_"+entitledItemId+"_"+swatchToUpdateValue).title=swatchElement.alt;}
document.getElementById("swatch_link_"+entitledItemId+"_"+swatchToUpdateValue).setAttribute("aria-disabled","false");document.getElementById("swatch_link_"+entitledItemId+"_"+swatchToUpdateValue).onclick=swatchToUpdateOnclick;}else{if(swatchToUpdateName!=doNotDisable){var swatchElement=dojo.byId("swatch_"+entitledItemId+"_"+swatchToUpdateValue);var swatchLinkElement=dojo.byId("swatch_link_"+entitledItemId+"_"+swatchToUpdateValue);swatchElement.className="color_swatch_disabled";swatchLinkElement.onclick=null;swatchElement.src=swatchElement.src.replace("_enabled.png","_disabled.png");var titleText=storeNLS["INV_ATTR_UNAVAILABLE"];swatchLinkElement.title=dojo.string.substitute(titleText,{0:swatchElement.alt});document.getElementById("swatch_link_"+entitledItemId+"_"+swatchToUpdateValue).setAttribute("aria-disabled","true");if(selectedAttributes[swatchToUpdateName]==swatchToUpdateValue){disabledAttributes.push(swatchToUpdate[i]);}}}}
for(i in disabledAttributes){var disabledAttributeName=disabledAttributes[i][0];var disabledAttributeValue=disabledAttributes[i][1];for(i in swatchToUpdate){var swatchToUpdateName=swatchToUpdate[i][0];var swatchToUpdateValue=swatchToUpdate[i][1];var swatchToUpdateEnabled=swatchToUpdate[i][5];if(swatchToUpdateName==disabledAttributeName&&swatchToUpdateValue!=disabledAttributeValue&&swatchToUpdateEnabled){this.makeSwatchSelection(swatchToUpdateName,swatchToUpdateValue,entitledItemId,doNotDisable,imageField);break;}}}},changePrice:function(entitledItemId,isPopup,displayPriceRange,productId){this.displayPriceRange=displayPriceRange;this.isPopup=isPopup;var entitledItemJSON;if(dojo.byId(entitledItemId)!=null&&!this.isPopup){entitledItemJSON=eval('('+dojo.byId(entitledItemId).innerHTML+')');}else{entitledItemJSON=this.getEntitledItemJsonObject();}
var catalogEntryId=null;this.setEntitledItems(entitledItemJSON);if(this.selectedProducts[productId]){var catalogEntryId=this.getCatalogEntryIdforProduct(this.selectedProducts[productId]);}else{var catalogEntryId=this.getCatalogEntryId(entitledItemId);}
if(catalogEntryId!=null){if(this.itemPriceJsonOject[catalogEntryId]!=null&&this.itemPriceJsonOject[catalogEntryId]!='undefined'){this.displayPrice(this.itemPriceJsonOject[catalogEntryId].catalogEntry,productId);console.debug("ShoppingActions.changePrice: using stored json object.");}
else{var parameters={};parameters.storeId=this.storeId;parameters.langId=this.langId;parameters.catalogId=this.catalogId;parameters.catalogEntryId=catalogEntryId;parameters.productId=productId;wc.service.declare({id:"getCatalogEntryDetailsSA",actionId:"getCatalogEntryDetailsSA",url:getAbsoluteURL()+appendWcCommonRequestParameters("GetCatalogEntryDetailsByIDView"),formId:"",successHandler:function(serviceResponse,ioArgs){shoppingActionsJS.displayPriceServiceResponse(serviceResponse,ioArgs);},failureHandler:function(serviceResponse,ioArgs){console.debug("ShoppingActions.changePrice: Unexpected error occurred during an xhrPost request.");}});wc.service.invoke("getCatalogEntryDetailsSA",parameters);}}
else{console.debug("ShoppingActions.changePrice: all attributes are not selected.");}},displayPriceServiceResponse:function(serviceResponse,ioArgs){var productId=ioArgs['args'].content['productId'];shoppingActionsJS.itemPriceJsonOject[serviceResponse.catalogEntry.catalogEntryIdentifier.uniqueID]=serviceResponse;shoppingActionsJS.displayPrice(serviceResponse.catalogEntry,productId);},displayPrice:function(catEntry,productId){var tempString;var popup=shoppingActionsJS.isPopup;if(popup==true){document.getElementById('productPrice').innerHTML=catEntry.offerPrice;document.getElementById('productName').innerHTML=catEntry.description[0].name;document.getElementById('productSKUValue').innerHTML=catEntry.catalogEntryIdentifier.externalIdentifier.partNumber;}
if(popup==false){var innerHTML="";var listPrice=dojo.currency.parse(catEntry.listPrice,{symbol:this.currencySymbol});var offerPrice=dojo.currency.parse(catEntry.offerPrice,{symbol:this.currencySymbol});this.setPriceInProductList(productId,offerPrice);if(!catEntry.listPriced||listPrice<=offerPrice){innerHTML="<span id='offerPrice_"+catEntry.catalogEntryIdentifier.uniqueID+"' class='price'>"+catEntry.offerPrice+"</span>";}
else{innerHTML="<span id='listPrice_"+catEntry.catalogEntryIdentifier.uniqueID+"' class='old_price'>"+catEntry.listPrice+"</span>"+"<span id='offerPrice_"+catEntry.catalogEntryIdentifier.uniqueID+"' class='price'>"+catEntry.offerPrice+"</span>";}
document.getElementById('price_display_'+productId).innerHTML=innerHTML
+"<input type='hidden' id='ProductInfoPrice_"+catEntry.catalogEntryIdentifier.uniqueID+"' value='"+catEntry.offerPrice+"'/>";innerHTML="";if(shoppingActionsJS.displayPriceRange==true){for(var i in catEntry.priceRange){if(catEntry.priceRange[i].endingNumberOfUnits==catEntry.priceRange[i].startingNumberOfUnits){tempString=storeNLS['PQ_PRICE_X'];innerHTML=innerHTML+"<p>"+dojo.string.substitute(tempString,{0:catEntry.priceRange[i].startingNumberOfUnits});}
else if(catEntry.priceRange[i].endingNumberOfUnits!='null'){tempString=storeNLS['PQ_PRICE_X_TO_Y'];innerHTML=innerHTML+"<p>"+dojo.string.substitute(tempString,{0:catEntry.priceRange[i].startingNumberOfUnits,1:catEntry.priceRange[i].endingNumberOfUnits});}
else{tempString=storeNLS['PQ_PRICE_X_OR_MORE'];innerHTML=innerHTML+"<p>"+dojo.string.substitute(tempString,{0:catEntry.priceRange[i].startingNumberOfUnits});}
innerHTML=innerHTML+" <span class='price'>"+catEntry.priceRange[i].localizedPrice+"</span></p>";}}
var quantityDiscount=dojo.byId("productLevelPriceRange_"+productId);var itemQuantityDiscount=dojo.byId("itemLevelPriceRange_"+productId);if(null!=quantityDiscount&&null==itemQuantityDiscount){dojo.style(quantityDiscount,"display","");}
else if(""!=innerHTML&&null!=itemQuantityDiscount){innerHTML=storeNLS['PQ_PURCHASE']+innerHTML;itemQuantityDiscount.innerHTML=innerHTML;dojo.style(itemQuantityDiscount,"display","");if(null!=quantityDiscount){dojo.style(quantityDiscount,"display","none");}}
else if(""==innerHTML){if(null!=itemQuantityDiscount){dojo.style(itemQuantityDiscount,"display","none");}
if(null!=quantityDiscount){dojo.style(quantityDiscount,"display","");}}
var productNameLink=dojo.query('#product_name_'+productId+' > a');if(productNameLink.length==1){productNameLink[0].innerHTML=catEntry.description[0].name;}else if(dojo.byId('product_name_'+productId)){dojo.byId('product_name_'+productId).innerHTML=catEntry.description[0].name;}
if(dojo.query("#widget_product_info_viewer > div[id^='PageHeading_']")!=null){dojo.query("#widget_product_info_viewer > div[id^='PageHeading_']").forEach(function(node){if(node.childNodes!=null&&node.childNodes.length==3){node.childNodes[1].innerHTML=catEntry.description[0].name;}});}
if(document.getElementById("ProductInfoName_"+productId)!=null){document.getElementById("ProductInfoName_"+productId).value=catEntry.description[0].name;}
if(document.getElementById('product_shortdescription_'+productId)){document.getElementById('product_shortdescription_'+productId).innerHTML=catEntry.description[0].shortDescription;}
if(document.getElementById('product_SKU_'+productId)){document.getElementById('product_SKU_'+productId).innerHTML=storeNLS['SKU']+" "+catEntry.catalogEntryIdentifier.externalIdentifier.partNumber;}}},showWCDialogPopup:function(widgetId){var popup=dijit.byId(widgetId);if(popup!=null){popup.closeButtonNode.style.display='none';popup.show();}
else{console.debug(widgetId+" does not exist");}},notifyAttributeChange:function(catalogEntryID){this.baseCatalogEntryId=catalogEntryID;var selectedAttributes=this.selectedAttributesList["entitledItem_"+catalogEntryID];dojo.topic.publish('DefiningAttributes_Resolved_'+catalogEntryID,catalogEntryID,-1);},notifyQuantityChange:function(quantity){dojo.topic.publish("Quantity_Changed",quantity);},initCompare:function(fromPage){if(fromPage=='compare'){this.checkForCompare();}else{var cookieKey=this.cookieKeyPrefix+this.storeId;var newCookieValue="";dojo.cookie(cookieKey,newCookieValue,{path:'/'});}},changeCompareBox:function(cbox,catEntryIdentifier){box=document.getElementById(cbox);box.checked=!box.checked;this.addOrRemoveFromCompare(catEntryIdentifier,box.checked);},addOrRemoveFromCompare:function(catEntryIdentifier,checked){if(checked){this.addToCompare(catEntryIdentifier);}
else{this.removeFromCompare(catEntryIdentifier);}},addToCompare:function(catEntryIdentifier){var cookieKey=this.cookieKeyPrefix+this.storeId;var cookieValue=dojo.cookie(cookieKey);if(cookieValue!=null){if(cookieValue.indexOf(catEntryIdentifier)!=-1||catEntryIdentifier==null){MessageHelper.displayErrorMessage(storeNLS["COMPARE_ITEM_EXISTS"]);return;}}
var currentNumberOfItemsInCompare=0;if(cookieValue!=null&&cookieValue!=""){currentNumberOfItemsInCompare=cookieValue.split(this.cookieDelimiter).length;}
if(currentNumberOfItemsInCompare<parseInt(this.maxNumberProductsAllowedToCompare)){var newCookieValue="";if(cookieValue==null||cookieValue==""){newCookieValue=catEntryIdentifier;}
else{newCookieValue=cookieValue+this.cookieDelimiter+catEntryIdentifier;}
dojo.cookie(cookieKey,newCookieValue,{path:'/'});shoppingActionsJS.checkForCompare();}else{this.showWCDialogPopup('widget_product_comparison_popup');document.getElementById("comparebox_"+catEntryIdentifier).checked=false;console.debug("You can only compare up to 4 products");}},removeFromCompare:function(catEntryIdentifier){var cookieKey=this.cookieKeyPrefix+this.storeId;var cookieValue=dojo.cookie(cookieKey);var currentNumberOfItemsInCompare=0;if(cookieValue!=null){if(dojo.trim(cookieValue)==""){dojo.cookie(cookieKey,null,{expires:-1});}else{var cookieArray=cookieValue.split(this.cookieDelimiter);var newCookieValue="";for(index in cookieArray){if(cookieArray[index]!=catEntryIdentifier){if(newCookieValue==""){newCookieValue=cookieArray[index];}else{newCookieValue=newCookieValue+this.cookieDelimiter+cookieArray[index];}}}
dojo.cookie(cookieKey,newCookieValue,{path:'/'});currentNumberOfItemsInCompare=newCookieValue.split(this.cookieDelimiter).length;}
shoppingActionsJS.checkForCompare();}},compareProducts:function(categoryIds){var url=appendWcCommonRequestParameters("CompareProductsDisplayView?storeId="+this.storeId+"&catalogId="+this.catalogId+"&langId="+this.langId+"&compareReturnName="+this.compareReturnName+"&searchTerm="+this.searchTerm);if(''!=categoryIds.top_category){url=url+"&top_category="+categoryIds.top_category;}
if(''!=categoryIds.parent_category_rn){url=url+"&parent_category_rn="+categoryIds.parent_category_rn;}
if(''!=categoryIds.categoryId){url=url+"&categoryId="+categoryIds.categoryId;}
var cookieKey=this.cookieKeyPrefix+this.storeId;var cookieValue=dojo.cookie(cookieKey);if(cookieValue!=null&&dojo.trim(cookieValue)!=""){url=url+"&catentryId="+cookieValue;}
var returnUrl=appendWcCommonRequestParameters(location.href);if(returnUrl.indexOf("?")==-1){returnUrl=returnUrl+"?fromPage=compare";}else if(returnUrl.indexOf("fromPage=compare")==-1){returnUrl=returnUrl+"&fromPage=compare";}
url=url+"&returnUrl="+encodeURIComponent(returnUrl);location.href=getAbsoluteURL()+url;},setProductQuantity:function(catalogEntryType,catalogEntryId,quantity,price){var productDetails=null;if(this.productList[catalogEntryId]){productDetails=this.productList[catalogEntryId];}else{productDetails=new Object();this.productList[catalogEntryId]=productDetails;productDetails.baseItemId=catalogEntryId;if("item"==catalogEntryType){productDetails.id=catalogEntryId;}else{productDetails.id=0;}}
productDetails.quantity=quantity;dojo.topic.publish("Quantity_Changed",dojo.toJson(productDetails));productDetails.price=dojo.number.parse(price);},quantityChanged:function(catalogEntryId,quantity){if(this.productList[catalogEntryId]){var productDetails=this.productList[catalogEntryId];productDetails.quantity=dojo.trim(quantity);dojo.topic.publish("Quantity_Changed",dojo.toJson(productDetails));if(MerchandisingAssociationJS!=null){if(MerchandisingAssociationJS.baseItemParams!=null){if(MerchandisingAssociationJS.baseItemParams.type=='BundleBean'){for(idx=0;idx<MerchandisingAssociationJS.baseItemParams.components.length;idx++){if(catalogEntryId==MerchandisingAssociationJS.baseItemParams.components[idx].productId||catalogEntryId==MerchandisingAssociationJS.baseItemParams.components[idx].id){MerchandisingAssociationJS.baseItemParams.components[idx].quantity=productDetails.quantity;}}}}}}},setPriceInProductList:function(catalogEntryId,price){var productDetails=this.productList[catalogEntryId];if(productDetails){productDetails.price=price;}},selectBundleItemSwatch:function(catalogEntryId,swatchName,swatchValue,doNotDisable){if(dojo.hasClass("swatch_"+catalogEntryId+"_"+swatchName+"_"+swatchValue,"color_swatch_disabled")){return;}
if(dojo.byId("entitledItem_"+catalogEntryId)!=null){var entitledItemJSON;var currentSwatchkey=swatchName+"_"+swatchValue;entitledItemJSON=dojo.fromJson(dojo.byId("entitledItem_"+catalogEntryId).innerHTML);var validSwatchArr=new Array();for(idx in entitledItemJSON){var validItem=false;var entitledItem=entitledItemJSON[idx];for(attribute in entitledItem.Attributes){if(currentSwatchkey==attribute){validItem=true;break;}}
if(validItem){for(attribute in entitledItem.Attributes){var currentSwatch=attribute.substring(0,attribute.lastIndexOf("_"));if(currentSwatch!=doNotDisable&&currentSwatch!=swatchName){validSwatchArr.push(attribute);}}}}
var swatchesDisabled=new Array();var selectedSwatches=new Array();for(idx in entitledItemJSON){var entitledItem=entitledItemJSON[idx];for(attribute in entitledItem.Attributes){var currentSwatch=attribute.substring(0,attribute.lastIndexOf("_"));if(currentSwatch!=doNotDisable&&currentSwatch!=swatchName){var swatchId="swatch_"+catalogEntryId+"_"+attribute;var swatchLinkId=swatchId.replace("swatch_","swatch_link_");if(dojo.indexOf(validSwatchArr,attribute)>-1){if(!dojo.hasClass(swatchId,"color_swatch_selected")){dojo.byId(swatchId).className="color_swatch";dojo.byId(swatchId).src=dojo.byId(swatchId).src.replace("_disabled.png","_enabled.png");dojo.byId(swatchLinkId).title=dojo.byId(swatchId).alt;document.getElementById(swatchLinkId).setAttribute("aria-disabled","false");}}else if(dojo.indexOf(swatchesDisabled,attribute)==-1){swatchesDisabled.push(attribute);if(dojo.hasClass(swatchId,"color_swatch_selected")){selectedSwatches.push(swatchId);}
dojo.byId(swatchId).className="color_swatch_disabled";dojo.byId(swatchId).src=dojo.byId(swatchId).src.replace("_enabled.png","_disabled.png");var titleText=storeNLS["INV_ATTR_UNAVAILABLE"];var altText=dojo.byId(swatchId).alt;dojo.byId(swatchLinkId).title=dojo.string.substitute(titleText,{0:altText});document.getElementById(swatchLinkId).setAttribute("aria-disabled","true");}}
if(document.getElementById("swatch_link_"+catalogEntryId+"_"+attribute)!=null){document.getElementById("swatch_link_"+catalogEntryId+"_"+attribute).setAttribute("aria-checked","false");}}}
for(idx in selectedSwatches){var selectedSwatch=selectedSwatches[idx];var idSelector=selectedSwatch.substring(0,selectedSwatch.lastIndexOf("_"));var swatchSelected=false;dojo.query("[id^='"+idSelector+"']").forEach(function(node,index,arr){if(!swatchSelected&&dojo.hasClass(node,"color_swatch")){var values=node.id.split("_");shoppingActionsJS.selectBundleItemSwatch(values[1],values[2],values[3],doNotDisable);shoppingActionsJS.setSelectedAttributeOfProduct(values[1],values[2],values[3],false);swatchSelected=true;}});}}
if(dojo.byId("swatch_selection_"+catalogEntryId+"_"+swatchName).style.display=="none"){dojo.byId("swatch_selection_"+catalogEntryId+"_"+swatchName).style.display="inline";}
dojo.byId("swatch_selection_"+catalogEntryId+"_"+swatchName).innerHTML=swatchValue;var swatchItem="swatch_"+catalogEntryId+"_"+swatchName+"_";var swatchItemLink="swatch_link_"+catalogEntryId+"_"+swatchName+"_";dojo.query("img[id^='"+swatchItem+"']").forEach(function(node,index,arr){if(dojo.hasClass(node,"color_swatch_disabled")){dojo.removeClass(node,"color_swatch")}else{dojo.addClass(node,"color_swatch");}
dojo.removeClass(node,"color_swatch_selected");});dojo.byId(swatchItem+swatchValue).className="color_swatch_selected";document.getElementById(swatchItemLink+swatchValue).setAttribute("aria-checked","true");this.setSelectedAttributeOfProduct(catalogEntryId,swatchName,swatchValue,false);this.changeBundleItemImage(catalogEntryId,swatchName,swatchValue,"productThumbNailImage_"+catalogEntryId);},changeBundleItemImage:function(catalogEntryId,swatchAttrName,swatchAttrValue,skuImageId){var entitledItemId="entitledItem_"+catalogEntryId;if(dojo.byId(entitledItemId)!=null){entitledItemJSON=eval('('+dojo.byId(entitledItemId).innerHTML+')');}
this.setEntitledItems(entitledItemJSON);var skuImage=null;var imageArr=shoppingActionsJS.getImageForBundleItem(catalogEntryId);if(imageArr!=null){skuImage=imageArr[1];}
if(skuImageId!=undefined){this.setSKUImageId(skuImageId);}
if(skuImage!=null){if(dojo.byId(this.skuImageId)!=null){document.getElementById(this.skuImageId).src=skuImage;if(document.getElementById("ProductInfoImage_"+catalogEntryId)!=null){document.getElementById("ProductInfoImage_"+catalogEntryId).value=skuImage;}}}else{var imageFound=false;for(x in this.entitledItems){var Attributes=this.entitledItems[x].Attributes;var itemImage=this.entitledItems[x].ItemThumbnailImage;for(y in Attributes){var index=y.indexOf("_");var entitledSwatchName=y.substring(0,index);var entitledSwatchValue=y.substring(index+1);if(entitledSwatchName==swatchAttrName&&entitledSwatchValue==swatchAttrValue){document.getElementById(this.skuImageId).src=itemImage;if(document.getElementById("ProductInfoImage_"+catalogEntryId)!=null){document.getElementById("ProductInfoImage_"+catalogEntryId).value=itemImage;}
imageFound=true;break;}}
if(imageFound){break;}}}},getImageForBundleItem:function(entitledItemId){var attributeArray=[];var selectedAttributes=this.selectedProducts[entitledItemId];for(attribute in selectedAttributes){attributeArray.push(attribute+"_"+selectedAttributes[attribute]);}
return this.resolveImageForSKU(attributeArray);},checkForCompare:function(){require(["dojo/_base/array","dojo/cookie","dojo/on","dojo/query"],function(array,cookie,on,query){var cookieValues=cookie(shoppingActionsJS.cookieKeyPrefix+shoppingActionsJS.storeId);cookieValues=(cookieValues?cookieValues.split(shoppingActionsJS.cookieDelimiter):[]);var labels=query(".compareCheckboxLabels > label");query(".compare_target").forEach(function(div){var checkbox=query("input[type=\"checkbox\"]",div)[0];checkbox.checked=(array.indexOf(cookieValues,checkbox.value)!=-1);var state=(checkbox.checked?(cookieValues.length>1?2:1):0);div.setAttribute("data-state",state.toString());var label=query("label[for=\""+checkbox.id+"\"]",div)[0];label.innerHTML=labels[state].innerHTML;});});},replaceItemAjaxHelper:function(catalogEntryId,qty,removeOrderItemId,addressId,shipModeId,physicalStoreId){var params=[];params.storeId=WCParamJS.storeId;params.catalogId=WCParamJS.catalogId;params.langId=WCParamJS.langId;params.orderItemId=removeOrderItemId;params.orderId=".";if(CheckoutHelperJS.shoppingCartPage){params.calculationUsage="-1,-2,-5,-6,-7";}else{params.calculationUsage="-1,-2,-3,-4,-5,-6,-7";}
var params2=[];params2.storeId=WCParamJS.storeId;params2.catalogId=WCParamJS.catalogId;params2.langId=WCParamJS.langId;params2.catEntryId=catalogEntryId;params2.quantity=qty;params2.orderId=".";params2.calculateOrder="1";if(CheckoutHelperJS.shoppingCartPage){params2.calculationUsage="-1,-2,-5,-6,-7";}else{params2.calculationUsage="-1,-2,-3,-4,-5,-6,-7";}
var params3=[];params3.storeId=WCParamJS.storeId;params3.catalogId=WCParamJS.catalogId;params3.langId=WCParamJS.langId;params3.orderId=".";if(CheckoutHelperJS.shoppingCartPage){params3.calculationUsage="-1,-2,-5,-6,-7";}else{params3.calculationUsage="-1,-2,-3,-4,-5,-6,-7";}
var shipInfoUpdateNeeded=false;var orderItemReqd=true;if(addressId!=null&&addressId!=""){params3.addressId=addressId;}
if(shipModeId!=null&&shipModeId!=""){params3.shipModeId=shipModeId;}
if(physicalStoreId!=null&&physicalStoreId!=""){params3.physicalStoreId=physicalStoreId;orderItemReqd=false;}
if(params3.shipModeId!=null&&(params3.addressId!=null||params3.physicalStoreId!=null)){shipInfoUpdateNeeded=true;}
if(orderItemReqd){params3.allocate="***";params3.backorder="***";params3.remerge="***";params3.check="*n";}
wc.service.declare({id:"AjaxReplaceItem",actionId:"AjaxReplaceItem",url:"AjaxRESTOrderItemDelete",formId:"",successHandler:function(serviceResponse){if(!shipInfoUpdateNeeded){wc.service.invoke("AjaxAddOrderItem",params2);}
else{wc.service.invoke("AjaxAddOrderItemTemp",params2);}},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}});wc.service.declare({id:"AjaxAddOrderItemTemp",actionId:"AjaxAddOrderItemTemp",url:"AjaxRESTOrderItemAdd",formId:"",successHandler:function(serviceResponse){params3.orderItemId=(serviceResponse.orderItem!=null&&serviceResponse.orderItem[0].orderItemId!=null)?serviceResponse.orderItem[0].orderItemId:serviceResponse.orderItemId;MessageHelper.displayStatusMessage(MessageHelper.messages["SHOPCART_ADDED"]);wc.service.invoke("OrderItemAddressShipMethodUpdate",params3);try{var cart=$('.t_addToCartBtn').data('info');if(cart!=null){var numberOfItems=parseInt(cart.cart_total_items)+serviceResponse.orderItem.length;cart.cart_total_items=""+numberOfItems;if(typeof utag!='undefined'&&utag!=null){utag.link(cart);}}}catch(err){console.log(err);}},failureHandler:function(serviceResponse){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}});if(!submitRequest()){return;}
cursor_wait();wc.service.invoke("AjaxReplaceItem",params);},customizeDynamicKit:function(catEntryIdentifier,quantity,customParams)
{var params=[];params.storeId=this.storeId;params.catalogId=this.catalogId;params.langId=this.langId;params.catEntryId=catEntryIdentifier;params.quantity=quantity;if(!isPositiveInteger(quantity)){MessageHelper.displayErrorMessage(storeNLS['QUANTITY_INPUT_ERROR']);return;}
var contractIdElements=document.getElementsByName('contractSelectForm_contractId');if(contractIdElements!=null&&contractIdElements!="undefined"){for(i=0;i<contractIdElements.length;i++){if(contractIdElements[i].checked){params.contractId=contractIdElements[i].value;break;}}}
if(customParams!=null&&customParams!='undefined'){for(i in customParams){params[i]=customParams[i];}}
if(!submitRequest()){return;}
cursor_wait();var configureURL="ConfigureView";var i=0;for(param in params){configureURL+=((i++==0)?"?":"&")+param+"="+params[param];}
document.location.href=getAbsoluteURL()+appendWcCommonRequestParameters(configureURL);},addInventoryAvailNotify:function(partnumber,catalogId){var email=document.getElementById('notifyMeEmailId').value;var subscribeEmailId=document.getElementById('isSubscribeEmailId').value;var sourceName=document.getElementById('sourceName').value;var params=[];params.email=email;params.partnumber=partnumber;params.catalogId=catalogId;params.subscribeEmailId=subscribeEmailId;params.storeId=shoppingActionsJS.storeId;params.sourceName=sourceName;if(validateEmailString(email)){wc.service.invoke("AjaxInvAvailNotify",params);return true;}
else{alert('Please enter a valid e-mail address');return false;}},switchSubscription:function(){var isSubscribeEmail=document.getElementById("isSubscribeEmailId").value==="true";if(isSubscribeEmail){document.getElementById('isSubscribeEmailId').value="false";}else{document.getElementById('isSubscribeEmailId').value="true";}},payWithPayPal:function(service){var params=[];params.storeId=shoppingActionsJS.storeId;params.catalogId=shoppingActionsJS.catalogId;params.langId=shoppingActionsJS.langId;cursor_wait();var paypalToken=getCookie("paypalToken2");if(paypalToken==undefined||paypalToken==''){wc.service.invoke(service,params);}
else{console.log('AjaxGetPayPalToken cookie');cursor_clear();var sheet=(function(){var style=document.createElement("style");style.appendChild(document.createTextNode(""));document.head.appendChild(style);return style.sheet;})();sheet.insertRule(".my-order .continue_checkout .checkoutWith .paypal { display: table !important }",0);if(service=="AjaxGetPayPalToken"){shoppingActionsJS.setupPayPalFromAdd(paypalToken);}
else if(service=="AjaxGetPayPalTokenFromAdd"){shoppingActionsJS.setupPayPalFromAdd(paypalToken);}
else if(service=="AjaxGetPayPalTokenFromCart"){shoppingActionsJS.setupPayPalFromCart(paypalToken);}
else if(service=="AjaxGetPayPalTokenFromShipping"){shoppingActionsJS.setupPayPalFromShipping(paypalToken);}
else if(service=="AjaxGetPayPalTokenFromBilling"){shoppingActionsJS.setupPayPalTokenFromBilling(paypalToken);}}},checkoutFromAdd:new Object(),setupPayPalFromAdd:function(token){braintree.setup(token,'custom',{onReady:function(integration){checkoutFromAdd=integration;},onPaymentMethodReceived:function(payload){console.log(payload);var details=payload.details;var billingAddress=details.billingAddress;var shippingAddress=details.shippingAddress;var params=[];params.storeId=shoppingActionsJS.storeId;params.catalogId=shoppingActionsJS.catalogId;params.langId=shoppingActionsJS.langId;if(billingAddress)
{params.billingCountry=billingAddress.countryCodeAlpha2;params.billingAddress2=billingAddress.extendedAddress;params.billingCity=billingAddress.locality;params.billingZipCode=billingAddress.postalCode;params.billingAddress1=billingAddress.streetAddress;params.billingState=billingAddress.region;}
if(shippingAddress)
{params.shippingCountry=shippingAddress.countryCodeAlpha2;params.shippingAddress2=shippingAddress.extendedAddress;params.shippingCity=shippingAddress.locality;params.shippingZipCode=shippingAddress.postalCode;params.shippingState=shippingAddress.region;params.shippingAddress1=shippingAddress.streetAddress;params.shippingRecipient=shippingAddress.recipientName;}
params.countryCode=details.countryCode;params.email1=details.email;params.firstName=details.firstName;params.lastName=details.lastName;params.payerId=details.payerId;params.phone1=details.phone;params.nonce=payload.nonce;params.paymentType=payload.type;params.orderId=shoppingActionsJS.orderId;params.URL=shoppingActionsJS.paypalRedirectViewURL;params.isBillingAddrOnly=false;params.operation='checkoutFromAdd';shoppingActionsJS.invokePayPalCallBack(params);},paypal:{singleUse:false,enableShippingAddress:true,enableBillingAddress:true,headless:true}})},checkoutFromCart:new Object(),setupPayPalFromCart:function(token){braintree.setup(token,'custom',{onReady:function(integration){checkoutFromCart=integration;},onPaymentMethodReceived:function(payload){console.log(payload);var details=payload.details;var billingAddress=details.billingAddress;var shippingAddress=details.shippingAddress;var params=[];params.storeId=shoppingActionsJS.storeId;params.catalogId=shoppingActionsJS.catalogId;params.langId=shoppingActionsJS.langId;if(billingAddress)
{params.billingCountry=billingAddress.countryCodeAlpha2;params.billingAddress2=billingAddress.extendedAddress;params.billingCity=billingAddress.locality;params.billingZipCode=billingAddress.postalCode;params.billingAddress1=billingAddress.streetAddress;params.billingState=billingAddress.region;}
if(shippingAddress)
{params.shippingCountry=shippingAddress.countryCodeAlpha2;params.shippingAddress2=shippingAddress.extendedAddress;params.shippingCity=shippingAddress.locality;params.shippingZipCode=shippingAddress.postalCode;params.shippingState=shippingAddress.region;params.shippingAddress1=shippingAddress.streetAddress;params.shippingRecipient=shippingAddress.recipientName;}
params.countryCode=details.countryCode;params.email1=details.email;params.firstName=details.firstName;params.lastName=details.lastName;params.payerId=details.payerId;params.phone1=details.phone;params.nonce=payload.nonce;params.paymentType=payload.type;params.orderId=shoppingActionsJS.orderId;params.URL=shoppingActionsJS.paypalRedirectViewURL;params.isBillingAddrOnly=false;params.operation='checkoutFromCart';shoppingActionsJS.invokePayPalCallBack(params);},paypal:{singleUse:false,enableShippingAddress:true,enableBillingAddress:true,headless:true}})},checkoutFromShipping:new Object(),setupPayPalFromShipping:function(token){braintree.setup(token,'custom',{onReady:function(integration){checkoutFromShipping=integration;},onPaymentMethodReceived:function(payload){console.log(payload);var details=payload.details;var billingAddress=details.billingAddress;var shippingAddress=details.shippingAddress;var params=[];params.storeId=shoppingActionsJS.storeId;params.catalogId=shoppingActionsJS.catalogId;params.langId=shoppingActionsJS.langId;if(billingAddress)
{params.billingCountry=billingAddress.countryCodeAlpha2;params.billingAddress2=billingAddress.extendedAddress;params.billingCity=billingAddress.locality;params.billingZipCode=billingAddress.postalCode;params.billingAddress1=billingAddress.streetAddress;params.billingState=billingAddress.region;}
if(shippingAddress)
{params.shippingCountry=shippingAddress.countryCodeAlpha2;params.shippingAddress2=shippingAddress.extendedAddress;params.shippingCity=shippingAddress.locality;params.shippingZipCode=shippingAddress.postalCode;params.shippingState=shippingAddress.region;params.shippingAddress1=shippingAddress.streetAddress;params.shippingRecipient=shippingAddress.recipientName;}
params.countryCode=details.countryCode;params.email1=details.email;params.firstName=details.firstName;params.lastName=details.lastName;params.payerId=details.payerId;params.phone1=details.phone;params.nonce=payload.nonce;params.paymentType=payload.type;params.orderId=shoppingActionsJS.orderId;params.URL=shoppingActionsJS.paypalRedirectViewURL;params.isBillingAddrOnly=false;params.operation='checkoutFromShipping';shoppingActionsJS.invokePayPalCallBack(params);},paypal:{singleUse:false,enableShippingAddress:true,enableBillingAddress:true,headless:true}})},setupPayPalTokenFromBilling:function(token){shoppingActionsJS.editPayPalFromBilling(token);shoppingActionsJS.setupPayPalFromBilling(token);},checkoutEditFromBilling:new Object(),editPayPalFromBilling:function(token){braintree.setup(token,'custom',{onReady:function(integration){checkoutEditFromBilling=integration;},onPaymentMethodReceived:function(payload){console.log(payload);var details=payload.details;var billingAddress=details.billingAddress;var params=[];params.storeId=shoppingActionsJS.storeId;params.catalogId=shoppingActionsJS.catalogId;params.langId=shoppingActionsJS.langId;if(billingAddress)
{params.billingCountry=billingAddress.countryCodeAlpha2;params.billingAddress2=billingAddress.extendedAddress;params.billingCity=billingAddress.locality;params.billingZipCode=billingAddress.postalCode;params.billingAddress1=billingAddress.streetAddress;params.billingState=billingAddress.region;}
params.countryCode=details.countryCode;params.email1=details.email;params.firstName=details.firstName;params.lastName=details.lastName;params.payerId=details.payerId;params.phone1=details.phone;params.nonce=payload.nonce;params.paymentType=payload.type;params.orderId=shoppingActionsJS.orderId;params.URL=shoppingActionsJS.paypalRedirectViewURL;params.isBillingAddrOnly=true;params.shipping_address_id=shoppingActionsJS.shippingAddressId;params.operation='checkoutEditFromBilling';shoppingActionsJS.invokePayPalCallBack(params);},paypal:{singleUse:false,enableShippingAddress:false,enableBillingAddress:true,headless:true}})},checkoutFromBilling:new Object(),setupPayPalFromBilling:function(token){braintree.setup(token,'custom',{onReady:function(integration){checkoutFromBilling=integration;},onPaymentMethodReceived:function(payload){console.log(payload);var details=payload.details;var billingAddress=details.billingAddress;var params=[];params.storeId=shoppingActionsJS.storeId;params.catalogId=shoppingActionsJS.catalogId;params.langId=shoppingActionsJS.langId;if(billingAddress)
{params.billingCountry=billingAddress.countryCodeAlpha2;params.billingAddress2=billingAddress.extendedAddress;params.billingCity=billingAddress.locality;params.billingZipCode=billingAddress.postalCode;params.billingAddress1=billingAddress.streetAddress;params.billingState=billingAddress.region;}
params.countryCode=details.countryCode;params.email1=details.email;params.firstName=details.firstName;params.lastName=details.lastName;params.payerId=details.payerId;params.phone1=details.phone;params.nonce=payload.nonce;params.paymentType=payload.type;params.orderId=shoppingActionsJS.orderId;params.URL=shoppingActionsJS.paypalRedirectViewURL;params.isBillingAddrOnly=true;params.shipping_address_id=shoppingActionsJS.shippingAddressId;params.operation='checkoutFromBilling';shoppingActionsJS.invokePayPalCallBack(params);},paypal:{enableShippingAddress:true,shippingAddressOverride:{recipientName:this.recipientName,streetAddress:this.streetAddress,extendedAddress:this.extendedAddress,locality:this.locality,countryCodeAlpha2:this.countryCodeAlpha2,postalCode:this.postalCode,region:this.region,phone:this.phone,editable:false},enableBillingAddress:true,headless:true}})},initPayPalFlowFromAdd:function(){checkoutFromAdd.paypal.initAuthFlow();},initPayPalFlowFromCart:function(){checkoutFromCart.paypal.initAuthFlow();},initPayPalFlowFromShipping:function(){checkoutFromShipping.paypal.initAuthFlow();},initPayPalFlowFromBilling:function(){checkoutFromBilling.paypal.initAuthFlow();},initPayPalEditFromBilling:function(){checkoutEditFromBilling.paypal.initAuthFlow();},invokePayPalCallBack:function(params){if(!submitRequest()){return;}
cursor_wait();wc.service.invoke('AjaxPayPalCallBack',params);},}
dojo.addOnLoad(function(){dojo.topic.subscribe("ProductInfo_Reset",shoppingActionsJS.resetProductAddedList);require(["dojo/on","dojo/has","dojo/_base/sniff","dojo/domReady!"],function(on,has){if(has("ie")<9){on(document,".compare_target > input[type=\"checkbox\"]:click",function(event){this.blur();this.focus();});}});});function validateEmailString(email){var re=/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;return re.test(email);}
shoppingActionsServicesDeclarationJS={langId:"-1",storeId:"",catalogId:"",cart_product_id:[],cart_product_name:[],cart_product_price:[],cart_product_quantity:[],persistent_cart_item:[" "],setCommonParameters:function(langId,storeId,catalogId){this.langId=langId;this.storeId=storeId;this.catalogId=catalogId;}}
dojo.addOnLoad(function(){wc.service.declare({id:"AddOrderItem",actionId:"AddOrderItem",url:getAbsoluteURL()+"AjaxRESTOrderItemAdd",formId:"",successHandler:function(serviceResponse){dojo.require("dijit.registry");MessageHelper.hideAndClearMessage();cursor_clear();if(shoppingActionsJS){var attributes_container=dojo.query('div[id^="attrValue_"]');if((dojo.query(".definingAttributes")[0])!=null){var attributes_container=dojo.query(".definingAttributes");}
else if((dojo.query(".product_sizes")[0])!=null){var attributes_container=dojo.query(".product_sizes");}
else if((dojo.query(".product_info")[0])!=null){var attributes_container=dojo.query(".product_info");}
var attributes=new Array();for(var i=0;i<attributes_container.length;i++){var attribute_selectors=attributes_container[i].querySelectorAll(".dijitSelect");for(var j=0;j<attribute_selectors.length;j++){attributes=attributes.concat(attribute_selectors[j]);}}
var dijitSelect=new Array();for(var i=0;i<attributes.length;i++){dijitSelect[i]=dijit.registry.byNode(attributes[i]);}
var singleSKU=true;for(var i=0;i<dijitSelect.length;i++){if(dijitSelect[i].options.length>2)
{singleSKU=false;}}
if(!singleSKU)
{shoppingActionsJS.selectedAttributes=new Object();dojo.topic.publish('DefiningAttributes_Resolved_'+shoppingActionsJS.baseCatalogEntryId,shoppingActionsJS.baseCatalogEntryId,-1);for(var i=0;i<dijitSelect.length;i++){if(dijitSelect[i]!=null){dijitSelect[i].value="";}}}
if(shoppingActionsJS.orderId=='')
{shoppingActionsJS.orderId=serviceResponse.orderId;}}
if(!(typeof isBundleAddtoCart==='undefined')&&isBundleAddtoCart=='true'){var message=null;try{var catentryId=serviceResponse.catEntryId_1;message=document.getElementById("bundleProduct_name_"+catentryId);if((message=='undefined')||message==null){message=document.getElementById("bundleProduct_name_"+productDisplayJS.productId);}}
catch(e){}
if(!(typeof message==='undefined')&&message!=null)
message=message.value+" added to Bag";else
message=storeNLS["MSC_ADDED_TO_BAG"];var id="add2CartBtn_"+catentryId;idElement=document.getElementById(id);if(idElement=='undefined'||idElement==null){id="add2CartBtn_"+productDisplayJS.productId;}
MessageHelper.resetErrors();MessageHelper.formErrorHandleClient(id,message,true);}
var addOn=document.getElementById('addOnMerchAssoc_'+serviceResponse.catEntryId_1[i]);if(addOn!=null&&addOn!='undefined'&&addOn.value=='true'){var addOnPopup=dijit.byId('addOnServicesPopup');if(addOnPopup!=null&&addOnPopup!=undefined&&addOnPopup!=''){addOnPopup.show();dojo.addClass(dojo.byId("grayOut"),"show");}
var contextValues=[];var orderItemIds=[];contextValues.productId=serviceResponse.catEntryId_1;for(var i=0;i<serviceResponse.orderItem.length;i++){orderItemIds[i]=serviceResponse.orderItem[i].orderItemId;}
if(orderItemIds.length>0){contextValues.parentOrderItemId=orderItemIds.sort()[0];console.info("parentOrderItemId:"+contextValues.parentOrderItemId);}
wc.render.updateContext('AddOnServicesContext',contextValues);}
console.info("serviceResponse",serviceResponse.orderItem);if(typeof(ShipmodeSelectionExtJS)!=null&&typeof(ShipmodeSelectionExtJS)!='undefined'){ShipmodeSelectionExtJS.setOrderItemId(serviceResponse.orderItem[0].orderItemId);}
dojo.publish('ProductAddedToCart');try{var cart=null;var quickview=false;if(typeof serviceResponse.isFromQV!='undefined'&&serviceResponse.isFromQV[0]!=null&&serviceResponse.isFromQV[0]=='true'){cart=$('.t_qv_addToCartBtn').data('info');quickview=true;}
else{cart=$('.t_addToCartBtn').data('info');console.log(cart);}
if(cart!=null){if(quickview){var t_product_categoryoneElement=document.getElementById("t_product_categoryone");if(t_product_categoryoneElement!=undefined&&t_product_categoryoneElement!=null&&t_product_categoryoneElement!=""){cart.product_categoryone.push(t_product_categoryoneElement.value);}}
var numberOfItems=parseInt(cart.cart_total_items)+serviceResponse.orderItem.length;if(!numberOfItems>0){numberOfItems=""+1;}
cart.cart_total_items=""+numberOfItems;if(!cart.cart_total_value){cart.cart_total_value=shoppingActionsServicesDeclarationJS.cart_product_price[0];}
Array.prototype.push.apply(shoppingActionsServicesDeclarationJS.cart_product_id,cart.product_id);Array.prototype.push.apply(shoppingActionsServicesDeclarationJS.cart_product_name,cart.product_name);Array.prototype.push.apply(shoppingActionsServicesDeclarationJS.cart_product_price,cart.product_unit_price);Array.prototype.push.apply(shoppingActionsServicesDeclarationJS.cart_product_quantity,cart.product_quantity);cart.persistent_cart_item=["Yes"];Array.prototype.push.apply(shoppingActionsServicesDeclarationJS.persistent_cart_item,cart.persistent_cart_item);cart.cart_product_id=shoppingActionsServicesDeclarationJS.cart_product_id;cart.cart_product_name=shoppingActionsServicesDeclarationJS.cart_product_name;cart.cart_product_price=shoppingActionsServicesDeclarationJS.cart_product_price;cart.cart_product_quantity=shoppingActionsServicesDeclarationJS.cart_product_quantity;shoppingActionsServicesDeclarationJS.persistent_cart_item=cart.persistent_cart_item
if(typeof customerCountry!='undefined'&&customerCountry!=null){cart.customer_country=" ";}
else
cart.customer_country=customerCountry;if(typeof utag!='undefined'&&utag!=null){utag.link(cart);}}}catch(err){console.debug(err);}},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){if(serviceResponse.errorMessageKey=="_ERR_NO_ELIGIBLE_TRADING"){MessageHelper.displayErrorMessage(storeNLS["ERROR_CONTRACT_EXPIRED_GOTO_ORDER"]);}else if(serviceResponse.errorMessageKey=="_ERR_RETRIEVE_PRICE"){var tempString=storeNLS["GENERICERR_MAINTEXT"];tempString=dojo.string.substitute(tempString,{0:storeNLS["GENERICERR_CONTACT_US"]});MessageHelper.displayErrorMessage(tempString);}else if(serviceResponse.errorMessageParam=="_ERR_QUANTITY_NOT_AVAILABLE_ATP_KILLSWITCHED"){var tempString=storeNLS["TEMPORARILY_OUT_OF_STOCK"];tempString=dojo.string.substitute(tempString,{0:shoppingActionsJS.productFullName});MessageHelper.displayErrorMessage(tempString);}else if(serviceResponse.errorCode=="CMN4512I"&&serviceResponse.errorMessage.includes("locked")&&serviceResponse.errorMessage.includes("Cart or order")){MessageHelper.displayErrorMessage(storeNLS["CART_ORDER_LOCKED"]);}else{serviceResponse.errorMessage=MessageHelper.parseHtml(serviceResponse.errorMessage);MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
isBundleAddtoCart=false;cursor_clear();}}),wc.service.declare({id:"CollectionsOrderItemAdd",actionId:"CollectionsOrderItemAdd",url:getAbsoluteURL()+"CollectionsOrderItemAddCmd",formId:"",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();cursor_clear();var addOn=document.getElementById('addOnMerchAssoc_'+serviceResponse.catEntryId_1[0]);if(addOn!=null&&addOn!='undefined'&&addOn.value=='true'){var addOnPopup=dijit.byId('addOnServicesPopup');if(addOnPopup!=null&&addOnPopup!=undefined&&addOnPopup!=''){addOnPopup.show();dojo.addClass(dojo.byId("grayOut"),"show");}
var contextValues=[];contextValues.productId=serviceResponse.catEntryId_1;contextValues.parentOrderItemId=serviceResponse.orderItemId;wc.render.updateContext('AddOnServicesContext',contextValues);}
dojo.publish('ProductAddedToCart');},failureHandler:function(serviceResponse){if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}
cursor_clear();}}),wc.service.declare({id:"AddPreConfigurationToCart",actionId:"AddOrderItem",url:getAbsoluteURL()+"AjaxRESTOrderAddPreConfigurationToCart",formId:"",successHandler:function(serviceResponse){MessageHelper.hideAndClearMessage();cursor_clear();if(shoppingActionsJS){var attributes=document.getElementsByName("attrValue");var singleSKU=true;for(var i=0;i<attributes.length;i++){if(attributes[i].options.length>1)
{singleSKU=false;}}
if(!singleSKU)
{shoppingActionsJS.selectedAttributes=new Object();for(var i=0;i<attributes.length;i++){if(attributes[i]!=null){attributes[i].value="";attributes[i].onchange();}}}}
if(typeof(ShipmodeSelectionExtJS)!=null&&typeof(ShipmodeSelectionExtJS)!='undefined'){ShipmodeSelectionExtJS.setOrderItemId(serviceResponse.orderItemId[0]);}
try{var cart=$('.t_addToCartBtn').data('info');if(typeof utag!='undefined'&&utag!=null){var numberOfItems=parseInt(cart.cart_total_items)+serviceResponse.orderItem.length;cart.cart_total_items=""+numberOfItems;utag.link(cart);}}catch(err){console.debug(err);}},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){if(serviceResponse.errorMessageKey=="_ERR_NO_ELIGIBLE_TRADING"){MessageHelper.displayErrorMessage(storeNLS["ERROR_CONTRACT_EXPIRED_GOTO_ORDER"]);}else if(serviceResponse.errorMessageKey=="_ERR_RETRIEVE_PRICE"){var tempString=storeNLS["GENERICERR_MAINTEXT"];tempString=dojo.string.substitute(tempString,{0:storeNLS["GENERICERR_CONTACT_US"]});MessageHelper.displayErrorMessage(tempString);}else{MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}}),wc.service.declare({id:"AjaxGetPayPalToken",actionId:"AjaxGetPayPalToken",url:getAbsoluteURL()+"GetPayPalTokenCmd",formId:"",successHandler:function(serviceResponse){dojo.cookie("paypalToken2",serviceResponse.token,{expires:30/24/48,path:"/"});console.log('AjaxGetPayPalToken successHandler');cursor_clear();var sheet=(function(){var style=document.createElement("style");style.appendChild(document.createTextNode(""));document.head.appendChild(style);return style.sheet;})();sheet.insertRule(".my-order .continue_checkout .checkoutWith .paypal { display: table !important }",0);shoppingActionsJS.setupPayPal(serviceResponse.token);},failureHandler:function(serviceResponse){console.log('AjaxGetPayPalToken failure: '+serviceResponse.errorMessageKey);cursor_clear();},}),wc.service.declare({id:"AjaxGetPayPalTokenFromAdd",actionId:"AjaxGetPayPalTokenFromAdd",url:getAbsoluteURL()+"GetPayPalTokenCmd",formId:"",successHandler:function(serviceResponse){dojo.cookie("paypalToken2",serviceResponse.token,{expires:30/24/48,path:"/"});console.log('AjaxGetPayPalTokenFromAdd successHandler');cursor_clear();var sheet=(function(){var style=document.createElement("style");style.appendChild(document.createTextNode(""));document.head.appendChild(style);return style.sheet;})();sheet.insertRule(".my-order .continue_checkout .checkoutWith .paypal { display: table !important }",0);shoppingActionsJS.setupPayPalFromAdd(serviceResponse.token);},failureHandler:function(serviceResponse){console.log('AjaxGetPayPalTokenFromAdd failure: '+serviceResponse.errorMessageKey);cursor_clear();},}),wc.service.declare({id:"AjaxGetPayPalTokenFromCart",actionId:"AjaxGetPayPalTokenFromCart",url:getAbsoluteURL()+"GetPayPalTokenCmd",formId:"",successHandler:function(serviceResponse){dojo.cookie("paypalToken2",serviceResponse.token,{expires:30/24/48,path:"/"});console.log('AjaxGetPayPalTokenFromCart successHandler');cursor_clear();var sheet=(function(){var style=document.createElement("style");style.appendChild(document.createTextNode(""));document.head.appendChild(style);return style.sheet;})();sheet.insertRule(".my-order .continue_checkout .checkoutWith .paypal { display: table !important }",0);shoppingActionsJS.setupPayPalFromCart(serviceResponse.token);},failureHandler:function(serviceResponse){console.log('AjaxGetPayPalTokenFromCart failure: '+serviceResponse.errorMessageKey);cursor_clear();},}),wc.service.declare({id:"AjaxGetPayPalTokenFromShipping",actionId:"AjaxGetPayPalTokenFromShipping",url:getAbsoluteURL()+"GetPayPalTokenCmd",formId:"",successHandler:function(serviceResponse){dojo.cookie("paypalToken2",serviceResponse.token,{expires:30/24/48,path:"/"});console.log('AjaxGetPayPalTokenFromShipping successHandler');cursor_clear();var sheet=(function(){var style=document.createElement("style");style.appendChild(document.createTextNode(""));document.head.appendChild(style);return style.sheet;})();sheet.insertRule(".my-order .continue_checkout .checkoutWith .paypal { display: table !important }",0);shoppingActionsJS.setupPayPalFromShipping(serviceResponse.token);},failureHandler:function(serviceResponse){console.log('AjaxGetPayPalTokenFromShipping failure: '+serviceResponse.errorMessageKey);cursor_clear();},}),wc.service.declare({id:"AjaxGetPayPalTokenFromBilling",actionId:"AjaxGetPayPalTokenFromBilling",url:getAbsoluteURL()+"GetPayPalTokenCmd",formId:"",successHandler:function(serviceResponse){dojo.cookie("paypalToken2",serviceResponse.token,{expires:30/24/48,path:"/"});console.log('AjaxGetPayPalTokenFromBilling successHandler');cursor_clear();var sheet=(function(){var style=document.createElement("style");style.appendChild(document.createTextNode(""));document.head.appendChild(style);return style.sheet;})();sheet.insertRule(".my-order .continue_checkout .checkoutWith .paypal { display: table !important }",0);shoppingActionsJS.setupPayPalTokenFromBilling(serviceResponse.token);},failureHandler:function(serviceResponse){console.log('AjaxGetPayPalTokenFromBilling failure: '+serviceResponse.errorMessageKey);cursor_clear();},}),wc.service.declare({id:"AjaxPayPalCallBack",actionId:"AjaxPayPalCallBack",url:getAbsoluteURL()+"PayPalCallBackCmd",formId:"",successHandler:function(serviceResponse){console.log('AjaxPayPalCallBack successHandler');cursor_clear();document.location.href=shoppingActionsJS.paypalRedirectViewURL;},failureHandler:function(serviceResponse){console.log('AjaxPayPalCallBack failure');console.log("Exception raised = "+serviceResponse.errorMessageKey);cursor_clear();MessageHelper.displayStatusMessage(MessageHelper.messages['ERROR_PAYPAL_SERVICE_FAILED']);},}),wc.service.declare({id:"AjaxInvAvailNotify",actionId:"AjaxInvAvailNotify",url:getAbsoluteURL()+"AjaxInvAvailNotify",formId:"",successHandler:function(serviceResponse){MessageHelper.displayStatusMessage("You will be notified by email when the product is back in stock.");dijit.byId("NotifyMeDialog").hide();},failureHandler:function(serviceResponse){}}),wc.service.declare({id:"mattelAddOnServicesSave",actionId:"mattelAddOnServicesSave",url:getAbsoluteURL()+"MattelAddOnServicesCmd",formId:"",successHandler:function(serviceResponse){var isUpdate=document.getElementById('addOnSelected');var update;if(isUpdate!=null){update=isUpdate.value;}
dijit.byId('addOnServicesPopup').hide();dojo.removeClass(dojo.byId('grayOut'),'show');var orderId;console.log(serviceResponse);var params=[];if(serviceResponse!=null){params.storeId=serviceResponse.storeId[0];params.catalogId=serviceResponse.catalogId[0];params.langId=serviceResponse.langId[0];params.productId=serviceResponse.parentCatentryId[0];params.orderId=serviceResponse.parentOrderItemId[0];}
if(!(typeof serviceResponse.aosProductOrderItemIdtoBeDeleted=='undefined'&&typeof serviceResponse.aosProdCatEntryIdstoBeAddedArray=='undefined'&&typeof serviceResponse.aosItemOrderItemIdtoBeDeleted=='undefined'&&typeof serviceResponse.aosItemOrderItemIdtoBeAdded=='undefined'))
{if(MessageHelper.messages["SHOPCART_ADDED"]!=undefined){MessageHelper.displayErrorMessage(MessageHelper.messages["SHOPCART_ADDED"]);}}
if(CheckoutHelperJS.pendingOrderDetailsPage)
{CheckoutHelperJS.getOrderPaymentsInJSON('OrderReviewUpdate');}else{var renderContext=wc.render.getContextById("ShopCartPaginationDisplay_Context");if(renderContext!=undefined&&renderContext!=null){wc.render.updateContext("ShopCartPaginationDisplay_Context",params);}
var renderContext=wc.render.getContextById("currentOrder_Context");if(renderContext!=undefined&&renderContext!=null){wc.render.updateContext("currentOrder_Context",params);}
var renderContext=wc.render.getContextById("OrderItemPaginationDisplay_Context");if(renderContext!=undefined&&renderContext!=null){wc.render.updateContext('OrderItemPaginationDisplay_Context',{'operation':'OrderReviewRefresh'});}}
cursor_clear();},failureHandler:function(serviceResponse){}}),wc.service.declare({id:"AddOrderItem1",actionId:"AddOrderItem1",url:getAbsoluteURL()+"AjaxRESTOrderItemAdd",formId:"",successHandler:function(serviceResponse){var cart=$('.t_addToCartBtn').data('info');try{if(typeof utag!='undefined'&&utag!=null){var numberOfItems=parseInt(cart.cart_total_items)+serviceResponse.orderItem.length;cart.cart_total_items=""+numberOfItems;utag.link(cart);}}catch(err){console.debug(err);}},failureHandler:function(serviceResponse){console.log("HHHH");if(serviceResponse.errorMessage){if(serviceResponse.errorMessageKey=="_ERR_NO_ELIGIBLE_TRADING"){MessageHelper.displayErrorMessage(storeNLS["ERROR_CONTRACT_EXPIRED_GOTO_ORDER"]);}else if(serviceResponse.errorMessageKey=="_ERR_RETRIEVE_PRICE"){var tempString=storeNLS["GENERICERR_MAINTEXT"];tempString=dojo.string.substitute(tempString,{0:storeNLS["GENERICERR_CONTACT_US"]});MessageHelper.displayErrorMessage(tempString);}else if(serviceResponse.errorMessageParam=="_ERR_QUANTITY_NOT_AVAILABLE_ATP_KILLSWITCHED"){var tempString=storeNLS["TEMPORARILY_OUT_OF_STOCK"];tempString=dojo.string.substitute(tempString,{0:shoppingActionsJS.productFullName});MessageHelper.displayErrorMessage(tempString);}else if(serviceResponse.errorCode=="CMN4512I"&&serviceResponse.errorMessage.includes("locked")&&serviceResponse.errorMessage.includes("Cart or order")){MessageHelper.displayErrorMessage(storeNLS["CART_ORDER_LOCKED"]);}else{MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
isBundleAddtoCart=false;cursor_clear();}}),wc.service.declare({id:"AddGiftCardToCart",actionId:"AddGiftCardToCart",url:getAbsoluteURL()+"MattelGiftCardAddCmd",formId:"",successHandler:function(e){QuickInfoJS.close();var params={};params["storeId"]=e.storeId;params["catalogId"]=e.catalogId;params["langId"]=e.langId;params["updatePrices"]="1";params["orderId"]=e.orderId;params["calculationUsageId"]="-1";wc.service.invoke("AjaxOrderCalculateForGiftCard",params);},failureHandler:function(e){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}});wc.service.declare({id:"AjaxOrderCalculateForGiftCard",actionId:"AjaxOrderCalculateForGiftCard",url:"AjaxRESTOrderCalculate",formId:"",successHandler:function(serviceResponse){console.log("order calculate success");},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}});});PIProductRecommendationsJS={getPIData:function(piURL,MattelPIRelatedProductsRefreshViewURL,widgetId){dojo.require("dojo.io.script");var jsonArgs={url:piURL,callbackParamName:"callback",load:function(data){var itemsList=data[0];var skuList="";var links="";var skuID="";if(itemsList.items!=undefined){for(i=0;i<itemsList.items.length;i++){if((itemsList.items[i].sku_id===undefined)||(itemsList.items[i].sku_id==null)||(itemsList.items[i].sku_id=="undefined")){skuID=itemsList.items[i].product_code;}else{skuID=itemsList.items[i].sku_id;}
skuList=skuList+skuID;links=links+itemsList.items[i].link;links=links+";"+skuID;if(i+1!=itemsList.items.length){skuList=skuList+",";links=links+",";}}
parseWidget('mattelPIRelatedProducts_area'+widgetId);wc.render.getRefreshControllerById('mattelPIRelatedProducts_controller'+widgetId).url=MattelPIRelatedProductsRefreshViewURL;wc.render.updateContext('mattelPIRelatedProducts_context'+widgetId,{PISKUList:skuList,links:links});}else{console.debug("Empty response from PI JSON");}},error:function(error){console.debug("error - inside getPIData()");console.debug(error);}};dojo.io.script.get(jsonArgs);},getPIAdobeRestData:function(skuIds,fromPage,adobePIurl,widgetId,MattelPIRelatedProductsRefreshViewURL){console.log(skuIds,fromPage,adobePIurl,widgetId,MattelPIRelatedProductsRefreshViewURL);var emailHash=dojo.cookie("email_hash");var thirdPartyId="";if(emailHash!=null&&emailHash!=undefined&&emailHash!=''){thirdPartyId=emailHash;}
$.ajax({url:adobePIurl,type:"POST",contentType:"application/json",data:JSON.stringify({"mbox":"target-global-mbox","thirdPartyId":thirdPartyId,"requestLocation":{"pageURL":window.location.href,"impressionId":"1","host":window.location.hostname},"profileParameters":{},"mboxParameters":{"site":sfIndicator,"pageType":fromPage,"entity.id":skuIds}}),success:function(result){try{var itemsList=result.content;if(itemsList!=undefined&&itemsList!=null&&itemsList!=""){var jsonContent=JSON.parse(itemsList);if(jsonContent!=undefined&&jsonContent!=null){var itemsList=jsonContent[0];var skuList="";var links="";var skuID="";if(itemsList.items!=undefined){for(i=0;i<itemsList.items.length;i++){if((itemsList.items[i].sku_id===undefined)||(itemsList.items[i].sku_id==null)||(itemsList.items[i].sku_id=="undefined")){skuID=itemsList.items[i].product_code;}else{skuID=itemsList.items[i].sku_id;}
skuList=skuList+skuID;links=links+itemsList.items[i].link;links=links+";"+skuID;if(i+1!=itemsList.items.length){skuList=skuList+",";links=links+",";}}
parseWidget('mattelPIRelatedProducts_area'+widgetId);wc.render.getRefreshControllerById('mattelPIRelatedProducts_controller'+widgetId).url=MattelPIRelatedProductsRefreshViewURL;wc.render.updateContext('mattelPIRelatedProducts_context'+widgetId,{PISKUList:skuList,links:links});}}}}
catch(err){console.debug(err);}},error:function(ex){}});}}
var GeolocationJS={akamaiCountryCode:"",geoLocateCookieValue:"",showPosition:function(position){if(position!==undefined&&position!=null){storeLocatorJS.refreshResultsFromNearest(position.coords.latitude,position.coords.longitude);}},locationError:function(error){var errorMsgKey;switch(error.code){case error.PERMISSION_DENIED:errorMsgKey="LBS_ERROR_PERMISSION_DENIED";break;case error.POSITION_UNAVAILABLE:errorMsgKey="LBS_ERROR_NO_USER_CURRENT_LOC";break;case error.TIMEOUT:errorMsgKey="LBS_ERROR_TIMEOUT";break;default:break;}
storeLocatorJS.refreshResultsWithLocationError(errorMsgKey);},launch:function(){if(navigator.geolocation){navigator.geolocation.getCurrentPosition(GeolocationJS.showPosition,GeolocationJS.locationError,{timeout:10000,enableHighAccuracy:true});}},getAkamaiCountryCode:function(){var akamaiCountryCode="";var xAkamaiEdgescape;try{var geoCookieValue=this.getValueFromCookie("X-MAT-GEO");if(typeof geoCookieValue!=undefined&&null!=geoCookieValue&&geoCookieValue!=""){xAkamaiEdgescape=geoCookieValue;}
if(typeof xAkamaiEdgescape!="undefined"&&xAkamaiEdgescape!=null){var headerParams=xAkamaiEdgescape.split(/\s*,\s*/);for(count=0;count<headerParams.length;count++){var params=headerParams[count].split(/\s*=\s*/);this.akamaiCountryCode=params[1];if(params[0]=="country_code"){break;}}}}catch(err){var xAkamaiEdgescape="";}},getValueFromCookie:function(cookieKey){this.geoLocateCookieValue=dojo.cookie(cookieKey);return this.geoLocateCookieValue;},createCookie:function(cookieKey,newCookieValue){dojo.cookie(cookieKey,newCookieValue,{path:"/"});},geoLocationShip:function(){this.getAkamaiCountryCode();console.log("akamaicc="+this.akamaiCountryCode);if(this.akamaiCountryCode=='CA'){var cookieVal=this.getValueFromCookie("geoLocate");if(cookieVal==undefined||cookieVal==null||cookieVal==""){this.createCookie("geoLocate",this.akamaiCountryCode);}}}}
var EmailSignupJS=EmailSignupJS||{locale:null,AllowOnlyNumbersOnKeyPress:function(evt){evt=(evt)?evt:window.event;var charCode=(evt.which)?evt.which:evt.keyCode;if(charCode>31&&(charCode<48||charCode>57)){return false;}
return true;},AllowOnlyCharactersOnKeyPress:function(evt){evt=(evt)?evt:window.event;var charCode=(evt.which)?evt.which:evt.keyCode;if(!(charCode>=65&&charCode<=120)&&(charCode!=32&&charCode!=0)){return false;}
return true;},AllowOnlyAlphaNumericOnKeyPress:function(evt){evt=(evt)?evt:window.event;var charCode=(evt.which)?evt.which:evt.keyCode;if((charCode<65||charCode>122)&&(charCode<48||charCode>57)){return false;}
return true;},NameCheck:function(ctrl){if(ctrl.val().match('^[a-zA-Z]{1,50}$')){return true;}else{return false;}},FinishRegistration:function(){if(EmailSignupJS.EmptyCheckForAll()){var json=EmailSignupJS.CreateJSONData();EmailSignupJS.SaveData(json);}},CreateJSONData:function(){var childCount=parseInt($("#childCountHidden").val());var children='';for(var i=1;i<=childCount;i++){if(EmailSignupJS.ConsiderChildData(i)){if(children==0){children='{'+
EmailSignupJS.CreateNode("Gender",$("input[type='radio'][name='gender"+i+"']:checked").val())+","+
EmailSignupJS.CreateNode("BirthDate",GetDate(i))+","+
EmailSignupJS.CreateNode("RelationShip",$("input[type='radio'][name='relation"+i+"']:checked").val())+'}';}
else{children=children+","+'{'+
EmailSignupJS.CreateNode("Gender",$("input[type='radio'][name='gender"+i+"']:checked").val())+","+
EmailSignupJS.CreateNode("BirthDate",GetDate(i))+","+
EmailSignupJS.CreateNode("RelationShip",$("input[type='radio'][name='relation"+i+"']:checked").val())+'}';}}}
var json='{'+
EmailSignupJS.CreateNode("EmailAddress",$("#emailSignupEmail").val())+','+'"storeId":"'+WCParamJS.storeId+'",'+'"CatalogId":"'+WCParamJS.catalogId+'",'+'"createPartyNow":"true",'+'"addAllContPref":"true",'+'"Children":['+
children+']'+'}';return json;},CreateNode:function(nodeid,val){var text='"'+nodeid+'"'+':'+'"'+val+'"';return text;},HideAllErrorMessage:function(){$('.form-group').removeClass('has-error');},EmptyCheckForAll:function(){var isValid=true;EmailSignupJS.HideAllErrorMessage();var email=$("email").val();var childCount=parseInt($("#childCountHidden").val());for(var i=1;i<=childCount;i++){var childValid=true;var isChildDirty=EmailSignupJS.IsChildDirty(i);if(isChildDirty){if(!EmailSignupJS.DateCheck(i)){$("#DBMM"+i).closest('.form-group').removeClass("has-error").addClass("has-error");isValid=false;childValid=false;}
if(!EmailSignupJS.GenderCheck(i)){$("#genderBoy"+i).closest('.form-group').removeClass("has-error").addClass("has-error");isValid=false;childValid=false;}
if(!EmailSignupJS.RelationShipCheck(i)){$("#relationMom"+i).closest('.form-group').removeClass("has-error").addClass("has-error");isValid=false;childValid=false;}}
if(i==1&&!isChildDirty){isValid=false;$("#DBMM1").closest('.form-group').removeClass("has-error").addClass("has-error");$("#genderBoy1").closest('.form-group').removeClass("has-error").addClass("has-error");$("#relationMom1").closest('.form-group').removeClass("has-error").addClass("has-error");}}
return isValid;},IsChildDirty:function(spot){var genderDirty=false;var birthDateDirty=false;var relationDirty=false;genderDirty=typeof $("input[type='radio'][name='gender"+spot+"']:checked").val()==="undefined"?false:true;birthDateDirty=isEmpty($("#DBMM"+spot).val())&&isEmpty($("#DBDD"+spot).val())&&isEmpty($("#DBYY"+spot).val())?false:true;relationDirty=typeof $("input[type='radio'][name='relation"+spot+"']:checked").val()==="undefined"?false:true;if(genderDirty||birthDateDirty||relationDirty)
return true;else
return false;},ConsiderChildData:function(spot){var genderDirty=false;var birthDateDirty=false;var relationDirty=false;genderDirty=typeof $("input[type='radio'][name='gender"+spot+"']:checked").val()==="undefined"?false:true;birthDateDirty=isEmpty($("#DBMM"+spot).val())&&isEmpty($("#DBDD"+spot).val())&&isEmpty($("#DBYY"+spot).val())?false:true;relationDirty=typeof $("input[type='radio'][name='relation"+spot+"']:checked").val()==="undefined"?false:true;if(genderDirty&&birthDateDirty&&relationDirty)
return true;else
return false;},GetDate:function(spot){var day=$("#DBDD"+spot).val();var month=$("#DBMM"+spot).val();var year=2000+parseInt($("#DBYY"+spot).val());return(day!=''&&month!=''&&year!='')?(day+"/"+month+"/"+year):"foo";},DateCheck:function(spot){if(isNaN(Date.parse(EmailSignupJS.GetDate(spot)))){return false;}
else{var year=2000+parseInt($("#DBYY"+spot).val());var currentTime=new Date()
var currentYear=currentTime.getFullYear()
var yearUpperLimit=parseInt(currentYear)+1;var yearLowerLimit=parseInt(currentYear)-6;if(year>yearUpperLimit||year<yearLowerLimit){return false;}
return true;}},GenderCheck:function(spot){var genderDirty=typeof $("input[type='radio'][name='gender"+spot+"']:checked").val()==="undefined"?false:true;return genderDirty;},RelationShipCheck:function(spot){var relationDirty=typeof $("input[type='radio'][name='relation"+spot+"']:checked").val()==="undefined"?false:true;return relationDirty;},BackToStart:function(){if(window.fp.device!='mobile'){EmailSignupJS.LoadEmailSignUpStartUp();}
else{$('#email-pop-up').modal('hide');}},CloseModal:function(){dijit.byId("EmailSignupDialog").hide();},SaveData:function(jsonData){$.ajax({url:"SubscribeToEmail",type:"POST",data:{"json":jsonData},beforeSend:function(){if($('#loading-indicator').length){$('#loading-indicator').modal({backdrop:'static',show:true});}},complete:function(){},success:function(result){$('#loading-indicator').modal('hide');$('body').addClass('modal-open');if(result==null||result==''||result==undefined){$("#emailError").text("The Email id is already registered");$("#emailError").removeClass("hidden");$("#emailError").closest('.form-group').removeClass("has-error").addClass("has-error");}
else{var obj=JSON.parse(jsonData);var catalogId=obj.CatalogId;var storeId=obj.storeId;dijit.byId("EmailSignupDialog").hide();}},error:function(ex){}})},isEmpty:function(el){return!$.trim(el)},isValidEmailAddress:function(emailAddress){var pattern=new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);return pattern.test(emailAddress);},startSignUp:function(){var isValid=MattelAgeGate.checkAge(storeUserType,'emailSignUp');if(isValid){var errorSpanId="#emailError";var email=$("#emailSignupEmail").val();$("#addChildBirthdayInfoEmailSignUp").html(' ');$("#childCountHidden").val('0');if(EmailSignupJS.isEmpty(email)){$(errorSpanId).text("Please enter your Email Address");$(errorSpanId).show();}else if(EmailSignupJS.isValidEmailAddress(email)==false){$(errorSpanId).text("Please enter a valid Email Address");$(errorSpanId).show();}else{$(errorSpanId).hide();var emailSignupDialog=dijit.byId('EmailSignupDialog');$("html, body").animate({scrollTop:0},'slow');emailSignupDialog.show();setTimeout(function(){$("#WC_EmailSignupForm_div_21").val($("#emailSignupEmail").val());$("#sourceName").val($("#footerSourceName").val());float_labels();$("#emailSignupEmail").val('');},2000);}}},startHeaderEmailSignUp:function(){var isValid=MattelAgeGate.checkAge(storeUserType,'emailSignUpHeader');if(isValid){var email=$("#emailSignupEmail").val();$("#addChildBirthdayInfoEmailSignUp").html(' ');$("#childCountHidden").val('0');var emailSignupDialog=dijit.byId('EmailSignupDialog');$("html, body").animate({scrollTop:0},'slow');emailSignupDialog.show();setTimeout(function(){float_labels();$("#emailSignupEmail").val('');$("#sourceName").val($("#headerSourceName").val());},2000);}},startFooterEmailSignUp:function(){var isValid=MattelAgeGate.checkAge(storeUserType,'emailSignUpHeader');if(isValid){var email=$("#emailSignupEmail").val();$("#addChildBirthdayInfoEmailSignUp").html(' ');$("#childCountHidden").val('0');var emailSignupDialog=dijit.byId('EmailSignupDialog');$("html, body").animate({scrollTop:0},'slow');emailSignupDialog.show();setTimeout(function(){float_labels();$("#emailSignupEmail").val('');$("#sourceName").val($("#footerSourceName").val());},2000);}},GetStarted:function(isMobile){var email='';var isValid=true;var errorSpanId="#emailError";if(isMobile=='true'){email=$("#emailMobile").val();errorSpanId=errorSpanId+"Mobile";}
else{email=$("#emailDesktop").val();}
if(isEmpty(email)){if(isMobile=="true"){$('#email-pop-up').modal('hide');}
isValid=false;$(errorSpanId).text("Please enter your Email Address");}
else if(isValidEmailAddress(email)==false){if(isMobile=="true"){$('#email-pop-up').modal('hide');}
isValid=false;$(errorSpanId).text("Please enter a valid Email Address");}
if(isValid){$('#email-pop-up').modal('show');LoadEmailSignUpForm(email);}
else{$(errorSpanId).removeClass("hidden");$(errorSpanId).closest('.form-group').removeClass("has-error").addClass("has-error");}},addAnotherChild:function(){var childCount=parseInt($("#childCountHidden").val());childCount=childCount+1;$(addChild(childCount)).insertBefore(".add-child-option");$("#childCountHidden").val(childCount);},HideRegistration:function(){$(".mobile-tile").hide();$(".desktop-tile").hide();this.ShowHideTopBar('hide');},ShowRegistration:function(){$(".mobile-tile").show();$(".desktop-tile").show();this.ShowHideTopBar('show');},ShowHideTopBar:function(showHide){$.ajax({url:"/"+locale+"/Registration/WriteEmailCookie",type:"GET",data:{"showHide":showHide},success:function(){},error:function(ex){}})},LoadEmailSignUpStartUp:function(){var result='<div class="email-signUp-content getStarted">'+'   <div class="header-wrapper">'+'       <div class="left-tile">'+'           <img src="/wcsstore/MattelSAS/images/colors/fp/email-sign-up/left-tile1.png" />'+'       </div>'+'       <div class="header-tile">'+'           <h2>Receive $10 off & free shipping!*</h2>'+'           <p>Sign up for the newsletter that grows with your child!</p>'+'       </div>'+'       <div class="right-tile">'+'           <img src="/wcsstore/MattelSAS/images/colors/fp/email-sign-up/right-tile1-option2.png" />'+'       </div>'+'   </div>'+'   <div class="content-tile">'+'       <div class="info">'+'           <ul>'+'               <li>Special savings & offers</li>'+'               <li>Playtime tips developed especially for your child\'s age and stage</li>'+'               <li>Helpful ideas and parenting resources</li>'+'           </ul>'+'           <form class="form-horizontal" role="form">'+'               <div class="form-group">'+'                   <div class="col-sm-7">'+'                       <input type="email" class="form-control" id="emailDesktop" placeholder="Enter your email" required />'+'                       <span id="emailError" class="help-block hidden"></span>'+'                   </div>'+'                   <div class="col-sm-5">'+'                       <div class="get-start-btn">'+'                           <input type="button" class="btn btn-default" value="SIGN UP" onclick="GetStarted(\'false\');utag.link({  eve_cat:\'Sign Up\' , eve_act:\'Email\', eve_lab:\'Email Capture - Step 1\', eve_des:\'New Email Sign Up\',eve_pos:\'Header\' });" />'+'                           <a class="glyphicon glyphicon-chevron-right"></a>'+'                       </div>'+'                   </div>'+'               </div>'+'           </form>'+'       </div>'+'       <div class="details">'+'           <div id="detail-info">'+'               <p><span>* $10 savings offer is valid on all orders of $75+ from the Fisher-Price Store</span> after discounts, and before charges for gift wrap, shipping & processing and/or     taxes are applied. Free shipping offer applies to standard shipping charges to U.S. addresses only; Canadian shipping charges,  rush charges and/or large item surcharges are additional. Offer is valid online only. If order is shipped to more than one address, offer applies to first "ship-to" address only.</p>'+'               <ul>'+'               <li>After signing up for Fisher-Price emails, we\'ll send this offer\'s promotion code to your inbox within one day.</li>'+'               <li>By clicking �Sign Up� you are agreeing to receive emails and notifications from Fisher-Price.</li>'+'               </ul>'+'           </div>'+'       </div>'+'   </div>'+'</div>';$('#loading-indicator').modal({backdrop:'static',show:true});$('#loading-indicator').modal('hide');$('body').addClass('modal-open');$("#email-pop-up .modal-body").html('').load(getAbsoluteURL(true)+'EmailSignupMainView?catalogId='+WCParamJS.catalogId+'&storeId='+WCParamJS.storeId);},LoadEmailSignUpForm:function(email){var result='<div class="email-signUp-content signUp-form">'+' <div class="header-wrapper">'+'  <div class="left-tile">'+'   <img src="/wcsstore/MattelSAS/images/colors/fp/email-sign-up/left-tile.png" />'+'  </div>'+'  <div class="header-tile">'+'   <h2>Sign up and receive $10 off & free shipping!*</h2>'+'   <p>Our newsletter grows with your child</span></p>'+'  </div>'+'  <div class="details visible-xs-block">'+'   <a href="#mobile-detail-info2" class="see-details" data-toggle="collapse">Details</a>'+'   <div id="mobile-detail-info2" class="collapse">'+'    <p><span>* $10 savings offer is valid on all orders of $75+</span> after discounts, and before charges for gift wrap, shipping & processing and/or     taxes are applied. Free shipping offer applies to standard shipping charges to U.S. addresses only; Canadian shipping charges,  rush charges and/or large item surcharges are additional. Offer is valid online only. If order is shipped to more than one address, offer applies to first "ship-to" address only.</p>'+'    <ul><li>Upon signup to our Fisher-Price email database the offer will be emailed to your inbox within 1 day.</li>'+'     <li>By clicking submit you are agreeing to receive emails and notifications from Fisher-Price</li>'+'    </ul>'+'   </div>'+'  </div>'+'  <div class="right-tile">'+'   <img src="/wcsstore/MattelSAS/images/colors/fp/email-sign-up/right-tile.png" desk-img="/wcsstore/MattelSAS/images/colors/fp/email-sign-up/right-tile.png" mobile-img="/wcsstore/MattelSAS/images/colors/fp/email-sign-up/right-tileMobile.png" class="imgswap"/>'+'  </div>'+' </div>'+' <div class="content-tile">'+'  <form class="form-horizontal" role="form">'+'   <div class="form-group">'+'    <label for="email" class="col-xs-3 control-label">My Email</label>'+'    <div class="col-xs-9">'+'                    <input type="email" class="form-control disabled enteredEmail" id="email" placeholder="test@test.nete" value="'+email+'" disabled />'+'      <!--a class="glyphicon glyphicon-pencil"></a-->'+'     </div>       '+'    </div>'+'               <input type="hidden" value="1" name="childCountHidden" id="childCountHidden" />'+'    <div class="form-group">'+'     <label class="col-xs-3 control-label childs-info">Child\'s info</label>'+'     <div class="col-xs-9">'+'      <p>Enter your child�s age and gender below. This info will only be used to select playtips, parenting articles and toys just right for your child\'s age and stage of development.</p>'+'     </div>       '+'    </div>'+'    <span class="help-block note">Please fill in all fields</span>'+'    <div class="add-child-option">'+'     <a href="#" onclick="javascript:addAnotherChild();"><span class="glyphicon glyphicon-plus"></span>Add Child</a>'+'    </div>'+'    <div class="btn-group">'+'                 <div class="back-btn">'+'                     <input type="button" class="btn btn-default back" value="BACK" onclick="BackToStart();" />'+'                     <a class="glyphicon glyphicon-chevron-left"></a>'+'                 </div>'+'     <input type="button" class="btn btn-default submit" onclick="FinishRegistration();utag.link({  eve_cat:\'Sign Up\' , eve_act:\'Email\', eve_lab:\'Email Capture - Step 2\', eve_des:\'New Email Sign Up\',eve_pos:\'Header\' });" value="SUBMIT" />'+'    </div>'+'   </form>'+'   <p class="visible-xs-block">By clicking submit you are agreeing to recieve emails and notifications from Fisher-Price</p>'+'   <div class="details">'+'    <a href="#detail-info-1" class="see-details" data-toggle="collapse">*See Details</a>'+'    <div id="detail-info-1" class="collapse">'+'     <p><span>* $10 savings offer is valid on all orders of $75+</span> after discounts, and before charges for gift wrap, shipping & processing and/or     taxes are applied. Free shipping offer applies to standard shipping charges to U.S. addresses only; Canadian shipping charges,  rush charges and/or large item surcharges are additional. Offer is valid online only. If order is shipped to more than one address, offer applies to first "ship-to" address only.</p>'+'     <ul><li>Upon sign up to our Fisher Price email database the offer will be emailed to your inbox within 1 day.</li>'+'      <li>By clicking submit you are agreeing to recieve emails and notifications from Fisher-Price</li>'+'     </ul>'+'    </div>'+'   </div>'+'  </div>'+' </div>';$('#loading-indicator').modal('hide');$('body').addClass('modal-open');if(isEmpty(result)){$("#emailError").text("The Email id is already registered");$("#emailError").removeClass("hidden");$("#emailError").closest('.form-group').removeClass("has-error").addClass("has-error");}
else{$("#email-pop-up .modal-body").html('').html(result);$(addChild(1)).insertBefore(".add-child-option");}},addChild:function(count){var childDiv='<div class="child-info" id="child'+count+'">'+'     <div class="info-1">'+'                     <div class="form-group birth-date">'+'                         <label class="col-sm-5 control-label">Birth Date or Due Date:</label>'+'                         <div class="col-sm-7">'+'                             <div class="input-row">'+'                                 <input type="text" id="DBMM'+count+'" data-maxlen="2" data-min="1" data-max="12" class="form-control numbersOnly" placeholder="MM" maxlength="2"/>'+'                                 <input type="text" id="DBDD'+count+'" data-maxlen="2" data-min="1" data-max="31" class="form-control numbersOnly" placeholder="DD" maxlength="2"/> '+'                                 <input type="text" id="DBYY'+count+'" data-maxlen="2" class="form-control numbersOnly" data-min="10" data-max="17" placeholder="YY" maxlength="2"/> '+'                             </div>           '+'                         </div>       '+'                     </div>'+'                     <div class="form-group">'+'                         <label class="col-sm-12 control-label">Child\'s Gender:</label>'+'                         <div class="col-sm-12">'+'                             <label for="genderBoy'+count+'" class="radio-inline col-xs-6 col-sm-3">'+'                                 <input type="radio" name="gender'+count+'" id="genderBoy'+count+'" value="M"/> <span>Boy</span>'+'                             </label>'+'                             <label for="genderGirl'+count+'" class="radio-inline col-xs-6 col-sm-3">'+'                               <input type="radio" name="gender'+count+'" id="genderGirl'+count+'" value="F"/> <span>Girl</span>'+' </label>'+'        <label for="genderBaby'+count+'" class="radio-inline col-xs-12 col-sm-6">'+'                               <input type="radio" name="gender'+count+'" id="genderBaby'+count+'" value="O"/> <span>Expecting, don\'t know yet</span>'+'                             </label>       '+'                         </div>       '+'                     </div>'+'     </div>'+'     <div class="info-2">'+'                     <div class="form-group">'+'                         <label class="col-sm-12 control-label">I am the: </label>'+'                         <div class="col-sm-12">'+'                             <label for="relationMom'+count+'" class="radio-inline col-xs-6">'+'                                 <input type="radio" name="relation'+count+'" id="relationMom'+count+'" value="Mother"/> <span>Mom</span>'+'                             </label>'+'                             <label for="relationDad'+count+'" class="radio-inline col-xs-6">'+'                               <input type="radio" name="relation'+count+'" id="relationDad'+count+'" value="Father"/> <span>Dad</span>'+'                             </label>'+'                             <label for="relationGrandparent'+count+'" class="radio-inline col-xs-6">'+'                               <input type="radio" name="relation'+count+'" id="relationGrandparent'+count+'" value="GrandFather"/> <span>Grandparent</span>'+'                             </label>'+'                             <label for="relationOther'+count+'" class="radio-inline col-xs-6">'+'                               <input type="radio" name="relation'+count+'" id="relationOther'+count+'" value="Friend / Family Member"/> <span>Family / Friend</span>'+'                             </label>      '+'                         </div>       '+'                     </div>'+'     </div>'+'                 <div class="remove-child-option">'+'     <a href="#" onclick="javascript:removeChildInfo(\''+count+'\');"><span class="glyphicon glyphicon-minus"></span>Remove Child</a>'+'    </div>'+'    </div>';return childDiv;},removeChildInfo:function(count){$("#child"+count).remove();},addChildBirthDayForm:function(){var childCount=parseInt($("#childCountHidden").val());var continueAddChild=true;if(childCount!=0){var formName=document.forms['childForm_'+childCount];continueAddChild=EmailSignupJS.validateChildForm(formName,childCount);}
if(continueAddChild&&childCount<5){var childCount=parseInt($("#childCountHidden").val());childCount=childCount+1;var parentDiv=document.getElementById("addChildBirthdayInfoEmailSignUp");var lastChild=parentDiv.lastChild;$(this.constructChildForm(childCount)).insertAfter(lastChild);$("#childCountHidden").val(childCount);if(childCount!=1){var hidePreviousRemoveButton=document.getElementById("removeChildForm_"+(childCount-1))
if(hidePreviousRemoveButton!=null&&hidePreviousRemoveButton!=undefined){hidePreviousRemoveButton.classList.add('hide');}}
float_labels();}},constructChildForm:function(count){var childFormDiv='';if(count<=1){childFormDiv='<div id="childFormDiv_'+count+'" class="padding_top_bottom">'}else{childFormDiv='<div id="childFormDiv_'+count+'" class="padding_top_bottom border_top">'}
childFormDiv+='<form name="childForm_'+count+'" method="post" class="childBaseForm" id="childForm_'+count+'" >'+'    <div class="column childName" id="childName_wrapper">'+'       <div id="childNameDiv" class="column_label">'+'     <span class="spanacce">'+'        <label for="childName_'+count+'">'+'         Child Name:'+'        </label>'+'      </span>'+'      Child Name: '+'     </div>'+'      <input class="inputField" type="text" maxlength="40" size="35" id="childName_'+count+'" name="childName_'+count+'" value="" />'+'    </div>'+'       <div class="child_birthday ">'+'     <label for="birthday" class="hidden-lg">Birthday</label>'+'        <div class="birthday_select_wrapper">'+'        <div class="label_spacer filled">'+'      Month'+'        </div>'+'        <select  name="birth_month_'+count+'" id="birth_month_'+count+'" size="1" aria-required="true"  class="filled birthday_month_select">'+'         '+this.getMonthOptioins()+'        </select>'+'        </div>'+'     <div class="birthday_select_wrapper">'+'      <div class="label_spacer filled" >'+'      Date'+'      </div>'+'      <select  name="birth_date_'+count+'" id="birth_date_'+count+'" aria-required="true" size="1" class="filled birthday_date_select" >'+'       '+this.getDateOptions()+'      </select>'+'     </div>'+'     <div class="birthday_select_wrapper">'+'      <div class="label_spacer filled">'+'      YEAR'+'      </div>'+'      <select name="birth_year_'+count+'" id="birth_year_'+count+'" aria-required="true" size="1" class="filled birthday_duedate_select">'+'       '+this.getYearOptions()+'      </select>'+'     </div>'+'     <div class="birthday_select_wrapper">'+'     <a href="http://corporate.mattel.com/privacy-statement.aspx" target="_blank" >Privacy statement</a>'+'     </div>'+'    </div>'+'                <div class="child_gender ">'+'    <div class=" options_heading">THE CHILD IS:</div>'+'    <div class="padding_top_bottom">'+'     <label>'+'       <input type="radio" value="M" class="radio" id="childGender_'+count+'" name="childGender_'+count+'"><span>Boy</span>'+'     </label>'+'     <label>'+'       <input type="radio" value="F" class="radio" id="childGender_'+count+'" name="childGender_'+count+'"><span>Girl</span>'+'     </label>'+'     <label>'+'       <input type="radio" value="O" class="radio" id="childGender_'+count+'" name="childGender_'+count+'"><span>Expecting (unknown)</span>'+'     </label>'+'    </div>'+'    </div>'+'    <div class="relation_with_child">'+'      <div class="options_heading">I am the:</div>'+'      <div class="padding_top_bottom">'+'      <label>'+'       <input type="radio" name="childRelation_'+count+'"  value="Mother" id ="childRelation_'+count+'" class="checkbox" />'+'       <span class="text">Mother</span>'+'      </label>'+'      <label>'+'       <input type="radio" name="childRelation_'+count+'" id="childRelation_'+count+'" value="Father" class="checkbox" />'+'       <span class="text">Father</span>'+'      </label>'+'      <label>'+'       <input type="radio" name="childRelation_'+count+'" id="childRelation_'+count+'" value="GrandParent" class="checkbox" />'+'       <span class="text">Grandparent</span>'+'      </label>'+'      <label>'+'          <input type="radio" name="childRelation_'+count+'"  id="childRelation_'+count+'" value="Friend / Family Member" class="checkbox" />'+'       <span class="text">Friend / Family Member </span>'+'      </label>'+'       <div id="businessTitle_err" class="input-error"></div>'+'      </div>'+'     </div>'+'                </form>'+'    <div class="add_child_wrapper" id="removeChildForm_'+count+'">'+'      <a class="child_add_remove_link"  href="JavaScript:EmailSignupJS.removeChildForm('+count+');"><span>Remove</span></a>'+'    </div>'+'    </div>';return childFormDiv;},removeChildForm:function(count){var childCount=parseInt($("#childCountHidden").val());if(count==childCount){$("#childFormDiv_"+count).remove();$("#childCountHidden").val(count-1);if(childCount!=1){var hidePreviousRemoveButton=document.getElementById("removeChildForm_"+(childCount-1))
if(hidePreviousRemoveButton!=null&&hidePreviousRemoveButton!=undefined){hidePreviousRemoveButton.classList.remove('hide');}}}},emailSignUpRegistration:function(){if(EmailSignupJS.validateAllForm()){var json=EmailSignupJS.CreateEmailSignUpJSONData();EmailSignupJS.saveEmailSignUpData(json);}},CreateEmailSignUpJSONData:function(){var childCount=parseInt($("#childCountHidden").val());var children='';var emailForm=document.forms['EmailSignUpForm'];var emailId=emailForm.email.value;var sourceName=emailForm.sourceName.value;for(var count=1;count<=childCount;count++){var formName=document.forms['childForm_'+count];var childName="";if(EmailSignupJS.validateChildForm(formName,count)){var nameId=document.getElementById("childName_"+count);if(nameId!=null&&nameId!=undefined&&nameId!=""){childName=nameId.value;}
if(count==1){children='{'+
EmailSignupJS.CreateNode("childName",childName)+","+
EmailSignupJS.CreateNode("Gender",formName["childGender_"+count].value)+","+
EmailSignupJS.CreateNode("BirthDate",this.getDateFormat(formName,count))+","+
EmailSignupJS.CreateNode("RelationShip",formName["childRelation_"+count].value)+'}';}
else{children=children+","+'{'+
EmailSignupJS.CreateNode("childName",childName)+","+
EmailSignupJS.CreateNode("Gender",formName["childGender_"+count].value)+","+
EmailSignupJS.CreateNode("BirthDate",this.getDateFormat(formName,count))+","+
EmailSignupJS.CreateNode("RelationShip",formName["childRelation_"+count].value)+'}';}}}
var json='{'+
EmailSignupJS.CreateNode("EmailAddress",emailId)+','+'"mbrgrpname":"'+WCParamJS.mbrgrpname+'",'+'"storeId":"'+WCParamJS.storeId+'",'+'"CatalogId":"'+WCParamJS.catalogId+'",'+'"sourceName":"'+sourceName+'",'+'"createPartyNow":"true",'+'"addAllContPref":"true",'+'"Children":['+
children+']'+'}';return json;},getDateFormat:function(formName,count){var birth_year="0";var birth_month="0";var birth_date="0";var birthYearId=document.getElementById("birth_year_"+count);var birthMonthId=document.getElementById("birth_month_"+count);var birthDateId=document.getElementById("birth_date_"+count);if(birthYearId!=null&&birthYearId!=undefined&&birthYearId!=""){var birth_year=birthYearId.value;}
if(birthMonthId!=null&&birthMonthId!=undefined&&birthMonthId!=""){var birth_month=birthMonthId.value;}
if(birthDateId!=null&&birthDateId!=undefined&&birthDateId!=""){var birth_date=birthDateId.value;}
return(birth_year!=''&&birth_month!=''&&birth_date!='')?(birth_date+"/"+birth_month+"/"+birth_year):"00/00/0000";},getCurrentYear:function(){var currentTime=new Date();var year=currentTime.getFullYear();return year;},getYearOptions:function(){var currentYear=this.getCurrentYear();var startYear=currentYear-30;var options='<option value="0">YYYY</option>'
var temp=currentYear;for(i=startYear;i<=currentYear;i++){options+='<option value="'+temp+'">'+temp+'</option>';temp=temp-1;}
return options;},getDateOptions:function(){var startDate=1;var endDate=31;var options='<option value="0">DD</option>'
for(i=startDate;i<=endDate;i++){options+='<option value="'+i+'">'+i+'</option>';}
return options;},getMonthOptioins:function(){var month=["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];var options='<option value="0">MM</option>'
for(i=0;i<12;i++){options+='<option value="'+(i+1)+'">'+month[i]+'</option>';}
return options;},validateChildForm:function(formName,count){var genderDirty=false;var birthDateDirty=false;var relationDirty=false;var childName="";var gender="";var relation="";var birth_year="0";var birth_month="0";var birth_date="0";var nameId=document.getElementById("childName_"+count);var genderId=document.getElementById("childGender_"+count);var relationId=document.getElementById("childRelation_"+count);var birthYearId=document.getElementById("birth_year_"+count);var birthMonthId=document.getElementById("birth_month_"+count);var birthDateId=document.getElementById("birth_date_"+count);if(nameId!=null&&nameId!=undefined&&nameId!=""){var childName=nameId.value;}
if(birthYearId!=null&&birthYearId!=undefined&&birthYearId!=""){var birth_year=birthYearId.value;}
if(birthMonthId!=null&&birthMonthId!=undefined&&birthMonthId!=""){var birth_month=birthMonthId.value;}
if(birthDateId!=null&&birthDateId!=undefined&&birthDateId!=""){var birth_date=birthDateId.value;}
var relation=formName["childRelation_"+count].value;var gender=formName["childGender_"+count].value;if(relation!=undefined&&relation!=null&&relation!=""){relationDirty=true;}
if(gender!=undefined&&gender!=null&&gender!=""){genderDirty=true;}
if(birth_year=="0"&&birth_month=="0"&&birth_year=="0"){MessageHelper.formErrorHandleClient(birthYearId.id,MessageHelper.messages["MY_ACC_CHILD_INVALID_DOB"]);MessageHelper.formErrorHandleClient(birthMonthId.id,MessageHelper.messages["MY_ACC_CHILD_INVALID_DOB"]);MessageHelper.formErrorHandleClient(birthDateId.id,MessageHelper.messages["MY_ACC_CHILD_INVALID_DOB"]);birthDateDirty=false;}
if(birth_year!="0"&&birth_month!="0"&&birth_date!="0"){birthDateDirty=true;var febDays=29;if(birth_year!="0"&&((birth_year%4)!="0")){febDays=28;}
var months=["4","6","9","11"];var monthFound=false;for(var i=0;i<months.length;i++){if(months[i]==birth_month){monthFound=true;break;}}
if(monthFound&&(birth_date>30)){MessageHelper.formErrorHandleClient(birthDateId.id,MessageHelper.messages["MY_ACC_CHILD_INVALID_DOB"]);birthDateDirty=false;}
if((birth_month=="2")&&(birth_date>febDays)){MessageHelper.formErrorHandleClient(birthDateId.id,MessageHelper.messages["MY_ACC_CHILD_INVALID_DOB"]);birthDateDirty=false;}
if(formName.curr_year!=null&&formName.curr_month!=null&&formName.curr_date!=null){var curr_year=parseInt(formName.curr_year.value);var curr_month=parseInt(formName.curr_month.value);var curr_date=parseInt(formName.curr_date.value);if(birth_year>curr_year&&gender!='O'){MessageHelper.formErrorHandleClient(birthDateId.id,MessageHelper.messages["MY_ACC_CHILD_INVALID_DOB"]);birthDateDirty=false;}else{if((birth_year==curr_year)&&(birth_month>curr_month)&&gender!='O'){MessageHelper.formErrorHandleClient(birthMonthId.id,MessageHelper.messages["MY_ACC_CHILD_INVALID_DOB"]);birthDateDirty=false;}else{if((birth_year==curr_year)&&(birth_month==curr_month)&&(birth_date>curr_date)&&gender!='O'){MessageHelper.formErrorHandleClient(birthDateId.id,MessageHelper.messages["MY_ACC_CHILD_INVALID_DOB"]);birthDateDirty=false;}}}}}
if(genderDirty&&birthDateDirty&&relationDirty)
return true;else
{if(!genderDirty){MessageHelper.formErrorHandleClient(genderId.id,MessageHelper.messages["MY_ACC_CHILD_GENDER_ERROR_MESSAGE"]);}
if(!relationDirty){MessageHelper.formErrorHandleClient(relationId.id,MessageHelper.messages["MY_ACC_CHILD_RELATIONSHIP_ERROR_MESSAGE"]);}
return false;}},validateAllForm:function(){var isValid=true;var emailForm=document.forms['EmailSignUpForm'];var email=emailForm.email.value;if(EmailSignupJS.isEmpty(email)){isValid=false;}
else if(EmailSignupJS.isValidEmailAddress(email)==false){isValid=false;}
var childCount=parseInt($("#childCountHidden").val());for(var i=1;i<=childCount;i++){var childValid=true;var formName=document.forms['childForm_'+i];if(!EmailSignupJS.validateChildForm(formName,i)){isValid=false;}}
return isValid;},saveEmailSignUpData:function(jsonData){$.ajax({url:getAbsoluteURL()+"SubscribeToEmail",type:"POST",data:{"json":jsonData,"sendEmail":'Y',"catalogId":WCParamJS.catalogId,"storeId":WCParamJS.storeId,"langId":WCParamJS.langId,"mbrgrpname":WCParamJS.mbrgrpname},beforeSend:function(){resetRequest();submitRequest()
cursor_wait();},complete:function(){},success:function(result){var obj=JSON.parse(jsonData);var catalogId=obj.CatalogId;var storeId=obj.storeId;dijit.byId('EmailSignupDialog').hide();var emailSignUpThankYouDialog=dijit.byId('EmailSignUpThankYouDialog');emailSignUpThankYouDialog.show();cursor_clear();try{if(typeof utag!='undefined'&&utag!=null&&typeof tealium_event!='undefined'&&tealium_event!=null){if(document.getElementById("WC_EmailSignupForm_div_21")!=undefined&&document.getElementById("WC_EmailSignupForm_div_21")!=null){var email=document.getElementById("WC_EmailSignupForm_div_21").value;}
tealium_event.opt_in.customer_email=email;tealium_event.opt_in.email_capture_location="Footer";utag.link(tealium_event.opt_in);}}catch(err){console.debug(err);}},error:function(ex){cursor_clear();}});},}
dojo.addOnLoad(function(){EmailSignupJS.locale=$("#locale").val();if($('#email-signUp-tile').length){$('#email-signUp-tile').on('hidden.bs.collapse',function(){ShowHideTopBar('hide');});if('ontouchstart'in window||navigator.maxTouchPoints){$('#email-signUp-tile .click-link').html($('#email-signUp-tile .click-link').html().replace("click here","tap here"))}}});var toggleCollapsible=function(collapsible){var content=collapsible.querySelector(".content");var expanded=collapsible.getAttribute("aria-expanded");var mainESpotHome=document.getElementById("mainESpotHome");(content.id.match(/homeESpotDetails/))?((mainESpotHome.className=="closed")?mainESpotHome.className="expand":mainESpotHome.className="closed"):0;if(expanded=="true"){content.style.maxHeight=content.scrollHeight+"px";window.setTimeout(function(){collapsible.setAttribute("aria-expanded","false");content.style.maxHeight=null;content.style.transition="max-height .2s";},0);window.setTimeout(function(){content.style.transition=null;},200);}
else if(expanded=="false"){collapsible.setAttribute("aria-expanded","true");content.style.maxHeight=content.scrollHeight+"px";content.style.transition="max-height .2s";window.setTimeout(function(){content.style.maxHeight=null;content.style.transition=null;},200);}};var updateGrid=function(grid){var width=grid.clientWidth;var minColWidth=grid.getAttribute("data-min-col-width");var minColCount=grid.getAttribute("data-min-col-count");var colCount=Math.floor(width/minColWidth);if(colCount<minColCount){colCount=minColCount;}
var colWidth=Math.floor(100/colCount)+"%";var cols=grid.querySelectorAll(".col");for(var i=0;i<cols.length;i++){cols[i].style.width=colWidth;}};var toggleExpand=function(id){var icon=byId("icon_"+id);var section_list=byId("section_list_"+id);if(icon.className=="arrow"){icon.className="arrow arrow_collapsed";section_list.setAttribute("aria-expanded","false");section_list.style.display="none";}
else{icon.className="arrow";section_list.setAttribute("aria-expanded","true");section_list.style.display="block";}};require(["dojo/on","dojo/query","dojo/topic","dojo/dom-attr","dojo/NodeList-traverse","dojo/domReady!"],function(on,query,topic){var updateCollapsibles=function(mediaQuery){var expanded=mediaQuery?!mediaQuery.matches:document.documentElement.clientWidth>583;if(expanded==false){query(".collapsible").attr("aria-expanded",expanded.toString());}else{query(".collapsible:not(.collapsedOnInit)").attr("aria-expanded",expanded.toString());}};if(window.matchMedia){var mediaQuery=window.matchMedia("(max-width: 600px)");updateCollapsibles(mediaQuery);mediaQuery.addListener(updateCollapsibles);}
else{updateCollapsibles();on(window,"resize",function(event){updateCollapsibles();});}
on(document,".collapsible .toggle:click",function(event){toggleCollapsible(query(event.target).parents(".collapsible")[0]);event.preventDefault();});on(document,".collapsible .toggle:keydown",function(event){if(event.keyCode==13||event.keyCode==32){toggleCollapsible(query(event.target).parents(".collapsible")[0]);event.preventDefault();}});query(".grid").forEach(updateGrid);on(window,"resize",function(event){query(".grid").forEach(updateGrid);});});ChildInfoJS={showAddChildBirthDayForm:function(){try{var addChildBirthdayInfoElement=document.getElementById("addChildBirthdayInfo");if(addChildBirthdayInfoElement!=null&&addChildBirthdayInfoElement!=undefined){addChildBirthdayInfoElement.classList.remove('hide');}
var addChilBirthInfoButtonElement=document.getElementById("addChilBirthInfoButton");if(addChilBirthInfoButtonElement!=null&&addChilBirthInfoButtonElement!=undefined){addChilBirthInfoButtonElement.classList.add('hide');}}catch(e){console.log("Error:"+e);}},hideAddChildBirthDayForm:function(){try{var addChildBirthdayInfoElement=document.getElementById("addChildBirthdayInfo");if(addChildBirthdayInfoElement!=null&&addChildBirthdayInfoElement!=undefined){addChildBirthdayInfoElement.classList.add('hide');}
var addChilBirthInfoButtonElement=document.getElementById("addChilBirthInfoButton");if(addChilBirthInfoButtonElement!=null&&addChilBirthInfoButtonElement!=undefined){addChilBirthInfoButtonElement.classList.remove('hide');}
var addBirthdayForm=document.forms['Register_'];if(addBirthdayForm!=null&&addBirthdayForm!=''){addBirthdayForm.reset();}}catch(e){console.log("Error:"+e);}},deleteChildBirthDayForm:function(selectionName,addressDeleteUrl,personalInfortionURL,storeId,catalogId){console.log("selectionName"+selectionName+"addressDeleteUrl:"+addressDeleteUrl);var params=[];params.storeId=storeId;params.catalogId=catalogId;params.addressId=selectionName;params.URL=personalInfortionURL;dojo.require("wc.service.common");wc.service.declare({id:"AddressDelete",actionId:"AddressDelete",url:addressDeleteUrl,successHandler:function(serviceResponse){wc.render.updateContext("showChildBirthdayInformationContext",{});cursor_clear();},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}
else{if(serviceResponse.errorMessageKey){MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);}}
cursor_clear();}});if(!submitRequest()){return;}
cursor_wait();wc.service.invoke("AddressDelete",params);},prepareRegSubmit:function(form,addressId){var childList=dojo.query('div[id^="birth-info_"]');var maxChildCount=6;if(childList.length>=maxChildCount){MessageHelper.formErrorHandleClient(document.getElementById("maxChild_err").id,"We are sorry. Maximum of "+maxChildCount+" children allowed");return false;}
if(document.getElementById("firstName_"+addressId+"_err")!=null&&document.getElementById("firstName_"+addressId+"_err")!="undefined"){document.getElementById("firstName_"+addressId+"_err").innerHTML="";}
document.getElementById("birth_year_"+addressId+"_err").innerHTML="";document.getElementById("birth_month_"+addressId+"_err").innerHTML="";document.getElementById("birth_date_"+addressId+"_err").innerHTML="";document.getElementById("businessTitle_"+addressId+"_err").innerHTML="";document.getElementById("gender_"+addressId+"_err").innerHTML="";var firstName="";var businessTitle="";var birth_year="";var birth_month="";var birth_date="";var genderValue="";var validFlag=true;var relationshipList=form["businessTitle_"+addressId];for(var i=0;i<relationshipList.length;i++)
{if(relationshipList[i].checked)
{businessTitle=relationshipList[i].value;}}
if(document.getElementById("firstName_"+addressId)!=null&&document.getElementById("firstName_"+addressId)!="undefined"){firstName=document.getElementById("firstName_"+addressId).value;}
if(addressId==""||addressId==undefined||addressId==null){var relationshipList=form["businessTitle_"+addressId];var genderList=form["billingCodeType"+addressId];for(var i=0;i<genderList.length;i++)
{if(genderList[i].checked)
{genderValue=genderList[i].value;}}
if(businessTitle=="0"||businessTitle==""){this.mattelFormErrorHandleClient("businessTitle_"+addressId,"Please select the relationship");validFlag=false;return false;}
if(genderValue=="0"||genderValue==""){this.mattelFormErrorHandleClient("gender_"+addressId,"Please select the gender");validFlag=false;return false;}}
if(null!=document.getElementById("birth_year_"+addressId)){birth_year=document.getElementById("birth_year_"+addressId).value;}
if(null!=document.getElementById("birth_month_"+addressId)){birth_month=document.getElementById("birth_month_"+addressId).value;if(birth_month<10)
{birth_month=birth_month;}}
if(null!=document.getElementById("birth_date_"+addressId)){birth_date=document.getElementById("birth_date_"+addressId).value;if(birth_date<10)
{birth_date=birth_date;}
reWhiteSpace=new RegExp(/^\s+$/);var exp=/^[a-zA-Z0-9\s]+$/;if(document.getElementById("firstName_"+addressId)!=null&&document.getElementById("firstName_"+addressId)!="undefined"){if(reWhiteSpace.test(firstName)||firstName==""){this.mattelFormErrorHandleClient("firstName_"+addressId,MessageHelper.messages["ERROR_NameEmpty"]);validFlag=false;}
if(!exp.test(firstName)){this.mattelFormErrorHandleClient("firstName_"+addressId,MessageHelper.messages["ERROR_NameEmpty"]);validFlag=false;}}
if(birth_year!="0"&&birth_month!="0"&&birth_date!="0"){var febDays=29;if(birth_year!="0"&&((birth_year%4)!="0")){febDays=28;}
var months=["4","6","9","11"];var monthFound=false;for(var i=0;i<months.length;i++){if(months[i]==birth_month){monthFound=true;break;}}
if(monthFound&&(birth_date>30)){this.mattelFormErrorHandleClient("birth_date_"+addressId,MessageHelper.messages["ERROR_InvalidDate1"]);validFlag=false;}
if((birth_month=="2")&&(birth_date>febDays)){this.mattelFormErrorHandleClient("birth_date_"+addressId,MessageHelper.messages["ERROR_InvalidDate1"]);validFlag=false;}
if(form.curr_year!=null&&form.curr_month!=null&&form.curr_date!=null){var curr_year=parseInt(form.curr_year.value);var curr_month=parseInt(form.curr_month.value);var curr_date=parseInt(form.curr_date.value);if(birth_year>curr_year&&form.billingCodeType.value!='O'){this.mattelFormErrorHandleClient(form.birth_year.id,MessageHelper.messages["ERROR_InvalidDate2"]);validFlag=false;}else{if((birth_year==curr_year)&&(birth_month>curr_month)&&form.billingCodeType.value!='O'){this.mattelFormErrorHandleClient("birth_month_"+addressId,MessageHelper.messages["ERROR_InvalidDate2"]);validFlag=false;}else{if((birth_year==curr_year)&&(birth_month==curr_month)&&(birth_date>curr_date)&&form.billingCodeType.value!='O'){this.mattelFormErrorHandleClient("birth_date_"+addressId,MessageHelper.messages["ERROR_InvalidDate2"]);validFlag=false;}}}
document.getElementById("addressField2").value=birth_month+"/"+birth_date+"/"+birth_year;}}else{if(form.billingCodeType.value!=''){this.mattelFormErrorHandleClient("birth_date_"+addressId,MessageHelper.messages["MY_ACC_CHILD_INVALID_DOB"]);validFlag=false;}}
if(validFlag){if(null!=document.getElementById("actionType_"+addressId)){var type=document.getElementById("actionType_"+addressId).value;if(type=="EDIT"||"DEFAULT_EDIT"==type){form.addressId.value=addressId;}}
document.getElementById("businessTitle").value=businessTitle;document.getElementById("birth_year").value=birth_year;document.getElementById("birth_month").value=birth_month;document.getElementById("birth_date").value=birth_date;if(document.getElementById("firstName_"+addressId)!=null&&document.getElementById("firstName_"+addressId)!="undefined"){form.firstName.value=firstName.trim();}
form.businessTitle.value=businessTitle;form.addressField2.value=birth_month+"/"+birth_date+"/"+birth_year;var functionType=form.type.value;if(functionType=="EDIT"){if(!submitRequest()){return;}
cursor_wait();wc.service.getServiceById("MattelAjaxUpdateBirthDate").formId=form.id;wc.service.invoke("MattelAjaxUpdateBirthDate");}else{if(null!=document.getElementById("addressId")){document.getElementById("addressId").value="";}
if(!submitRequest()){return;}
wc.service.getServiceById("MattelAjaxAddBirthDate").formId="Register_"+addressId;cursor_wait();wc.service.invoke("MattelAjaxAddBirthDate");}
return true;}else{return false;}}},showEditForm:function(addressId){document.getElementById("birth-info_"+addressId).style.display="none";document.getElementById("editForm_"+addressId).style.display="block";},addAnotherBirthDate:function(form,addressId){if(document.getElementById("firstName_"+addressId+"_err")!=null&&document.getElementById("firstName_"+addressId+"_err")!="undefined"){document.getElementById("firstName_"+addressId+"_err").innerHTML="";}
document.getElementById("birth_year_"+addressId+"_err").innerHTML="";document.getElementById("birth_month_"+addressId+"_err").innerHTML="";document.getElementById("birth_date_"+addressId+"_err").innerHTML="";document.getElementById("businessTitle_"+addressId+"_err").innerHTML="";var firstName="";var businessTitle="";var birth_year="";var birth_month="";var birth_date="";var validFlag=true;if(null!=document.getElementById("firstName_"+addressId)&&document.getElementById("firstName_"+addressId)!="undefined"){firstName=document.getElementById("firstName_"+addressId).value;}
if(null!=document.getElementById("businessTitle_"+addressId)){businessTitle=document.getElementById("businessTitle_"+addressId).value;}
if(null!=document.getElementById("birth_year_"+addressId)){birth_year=document.getElementById("birth_year_"+addressId).value;}
if(null!=document.getElementById("birth_month_"+addressId)){birth_month=document.getElementById("birth_month_"+addressId).value;}
if(null!=document.getElementById("birth_date_"+addressId)){birth_date=document.getElementById("birth_date_"+addressId).value;reWhiteSpace=new RegExp(/^\s+$/);var exp=/^[a-zA-Z0-9-]+$/;if(document.getElementById("firstName_"+addressId)!=null&&document.getElementById("firstName_"+addressId)!="undefined"){if(reWhiteSpace.test(firstName)||firstName==""){this.mattelFormErrorHandleClient("firstName_"+addressId,MessageHelper.messages["ERROR_NameEmpty"]);validFlag=false;}
if(!exp.test(firstName)){this.mattelFormErrorHandleClient("firstName_"+addressId,MessageHelper.messages["ERROR_NameEmpty"]);validFlag=false;}}
if(businessTitle=="0"){this.mattelFormErrorHandleClient("businessTitle_"+addressId,MessageHelper.messages["ERROR_RelationEmpty"]);validFlag=false;}
if(birth_year!="0"&&birth_month!="0"&&birth_date!="0"){var febDays=29;if(birth_year!="0"&&((birth_year%4)!="0")){febDays=28;}
var months=["4","6","9","11"];var monthFound=false;for(var i=0;i<months.length;i++){if(months[i]==birth_month){monthFound=true;break;}}
if(monthFound&&(birth_date>30)){this.mattelFormErrorHandleClient("birth_date_"+addressId,MessageHelper.messages["ERROR_InvalidDate1"]);validFlag=false;}
if((birth_month=="2")&&(birth_date>febDays)){this.mattelFormErrorHandleClient("birth_date_"+addressId,MessageHelper.messages["ERROR_InvalidDate1"]);validFlag=false;}
if(form.curr_year!=null&&form.curr_month!=null&&form.curr_date!=null){var curr_year=parseInt(form.curr_year.value);var curr_month=parseInt(form.curr_month.value);var curr_date=parseInt(form.curr_date.value);if(birth_year>curr_year){this.mattelFormErrorHandleClient(form.birth_year.id,MessageHelper.messages["ERROR_InvalidDate2"]);validFlag=false;}else{if((birth_year==curr_year)&&(birth_month>curr_month)){this.mattelFormErrorHandleClient("birth_month_"+addressId,MessageHelper.messages["ERROR_InvalidDate2"]);validFlag=false;}else{if((birth_year==curr_year)&&(birth_month==curr_month)&&(birth_date>curr_date)){this.mattelFormErrorHandleClient("birth_date_"+addressId,MessageHelper.messages["ERROR_InvalidDate2"]);validFlag=false;}}}
document.getElementById("addressField2").value=birth_month+"/"+birth_date+"/"+birth_year;}}else{this.mattelFormErrorHandleClient("birth_date_"+addressId,MessageHelper.messages["ERROR_SPECIFY_ALL_FIELDS"]);validFlag=false;}
if(validFlag){if(null!=document.getElementById("actionType_"+addressId)){var type=document.getElementById("actionType_"+addressId).value;if(type=="EDIT"||"DEFAULT_EDIT"==type){form.addressId.value=addressId;}}
document.getElementById("businessTitle").value=businessTitle;document.getElementById("birth_year").value=birth_year;document.getElementById("birth_month").value=birth_month;document.getElementById("birth_date").value=birth_date;if(document.getElementById("firstName_"+addressId)!=null&&document.getElementById("firstName_"+addressId)!="undefined"){form.firstName.value=firstName.trim();}
form.businessTitle.value=businessTitle;form.addressField2.value=birth_month+"/"+birth_date+"/"+birth_year;var functionType=form.type.value;if(functionType=="EDIT"){wc.service.getServiceById("AjaxUpdateBirthDate").formId=form.id;wc.service.invoke("AjaxUpdateBirthDate");}else{if(null!=document.getElementById("addressId")){document.getElementById("addressId").value="";}
wc.service.getServiceById("AjaxAddAnotherBirthDate").formId="Register_"+addressId;wc.service.invoke("AjaxAddAnotherBirthDate");}
return true;}else{return false;}}},mattelFormErrorHandleClient:function(id,errorMessage){var element=dojo.byId(id);if(errorMessage==null){console.debug("formErrorHandleClient: The error message is null.");return;}
if(element){var errNode=dojo.byId(id+"_err");if(dojo.isIE<7){node.innerHTML=errorMessage+"<iframe id='errorMessageIFrame' scrolling='no' frameborder='0' src='"+imgDirPath+"images/empty.gif'></iframe>";dojo.addClass(id+"_err","error text-danger small");}else{errNode.innerHTML=errorMessage;dojo.addClass(id+"_err","error text-danger small");}}}};dojo.addOnLoad(function(){wc.render.declareContext("BirthDateUpdateContext");wc.render.declareRefreshController({id:"BirthDateAddController",renderContext:wc.render.getContextById("BirthDateUpdateContext"),url:"",formId:"",renderContextChangedHandler:function(message,widget){widget.refresh(this.renderContext.properties);},postRefreshHandler:function(widget){if(null!=document.getElementById("addBirthdateButton")&&document.getElementById("addBirthdateButton")!="undefined"){document.getElementById("addBirthdateButton").style.display="none";}
var childCount=document.getElementById("childCount").value;if(childCount>=9){document.getElementById("applyAddBirthDate").style.display="none";}
if(this.renderContext.properties.sender=="MattelAjaxAddBirthDate"){hideEditForm_();}
if(null!=document.getElementById("firstName_")&&document.getElementById("firstName_")!="undefined"){document.getElementById("firstName_").value="";}}});wc.service.declare({id:"MattelAjaxAddBirthDate",actionId:"AjaxAddBirthDate",url:"AjaxPersonChangeServiceAddressAdd",formId:"",successHandler:function(serviceResponse){wc.render.updateContext("showChildBirthdayInformationContext",{});ChildInfoJS.hideAddChildBirthDayForm();try{var childAddForm=document.forms['Register_'];childAddForm.reset();}catch(e){console.log("Error"+e);}
cursor_clear()
resetRequest();},failureHandler:function(serviceResponse){cursor_clear();resetRequest();if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}}});wc.service.declare({id:"AjaxAddAnotherBirthDate",actionId:"AjaxAddAnotherBirthDate",url:"AjaxPersonChangeServiceAddressAdd",formId:"",successHandler:function(serviceResponse){wc.render.updateContext("BirthDateUpdateContext",{"sender":"AjaxAddAnotherBirthDate"});try{var childAddForm=document.forms['Register_'];childAddForm.reset();}catch(e){console.log("Error"+e);}},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}}});wc.service.declare({id:"MattelAjaxUpdateBirthDate",actionId:"AjaxUpdateBirthDate",url:"AjaxPersonChangeServiceAddressUpdate",formId:"",successHandler:function(serviceResponse){console.log("success");cursor_clear();resetRequest();wc.render.updateContext("showChildBirthdayInformationContext",{});},failureHandler:function(serviceResponse){cursor_clear();resetRequest();if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}}});wc.service.declare({id:"MattelAjaxDeleteBirthDate",actionId:"MattelAjaxDeleteBirthDate",url:"PersonChangeServiceAddressDelete",formId:"",successHandler:function(serviceResponse){console.log("success");wc.render.updateContext("showChildBirthdayInformationContext",{});},failureHandler:function(serviceResponse){if(serviceResponse.errorMessage){MessageHelper.displayErrorMessage(serviceResponse.errorMessage);}}});});var MattelAgeGate=MattelAgeGate||{langId:"-1",storeId:"",catalogId:"",userType:"",setCommonParameters:function(langId,storeId,catalogId,userType){this.langId=langId;this.storeId=storeId;this.catalogId=catalogId;this.userType=userType;},fromPageAction:"",init:function(){console.log("Init");},checkOutPageCheck:function(){var ageValidationCookie=dojo.cookie("ageValidationCookie");if(ageValidationCookie!=null&&ageValidationCookie!=undefined&&ageValidationCookie!=''){if(ageValidationCookie=='false'){document.location.href="/";}}},checkAge:function(userType,fromPage){if(userType=='G'){this.fromPageAction=fromPage;var ageValidationCookie=dojo.cookie("ageValidationCookie");if(ageValidationCookie==null||ageValidationCookie==undefined||ageValidationCookie==''){AgeGateDialog.show();return false;}else if(ageValidationCookie=='true'){if(this.fromPageAction=='checkoutLogon'){document.location.href="OrderShippingView?storeId="+this.storeId+"&catalogId="+this.catalogId+"&langId="+this.langId+"&URL="+"OrderShippingView"+"&errorViewName="+"AjaxOrderItemDisplayView"+"&isShippingAddressInvalid=false";}
if(this.fromPageAction=='catalogRequest'){return true;}
if(this.fromPageAction=='emailSignUp'){return true;}
if(this.fromPageAction=='emailSignUpHeader'){return true;}}
else if(ageValidationCookie='false'){AgeGateErrorDialog.show();return false;}}
return true;},checkAgeInCatalogRequest:function(userType){if(userType=='G'){var ageValidationCookie=dojo.cookie("ageValidationCookie");if(ageValidationCookie==null||ageValidationCookie==undefined||ageValidationCookie==''){AgeGateDialog.show();return false;}else if(ageValidationCookie=='true'){return true;}
else if(ageValidationCookie='false'){AgeGateErrorDialog.show();return false;}}
return true;},validateAge:function(){MessageHelper.messages['MY_ACC_CHILD_INVALID_DOB']="Please enter a valid date."
var birth_year_select=document.getElementById("birth_year");var birth_year=birth_year_select.options[birth_year_select.selectedIndex].value;var birth_month_select=document.getElementById("birth_month");var birth_month=birth_month_select.options[birth_month_select.selectedIndex].value;var birth_date_select=document.getElementById("birth_date");var birth_date=birth_date_select.options[birth_date_select.selectedIndex].value;var flag=false;if(birth_year==0&&birth_month==0&&birth_date==0){MessageHelper.formErrorHandleClient("birth_year",MessageHelper.messages['MY_ACC_CHILD_INVALID_YEAR']);MessageHelper.formErrorHandleClient("birth_month",MessageHelper.messages['MY_ACC_CHILD_INVALID_MONTH']);MessageHelper.formErrorHandleClient("birth_date",MessageHelper.messages['MY_ACC_CHILD_INVALID_DATE']);flag=true;}
if(birth_year!=0||birth_month!=0||birth_date!=0){if(birth_year==0){MessageHelper.formErrorHandleClient("birth_year",MessageHelper.messages['MY_ACC_CHILD_INVALID_YEAR']);flag=true;}
if(birth_month==0){MessageHelper.formErrorHandleClient("birth_month",MessageHelper.messages['MY_ACC_CHILD_INVALID_MONTH']);flag=true;}
if(birth_date==0){MessageHelper.formErrorHandleClient("birth_date",MessageHelper.messages['MY_ACC_CHILD_INVALID_DATE']);flag=true;}
var febDays=29;if(birth_year!=0&&((birth_year%4)!=0)){febDays=28;}
var months=["4","6","9","11"];var monthFound=false;for(var i=0;i<months.length;i++){if(months[i]==birth_month){monthFound=true;break;}}
if(monthFound&&(birth_date>30)){MessageHelper.formErrorHandleClient("ageGateError".id,MessageHelper.messages['MY_ACC_CHILD_INVALID_DOB']);flag=true;}
if((birth_month==2)&&(birth_date>febDays)){MessageHelper.formErrorHandleClient("ageGateError".id,MessageHelper.messages['MY_ACC_CHILD_INVALID_DOB']);flag=true;}}
if(!flag){var presentYear=new Date().getFullYear();var enteredYear=birth_year;var checkageValidation=parseInt(presentYear)-parseInt(enteredYear);if(checkageValidation<18){dojo.cookie("ageValidationCookie","false",{path:"/"});AgeGateDialog.hide();AgeGateErrorDialog.show();}else{dojo.cookie("ageValidationCookie","true",{path:"/"});AgeGateDialog.hide();if(this.fromPageAction=='checkoutLogon'){document.location.href="OrderShippingView?storeId="+this.storeId+"&catalogId="+this.catalogId+"&langId="+this.langId+"&URL="+"OrderShippingView"+"&errorViewName="+"AjaxOrderItemDisplayView"+"&isShippingAddressInvalid=false";}
if(this.fromPageAction=='catalogRequest'){}
if(this.fromPageAction=='emailSignUp'){EmailSignupJS.startSignUp();}
if(this.fromPageAction=='emailSignUpHeader'){EmailSignupJS.startHeaderEmailSignUp();}}}}};MattelAgeGate.init();var AGRewards=AGRewards||{langId:"-1",storeId:"",catalogId:"",userType:"",fromPageAction:"",show:function(){$("html, body").animate({scrollTop:0},'slow',function(){if(AGRewards!=null&&AGRewards!=undefined){if(AGRewards.Dialog!=null&&AGRewards.Dialog!=undefined){if(AGRewards.Dialog!=null&&AGRewards.Dialog!=undefined){AGRewards.Dialog.show();}}}
setTimeout(function(){float_labels();},1000);});},setCommonParameters:function(langId,storeId,catalogId,userType){this.langId=langId;this.storeId=storeId;this.catalogId=catalogId;this.userType=userType;},updateEmail:function(){var emailDiv=document.getElementById("agRewardsEmail");if(emailDiv!=null&&emailDiv!=undefined){var email=emailDiv.value;if(email==""){MessageHelper.formErrorHandleClient("agRewardsEmail","Email address field cannot be empty");return false;}
else{var re=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;if(!re.test(email)){MessageHelper.formErrorHandleClient("agRewardsEmail","Please enter a valid email address");return false;}
var caTestRegex=/^.*\.[cC][aA]/;if(caTestRegex.test(email)){MessageHelper.formErrorHandleClient("agRewardsEmail","AG Rewards is a program for United States customers only");return false;}}
var params=[];params.storeId=this.storeId;params.catalogId=this.catalogId;params.langId=this.langId;params.loyaltyFromPage="myAccount";params.isloyaltyEmailcheckpass="N";params.email1=emailDiv.value;params.requesttype="ajax";cursor_wait();wc.service.invoke("MattelCreateLoyalty",params);}},removeAGFieldError:function(){var emailElement=document.getElementById("agRewardsEmail");if(emailElement!=null&&emailElement!=undefined){var errorElement=MessageHelper.errors[emailElement.id];if(errorElement!=null&&errorElement!=undefined){MessageHelper.removeError(emailElement.id);}}}};dojo.addOnLoad(function(){$('[data-show-ag-rewards="true"]').each(function(){$(this).click(AGRewards.show);});});MattelAddOnServicesJS={setCommonParameters:function(langId,storeId,catalogId){this.langId=langId;this.storeId=storeId;this.catalogId=catalogId;},initializeCorrectArray:function(sourceArray){var c=0;var finalArray=[];if(sourceArray!=null&&sourceArray!='undefined'&&sourceArray.length>0){for(var i=0;i<=sourceArray.length;i++){if(sourceArray[i]!=null&&sourceArray[i]!='undefined'){finalArray[c]=sourceArray[i];c=c+1;}}}
return finalArray;},addServiceToCart:function(){var params=[];var checkbox;var addFlag=true;var updateFlag=false;var productCount="";var itemCount="";var sourcePage="";var fromPage="";var srcPage=document.getElementById('sourcePage');var dynamicSetAddOn=document.getElementById('dynamicSetAddOn');var creatASetAddOn=document.getElementById('creatASetAddOn');var isUpdate=$("#addOnSelected").val();if(isUpdate=='true'){updateFlag=true;}
var parentOrderItemId=document.getElementById('parentOrderItemIdField').value;var childCatentryIdsForSet=document.getElementById('childCatentryIdsForSet');var catalogIdElement=document.getElementById('currentCatalogId');var catalogId;if(catalogIdElement!=null){catalogId=catalogIdElement.value;}
var storeIdElement=document.getElementById('currentStoreId');var storeId;if(storeIdElement!=null){storeId=storeIdElement.value;}
parentCatentryId=document.getElementById('parentCatentryId');if(dynamicSetAddOn!=null&&dynamicSetAddOn!='undefined'&&dynamicSetAddOn.value!=null&&dynamicSetAddOn.value!='undefined'){MattelTTshoppingActionsJS.addWCSSet2ShopCartAjax(parentCatentryId.value);childCatentryIdsForSet.value=paramAddon.childCatentryIdsForSet;srcPage.value=paramAddon.sourcePage;}
else if(creatASetAddOn!=null&&creatASetAddOn!='undefined'&&creatASetAddOn.value!=null&&creatASetAddOn.value!='undefined'&&creatASetAddOn.value=='creatASetAddOn'){MattelTTshoppingActionsJS.addCreateAset2ShopCartAjax();srcPage.value=paramAddon.sourcePage;childCatentryIdsForSet.value=paramAddon.childCatentryIdsForSet;}
var quickSellSelectedItems=document.getElementById('quickSellSelectedItems');if(quickSellSelectedItems!=null&&quickSellSelectedItems!='undefined'&&quickSellSelectedItems.value!=null&&quickSellSelectedItems.value!='undefined'){params.aosQuickSellCatEntryIdstoBeAddedArray=(quickSellSelectedItems.value).split('|');}
var numAddOnServicesItems=document.getElementById('numAddOnServicesItems');if(numAddOnServicesItems!=null&&numAddOnServicesItems!='undefined'&&numAddOnServicesItems.value!=null&&numAddOnServicesItems.value!='undefined'){itemCount=numAddOnServicesItems.value;}
var numAddOnServicesProducts=document.getElementById('numAddOnServicesProducts');if(numAddOnServicesProducts!=null&&numAddOnServicesProducts!='undefined'&&numAddOnServicesProducts.value!=null&&numAddOnServicesProducts.value!='undefined'){productCount=numAddOnServicesProducts.value;}
var aosItemCatEntryIdstoBeAddedArray=[];var aosItemQuantitytoBeAddedArray=[];var aosProdCatEntryIdstoBeAddedArray=[];var aosProdQuantitytoBeAddedArray=[];var aosItemOrderItemIdtoBeDeleted=[];var aosProductOrderItemIdtoBeDeleted=[];var addedItemOID="";var parCatentryId="";if(srcPage!=null&&srcPage!='undefined'&&srcPage.value!=null&&srcPage.value!='undefined'&&srcPage.value!=""){sourcePage=srcPage.value;}
if(sourcePage!=null&&sourcePage!='undefined'&&sourcePage!=""&&sourcePage=='PDP'){parCatentryId=MattelAddOnServicesJS.findCorrectParentCatentryId();}
if(itemCount!=null&&itemCount!='undefined'&&itemCount!=""){for(var i=1;i<=itemCount;i++){checkbox=document.getElementById('aosItem'+i);addedItemOID=document.getElementById('addedItem'+checkbox.value+'_OID');if(checkbox!=null&&checkbox.checked&&checkbox.value!=null&&checkbox.value!='undefined'){if((addedItemOID==null||addedItemOID=='undefined')){aosItemCatEntryIdstoBeAddedArray[i-1]=checkbox.value;aosItemQuantitytoBeAddedArray[i-1]=1;addFlag=true;}}else if(checkbox!=null&&!checkbox.checked){if(addedItemOID!=null&&addedItemOID!='undefined'&&addedItemOID.value!=null&&addedItemOID.value!='undefined'){aosItemOrderItemIdtoBeDeleted[i-1]=addedItemOID.value;updateFlag=true;}}}}
if(productCount!=null&&productCount!='undefined'&&productCount!=""){for(var i=1;i<=productCount;i++){var selectBox=document.getElementById('aosProduct'+i);var addedProductOID=document.getElementById('addedProduct_modal_'+i+'_OID');var addedProductCID=document.getElementById('addedProduct_modal_'+i+'_CID');if(selectBox!=null&&selectBox.value!=null&&selectBox.value!='notSelected'){if(sourcePage!=null&&sourcePage!='undefined'&&sourcePage=='PDP'&&selectBox.value!='NONE'){aosProdCatEntryIdstoBeAddedArray[i-1]=selectBox.value;aosProdQuantitytoBeAddedArray[i-1]=1;addFlag=true;}else{if(addedProductCID!=null&&addedProductCID!='undefined'&&addedProductOID.value!=null&&addedProductOID.value!='undefined'&&addedProductCID.value!=null&&addedProductCID.value!='undefined'&&selectBox.value!=addedProductCID.value){aosProductOrderItemIdtoBeDeleted[i-1]=addedProductOID.value;updateFlag=true;if(selectBox.value!='NONE'){aosProdCatEntryIdstoBeAddedArray[i-1]=selectBox.value;aosProdQuantitytoBeAddedArray[i-1]=1;addFlag=true;}}else if((addedProductCID==null||addedProductCID=='undefined')&&selectBox.value!='NONE'){aosProdCatEntryIdstoBeAddedArray[i-1]=selectBox.value;aosProdQuantitytoBeAddedArray[i-1]=1;addFlag=true;}}}}}
if(aosItemCatEntryIdstoBeAddedArray!=null&&aosItemCatEntryIdstoBeAddedArray!='undefined'&&aosItemCatEntryIdstoBeAddedArray!=""){var aosItemCatEntryIdstoBeAddedArrayFinal=MattelAddOnServicesJS.initializeCorrectArray(aosItemCatEntryIdstoBeAddedArray);params.aosItemCatEntryIdstoBeAddedArray=aosItemCatEntryIdstoBeAddedArrayFinal;}
if(aosItemQuantitytoBeAddedArray!=null&&aosItemQuantitytoBeAddedArray!='undefined'&&aosItemQuantitytoBeAddedArray!=""){var aosItemQuantitytoBeAddedArrayFinal=MattelAddOnServicesJS.initializeCorrectArray(aosItemQuantitytoBeAddedArray);params.aosItemQuantitytoBeAddedArray=aosItemQuantitytoBeAddedArrayFinal;}
if(aosItemOrderItemIdtoBeDeleted!=null&&aosItemOrderItemIdtoBeDeleted!='undefined'&&aosItemOrderItemIdtoBeDeleted!=""){var aosItemOrderItemIdtoBeDeletedFinal=MattelAddOnServicesJS.initializeCorrectArray(aosItemOrderItemIdtoBeDeleted);params.aosItemOrderItemIdtoBeDeleted=aosItemOrderItemIdtoBeDeletedFinal;}
if(aosProdCatEntryIdstoBeAddedArray!=null&&aosProdCatEntryIdstoBeAddedArray!='undefined'&&aosProdCatEntryIdstoBeAddedArray!=""){var aosProdCatEntryIdstoBeAddedArrayFinal=MattelAddOnServicesJS.initializeCorrectArray(aosProdCatEntryIdstoBeAddedArray);params.aosProdCatEntryIdstoBeAddedArray=aosProdCatEntryIdstoBeAddedArrayFinal;}
if(aosProdQuantitytoBeAddedArray!=null&&aosProdQuantitytoBeAddedArray!='undefined'&&aosProdQuantitytoBeAddedArray!=""){var aosProdQuantitytoBeAddedArrayFinal=MattelAddOnServicesJS.initializeCorrectArray(aosProdQuantitytoBeAddedArray);params.aosProdQuantitytoBeAddedArray=aosProdQuantitytoBeAddedArrayFinal;}
if(aosProductOrderItemIdtoBeDeleted!=null&&aosProductOrderItemIdtoBeDeleted!='undefined'&&aosProductOrderItemIdtoBeDeleted!=""){var aosProductOrderItemIdtoBeDeletedFinal=MattelAddOnServicesJS.initializeCorrectArray(aosProductOrderItemIdtoBeDeleted);params.aosProductOrderItemIdtoBeDeleted=aosProductOrderItemIdtoBeDeletedFinal;}
if(sourcePage!=null&&sourcePage!='undefined'&&sourcePage!=""&&sourcePage=='PDP'&&childCatentryIdsForSet!=null&&childCatentryIdsForSet!='undefined'&&childCatentryIdsForSet.value!=null&&childCatentryIdsForSet.value!='undefined'&&childCatentryIdsForSet.value!=""){params.childCatentryIdsForSet=childCatentryIdsForSet.value;params.aosChildCatEntryIdstoBeAddedForSetArray=(childCatentryIdsForSet.value).split('_');}
if(params.aosChildCatEntryIdstoBeAddedForSetArray!=null&&params.aosChildCatEntryIdstoBeAddedForSetArray!='undefined'&&((dynamicSetAddOn!=null&&dynamicSetAddOn!='undefined'&&dynamicSetAddOn.value!=null&&dynamicSetAddOn.value!='undefined')||(creatASetAddOn!=null&&creatASetAddOn!='undefined'&&creatASetAddOn.value!=null&&creatASetAddOn.value!='undefined'))){var totalNoOfComponentforDynamicSet=(params.aosChildCatEntryIdstoBeAddedForSetArray).length;var aosChildCatEntryIdstoBeAddedForSetArray=[];var aosChildCommentstoBeAddedForSetArray=[];var childCatentryIdsForForDynamicSet="";if(totalNoOfComponentforDynamicSet>0){childCatentryIdsForSet.value="";aosChildCommentstoBeAddedForSetArray[1]=paramAddon["comment_1"];for(var i=1;i<=totalNoOfComponentforDynamicSet;i++){var comment="comment";aosChildCatEntryIdstoBeAddedForSetArray[i]=paramAddon["catEntryId_"+(i+1)];aosChildCommentstoBeAddedForSetArray[i+1]=paramAddon["comment_"+(i+1)];if(childCatentryIdsForForDynamicSet!=null&&childCatentryIdsForForDynamicSet!=""){childCatentryIdsForForDynamicSet=childCatentryIdsForForDynamicSet+"_";}
childCatentryIdsForForDynamicSet=childCatentryIdsForForDynamicSet+paramAddon["catEntryId_"+(i+1)];}
if(aosChildCommentstoBeAddedForSetArray!=null&&aosChildCommentstoBeAddedForSetArray!='undefined'&&aosChildCommentstoBeAddedForSetArray!=""){params.aosChildCommentstoBeAddedForSetArray=MattelAddOnServicesJS.initializeCorrectArray(aosChildCommentstoBeAddedForSetArray);}
params.childCatentryIdsForSet=childCatentryIdsForForDynamicSet;}
if(paramAddon.quickSellSelectedItems!=null&&paramAddon.quickSellSelectedItems!='undefined'){params.aosQuickSellCatEntryIdstoBeAddedArray=(paramAddon.quickSellSelectedItems).split('|');}}
if(aosChildCatEntryIdstoBeAddedForSetArray!=null&&aosChildCatEntryIdstoBeAddedForSetArray!='undefined'&&aosChildCatEntryIdstoBeAddedForSetArray!=""){params.aosChildCatEntryIdstoBeAddedForSetArray=MattelAddOnServicesJS.initializeCorrectArray(aosChildCatEntryIdstoBeAddedForSetArray);}
console.info("Inside addFlag");var langId='-1';if("true"==$('#isCSROrderEntry').val()){params.storeId=$('#storeId').val();params.catalogId=$('#catalogId').val();params.orderId=$('#mattelCSROrderId').val();}else{params.storeId=storeId;params.catalogId=catalogId;params.langId=langId;}
var parentQuantity=document.getElementById('qty_1');if(parentQuantity!=null&&parentQuantity!='undefined'&&parentQuantity.value!=null&&parentQuantity.value!='undefined'){params.parentQuantity=parentQuantity.value;}else{params.parentQuantity='1';}
$("#addTocartLoadIconADD").css("display","block");params.parCatentryId=parCatentryId;params.parentOrderItemId=parentOrderItemId;params.sourcePage=sourcePage;params.mattelOrderType="Standard Orders";params.calculationUsage="-1,-2,-5,-6,-7,-21";var service=wc.service.getServiceById("mattelAddOnServicesSave");var currentPage=document.getElementById("currentPage");if(null!=currentPage&&undefined!=currentPage){params.fromPage=currentPage.value
console.info("currentPage: "+currentPage.value);}
service.formId="AddOnServices";if(addFlag||updateFlag){params.addFlag=addFlag;params.updateFlag=updateFlag;params.calculateOrder="1";wc.service.invoke("mattelAddOnServicesSave",params);}else{if("true"==$('#isCSROrderEntry').val()){$('#MyAGProductServices').trigger('close');}else{this.closeModal();}}},removeAddOnDialog:function()
{var isShopCart=document.getElementById('isShopCartPage');var isReviewPage=document.getElementById('isReviewPage');if(isShopCart!=undefined&&isShopCart!=null&&isShopCart!=""&&isShopCart.value)
{if(isShopCart.value)
dijit.byId('addOnServicesPopup').hide();}
else if(isReviewPage!=undefined&&isReviewPage!=null&&isReviewPage!="")
{if(isReviewPage.value)
dijit.byId('addOnServicesPopup').hide();}
else
{var parentOrderItemId=document.getElementById('parentOrderItemIdField').value;dijit.byId('addOnServicesPopup').hide();wc.render.updateContext('MiniShoppingCartContext',{addedOrderItemId:parentOrderItemId,displayMiniCart:"true"},"");}},closeModal:function(){if(("true"==$('#isCSROrderEntry').val()||"true"==$('#isCsrTrain').val())&&$("#CSRCommon_Widget").css("display")!="none"){$('#MyAGProductServices').trigger('close');}else{$("#addTocartLoadIconADD").css("display","block");var params=[];var sourcePage="";var addFlag=false;var addOnPage="";var srcPage=document.getElementById('sourcePage');var csrStatus=$('#isCsr').val();if("true"==csrStatus){params.orderType=$('#csrOrderType').val();params.orderSource=$('#csrOrderSource').val();parentCatentryId=document.getElementById('parentCatentryId');}
if(document.getElementById('dynamicSetAddOn')!=null&&document.getElementById('dynamicSetAddOn')!='undefined'){addOnPage=document.getElementById('dynamicSetAddOn').value;}
if(document.getElementById('creatASetAddOn')!=null&&document.getElementById('creatASetAddOn')!='undefined'){addOnPage=document.getElementById('creatASetAddOn').value;}
if(srcPage!=null&&srcPage!='undefined'&&srcPage.value!=null&&srcPage.value!='undefined'){sourcePage=srcPage.value;}
var quickSellSelectedItems=document.getElementById('quickSellSelectedItems');if(addOnPage!=null&&addOnPage!='undefined'&&addOnPage!=""){if(addOnPage=='dynamicSetAddOn'||addOnPage=='creatASetAddOn'){if(addOnPage=='dynamicSetAddOn'){MattelTTshoppingActionsJS.addWCSSet2ShopCartAjax(parentCatentryId.value);}
if(addOnPage=='creatASetAddOn'){MattelTTshoppingActionsJS.addCreateAset2ShopCartAjax();}
sourcePage=paramAddon.sourcePage;if(sourcePage!=null&&sourcePage!='undefined'&&sourcePage=='PDP'){params.addFlag=true;params.sourcePage=sourcePage;var parentQuantity=document.getElementById('qty_1');if(parentQuantity!=null&&parentQuantity!='undefined'&&parentQuantity.value!=null&&parentQuantity.value!='undefined'){params.parentQuantity=parentQuantity.value;}else{params.parentQuantity='1';}
if("true"==$('#isCSROrderEntry').val()||"true"==$('#isCsrTrain').val()||"true"==$("#isCsr").val()){params.storeId=$('#storeId').val();params.catalogId=$('#catalogId').val();if($('#mattelCSROrderId').val()!='undefined'&&$('#mattelCSROrderId').val()!=undefined&&$('#mattelCSROrderId').val()!=''){params.orderId=$('#mattelCSROrderId').val();}}else{params.storeId=CheckoutHelperJS.storeId;params.catalogId=CheckoutHelperJS.catalogId;params.langId=CheckoutHelperJS.langId;}
var childCatentryIdsForSet=paramAddon.childCatentryIdsForSet;;params.aosChildCatEntryIdstoBeAddedForSetArray=(childCatentryIdsForSet).split('_');var totalNoOfComponentforDynamicSet=(params.aosChildCatEntryIdstoBeAddedForSetArray).length;var aosChildCatEntryIdstoBeAddedForSetArray=[];var aosChildCommentstoBeAddedForSetArray=[];var childCatentryIdsForForDynamicSet="";if(totalNoOfComponentforDynamicSet>0){childCatentryIdsForSet.value="";aosChildCommentstoBeAddedForSetArray[1]=paramAddon["comment_1"];for(var i=1;i<=totalNoOfComponentforDynamicSet;i++){var comment="comment";aosChildCatEntryIdstoBeAddedForSetArray[i]=paramAddon["catEntryId_"+(i+1)];aosChildCommentstoBeAddedForSetArray[i+1]=paramAddon["comment_"+(i+1)];if(childCatentryIdsForForDynamicSet!=null&&childCatentryIdsForForDynamicSet!=""){childCatentryIdsForForDynamicSet=childCatentryIdsForForDynamicSet+"_";}
childCatentryIdsForForDynamicSet=childCatentryIdsForForDynamicSet+paramAddon["catEntryId_"+(i+1)];}
params.aosChildCatEntryIdstoBeAddedForSetArray=MattelAddOnServicesJS.initializeCorrectArray(aosChildCatEntryIdstoBeAddedForSetArray);params.aosChildCommentstoBeAddedForSetArray=MattelAddOnServicesJS.initializeCorrectArray(aosChildCommentstoBeAddedForSetArray);params.childCatentryIdsForSet=childCatentryIdsForForDynamicSet;if(paramAddon.quickSellSelectedItems!=null&&paramAddon.quickSellSelectedItems!='undefined'){params.aosQuickSellCatEntryIdstoBeAddedArray=(paramAddon.quickSellSelectedItems).split('|');}}
var parCatentryId=MattelAddOnServicesJS.findCorrectParentCatentryId();params.parCatentryId=parCatentryId;var currentPage=document.getElementById("currentPage");if(null!=currentPage&&undefined!=currentPage){params.fromPage=currentPage.value
console.info("currentPage: "+currentPage.value);}
params.mattelOrderType="Standard Orders";var service=wc.service.getServiceById("mattelAddOnServicesSave");service.formId="AddOnServices";params.calculateOrder="1";params.calculationUsage="-1,-2,-5,-6,-7,-21";wc.service.invoke("mattelAddOnServicesSave",params);}
$.v_modal.close();}}
else
{if(sourcePage!=null&&sourcePage!='undefined'&&sourcePage=='PDP'){params.addFlag=true;params.sourcePage=sourcePage;var parentQuantity=document.getElementById('qty_1');if(parentQuantity!=null&&parentQuantity!='undefined'&&parentQuantity.value!=null&&parentQuantity.value!='undefined'){params.parentQuantity=parentQuantity.value;}else{params.parentQuantity='1';}
if("true"==$('#isCSROrderEntry').val()){params.storeId=$('#storeId').val();params.catalogId=$('#catalogId').val();params.orderId=$('#mattelCSROrderId').val();}else{params.storeId=this.storeId;params.catalogId=this.catalogId;params.langId=this.langId;}
var childCatentryIdsForSet=document.getElementById('childCatentryIdsForSet');if(childCatentryIdsForSet!=null&&childCatentryIdsForSet!='undefined'&&childCatentryIdsForSet.value!=null&&childCatentryIdsForSet.value!='undefined'&&childCatentryIdsForSet.value!=""){params.childCatentryIdsForSet=childCatentryIdsForSet.value;params.aosChildCatEntryIdstoBeAddedForSetArray=(childCatentryIdsForSet.value).split('_');}
if(quickSellSelectedItems!=null&&quickSellSelectedItems!='undefined'&&quickSellSelectedItems.value!=null&&quickSellSelectedItems.value!='undefined'){params.aosQuickSellCatEntryIdstoBeAddedArray=(quickSellSelectedItems.value).split('|');}
var parCatentryId=MattelAddOnServicesJS.findCorrectParentCatentryId();params.parCatentryId=parCatentryId;params.mattelOrderType="Standard Orders";params.calculateOrder="1";params.calculationUsage="-1,-2,-5,-6,-7,-21";var currentPage=document.getElementById("currentPage");if(null!=currentPage&&undefined!=currentPage){params.fromPage=currentPage.value
console.info("currentPage: "+currentPage.value);}
var service=wc.service.getServiceById("mattelAddOnServicesSave");service.formId="AddOnServices";wc.service.invoke("mattelAddOnServicesSave",params);}else{$.v_modal.close();}}}},openModal:function(){},setAddOnProduct:function(counter){var e=document.getElementById("aosProduct"+counter);var strAddOnFeatureValue=e.value;if(strAddOnFeatureValue=='NONE'){dojo.html.set(dojo.byId('addOnPrice'+counter),"");}else if(strAddOnFeatureValue!='notSelected'){var params=[];console.log("service,,");params.catalogEntryId=strAddOnFeatureValue;var catalogIdElement=document.getElementById('currentCatalogId');var catalogId;if(catalogIdElement!=null){catalogId=catalogIdElement.value;}
var storeIdElement=document.getElementById('currentStoreId');var storeId;if(storeIdElement!=null){storeId=storeIdElement.value;}
var langId;var langIdElement=document.getElementById('langId');if(langIdElement!=null){langId=langIdElement.value;}
params.counter=counter;params.storeId=storeId;params.catalogId=catalogId;params.langId=langId;wc.service.invoke("MattelGetCatalogEntryDetailsByIDAddOns",params);}else{console.log("no price");dojo.html.set(dojo.byId('addOnPrice'+counter),"");}},getSelectedRadio:function(radios){for(var i=0;i<radios.length;i++){if(radios[i].checked){return radios[i];}}},updateAddOnPrice:function(catalogEntry,counter){if(catalogEntry.displayPrice!=null){dojo.html.set(dojo.byId('addOnPrice'+counter),catalogEntry.displayPrice);}else if(catalogEntry.listPrice>catalogEntry.offerPrice){var priceDisplay=dojo.byId('addOnPrice');dojo.html.set(dojo.byId('addOnPrice'+counter),catalogEntry.offerPrice);}else if(catalogEntry.offerPrice!=null){var priceDisplay=dojo.byId('addOnPrice');dojo.html.set(dojo.byId('addOnPrice'+counter),catalogEntry.offerPrice);}},findCorrectParentCatentryId:function(){var parentCatentryId="";var frmPage=$('#fromPage').val();if(frmPage=='BundlePage'){parentCatentryId=$("#resolvedmainBundleCatentryId").text();}
else{QuickInfoJS.setValues();parentCatentryId=QuickInfoJS.resolveSKU();}
return parentCatentryId;},allowClickOnce:function(){if(!submitRequest()){return;}},checkInventory:function(){var allowAddtoCart=true;var count=document.getElementById('numAddOnServicesItems');var checkedItemCount=0;if(count!=null&&count!='undefined'&&count!=''&&count.value!=null&&count.value!='undefined'&&count.value!=''){for(i=1;i<=count.value;i++){if(document.getElementById('aosItem'+i)!=null&&document.getElementById('aosItem'+i)!='undefined'){var check=document.getElementById('aosItem'+i).checked;var inv=document.getElementById('invMsg'+i).value;if(check==true&&inv=="true"){allowAddtoCart=false;}else if(check==true){checkedItemCount++;}}}}
var productCount=document.getElementById('numAddOnServicesProducts');var productItemIdsAndInvFlgList='0';var productItemIdsAndInvArr=[];var selectedProductItemId='';if(productCount!=null&&productCount!='undefined'){for(i=1;i<=productCount.value;i++){selectedProductItemId=document.getElementById('aosProduct'+i);if(selectedProductItemId!=null&&selectedProductItemId!='undefined'&&selectedProductItemId.value!=null&&selectedProductItemId.value!='undefined'&&selectedProductItemId.value!='NONE'&&selectedProductItemId.value!='notSelected'){productItemIdsAndInvFlgList=document.getElementById('productItemIdsAndInvFlgList'+i);if(productItemIdsAndInvFlgList!=null&&productItemIdsAndInvFlgList!='undefined'&&productItemIdsAndInvFlgList!=''&&productItemIdsAndInvFlgList.value!=null&&productItemIdsAndInvFlgList.value!='undefined'&&productItemIdsAndInvFlgList!=''){var indexUndScr=productItemIdsAndInvFlgList.value.indexOf('_');if(indexUndScr>0){productItemIdsAndInvArr=productItemIdsAndInvFlgList.value.split('_');for(j=0;j<productItemIdsAndInvArr.length;j++){var productItemIdAndInvFlg=productItemIdsAndInvArr[j];if(productItemIdAndInvFlg!=null&&productItemIdAndInvFlg!='undefined'){var index=productItemIdAndInvFlg.indexOf(':');var productItemId=productItemIdAndInvFlg.substr(0,index);var invFlg=productItemIdAndInvFlg.substr(index+1);if(invFlg=="true"&&productItemId==selectedProductItemId.value){allowAddtoCart=false;}else if(productItemId==selectedProductItemId.value){checkedItemCount++;}}}}}}}}
var isUpdate=$("#addOnSelected").val();if(isUpdate=='true'){allowAddtoCart=true;}
if(allowAddtoCart==true){this.addServiceToCart();}else{$('#errorMsg').attr('class','input-error');var addToDollButton=document.getElementById('addToDollButton');if(addToDollButton){this.setPointerEvent(addToDollButton,true);}}},setPointerEvent:function(element,value){if(element){if(value==true){element.style.pointerEvents="auto";}
else if(value==false){element.style.pointerEvents="none";}}}}
var Mattel=Mattel||{Utils:{log:function(){console.debug(arguments);},getCurrentURL:function(){return"";}}}
var utag_data={page_template_id:"",brand:"",page_category_id:"",page_id:"",event_id:"",event_category:"",page_type:"",platform:"",site_country:"",site_section:"",site_type:"",recent_login_date:"",event_type:"",area_of_login:"",language:"",search_autocorrect_values:"",search_results:"",search_term:"",search_type:"",product_id:"",product_name:"",product_category_id:"",add_to_bag_method:"",list_price:"",offer_price:"",product_inventory_status:"",backorder_date:"",average_review_rating:"",number_of_reviews:"",likelihood_to_recommend:"",multiple_products:"",quantity:"",unit_price:"",attribute_options1:"",attribute_options2:"",add_to_cart_sequence:"",search_refinement:"",search_refinement_value:"",promo_code_product:"",persistent_cart_item:"",order_id:"",order_subtotal:"",order_shipping:"",sales_tax:"",delivery_fee:"",payment_type:"",gift_card_value:"",billing_city:"",billing_state:"",billing_postal_code:"",billing_country:"",date_of_order:"",promo_code_order:"",user_type:"",espot_view:[],impression_cm_sp:[],impression_cm_re:[],manual_cm_sp:[],cm_vc:"",registration_id:"",form_errors:[],registrant_last_update:"",orig_registration_date:""};Mattel.Analytics={options:{debug:true},initialized:false,queue:[],addEvent:function(event){var event=(typeof event=="string"&&event.length>0)?event:null;if(event!=null){this.queue.push(event);this.log("Added Analytics Event to the Queue",event,this.queue);}
if(typeof utag!="undefined"&&typeof this.checkQueue!="undefined")
this.checkQueue();},publishFormErrors:function(){if(typeof this.handleFormErrors!='undefined'){this.handleFormErrors();}},setup:function(){this.log("SUCCESS: tealium script loaded successfully.",this);this.initialized=true;this.platform=this.Utils.getUserDevice();this.currentPageURL=this.Utils.getCurrentURL();this.documentReferer=this.Utils.getReferringURL();if(this.bindExtOnClickEvents!=null&&this.bindExtOnClickEvents!=undefined)
this.bindExtOnClickEvents();if(this.externalonClickEvents!=null&&this.externalonClickEvents!=undefined)
this.externalonClickEvents();if(this.handleFormErrors!=null&&this.handleFormErrors!=undefined)
this.handleFormErrors();if(this.checkQueue!=null&&this.checkQueue!=undefined)
this.checkQueue();},init:function(){try{if(this.initialized)return;if(this.tealiumTagOrgURI!=null||this.tealiumTagURI!=null){this.log("Init Analytics",this);utag_data.platform=this.getUserDevice().toUpperCase();utag_data.site_section=this.siteSection;utag_data.site_type=this.siteType;this.cachedScript(this.tealiumTagOrgURI).done(function(script,textStatus){setTimeout(function(){Mattel.Analytics.setup();if(typeof initPageLoadEvents!='undefined'){initPageLoadEvents()}},2000);}).fail(function(jqxhr,settings,exception){this.log("ERROR: could not load tealium",this);});}}catch(e){this.log(e,this);}},definitions:{},events:{loadApplyPromoMSOnloadEvent:['link','conversion','Shop:Checkout:Shipping Method:Apply Promo Code','Checkout','Shipping Method:Apply Promo Code'],loadCartEditViewMSEvent:['view','elementConversion','Shop:Checkout:Shipping Method:Quick View Edit/View','','Cart Shipping Method - Quick View'],loadEditViewCartEvent:['view','elementConversion','Shop:Cart:Quick View Edit/View','MTW30006000US','Shopping Cart - Quick View'],loadOrderStatusGuestConEvent:['link','conversionSuccess','Shop:My Account Order Status ','My Account','My Account Order Status'],loadMyAccViewOrderStatusFooterEvent:['link','conversion','My Account:Orders:View Order:Footer ','My Account:Orders','My Account Order Status'],loadMyAccBilPaymentEditSaveSuccessEvent:['link','registration','My Account:Edit Payment method','My Account:Billing','My Account Billing'],loadForgotPasswordStatusViewEvent:['view','','Shop:My Account:Order Status:Forgot Password','My Account','My Account Order Status - Forgot Password'],loadForgotPasswordStatusConEvent:['link','conversion','Shop:My Account:Order Status:Forgot Password','My Account:Orders','My Account:Order Status:Sign In Lookup'],loadMyAccRemoveShippingAddrSuccessEvent:['link','registrationConversionSuccess','Shop:My Account:Shipping:Remove Address','My Account','My Account Shipping'],loadForgotPasswordEvent:['link','conversionSuccess','Shop:My Account:Password Retrieval','My Account','My Account Login/Register'],loadPasswordResetLoginEvent:['link','conversion','Shop:My Account:Password Reset','My Account','My Account:Password Reset'],loadOrdercheckoutSubmitConEvent:['link','conversionSuccess','My Account:Order Status:Guest Submit','My Account:Orders','My Account:Order Status:Sign In Lookup'],loadPasswordChngeElementEvent:['link','element','Shop:My Account:Password Reset','My Account','Shop:My Account:Password Reset'],loadStartCheckoutConEvent:['link','conversion','Shop:Checkout:Login:Guest','Checkout�Log�In','Checkout Login'],loadCheckoutCreditCardExpandCollapseEvent:['link','elementConversion','Shop:Billing:Credit Card Expand and collapse','Checkout','Billing:Credit Card Expand and collapse'],loadCheckoutGiftCardExpandCollapseEvent:['link','elementConversion','Shop:Billing:Gift Card Expand','Checkout','Billing:Gift Card Expand'],loadLoginMyAccViewOrderEvent:['link','conversionSuccess','Shop:My Account:View Order ','My Account','My Account Order Status'],loadMyAccViewOrderFooterEvent:['link','conversionSuccess','My Account:Orders:View Order:Footer ','My Account:Orders','My Account Order Status']},pageDefinitions:{giftOptionDisplay:['','10000','','SITE_SECTION_SHOP'],passwordResetSuccess:['My Account:Password Reset Success','10012','My Account','SITE_SECTION_SHOP'],BVReviewSubmission:['','','','SITE_SECTION_SHOP'],editItemAttrQV:['','30000','','SITE_SECTION_SHOP']},externalonClickEvents:function(){Mattel.Utils.log('externalonClickEvents');},externalOnLoadEvents:{},log:function(){if(this.options.debug&&typeof console!='undefined'){if(typeof console.log!="undefined")
return console.log(arguments);return console.debug(arguments);}},cachedScript:function(url,options){options=$.extend(options||{},{dataType:"script",cache:true,asynch:true,timeout:3000,url:url});return $.ajax(options);},getReferringURL:function(){var documentReferer=document.referrer;if(null!=documentReferer&&$.trim(documentReferer)!=''){documentReferer=documentReferer.substring(0,documentReferer.indexOf('?'));return documentReferer;}else{return this.getCurrentURL();}},getCurrentURL:function(){var currentPageURL=location.href;currentPageURL=currentPageURL.substring(0,currentPageURL.indexOf('?'));return currentPageURL;},getUserDevice:function(){var ua=navigator.userAgent;return
ua.match(/GoogleTV|SmartTV|Internet.TV|NetCast|NETTV|AppleTV|boxee|Kylo|Roku|DLNADOC|CE\-HTML/i)?'tv':ua.match(/Xbox|PLAYSTATION.3|Wii/i)?'tv':ua.match(/iPad/i)||ua.match(/tablet/i)&&!ua.match(/RX-34/i)||ua.match(/FOLIO/i)?'tablet':ua.match(/Linux/i)&&ua.match(/Android/i)&&!ua.match(/Fennec|mobi|HTC.Magic|HTCX06HT|Nexus.One|SC-02B|fone.945/i)?'tablet':ua.match(/Kindle/i)||ua.match(/Mac.OS/i)&&ua.match(/Silk/i)?'tablet':ua.match(/GT-P10|SC-01C|SHW-M180S|SGH-T849|SCH-I800|SHW-M180L|SPH-P100|SGH-I987|zt180|HTC(.Flyer|\_Flyer)|Sprint.ATP51|ViewPad7|pandigital(sprnova|nova)|Ideos.S7|Dell.Streak.7|Advent.Vega|A101IT|A70BHT|MID7015|Next2|nook/i)||ua.match(/MB511/i)&&ua.match(/RUTEM/i)?'tablet':ua.match(/BOLT|Fennec|Iris|Maemo|Minimo|Mobi|mowser|NetFront|Novarra|Prism|RX-34|Skyfire|Tear|XV6875|XV6975|Google.Wireless.Transcoder/i)?'mobile':ua.match(/Opera/i)&&ua.match(/Windows.NT.5/i)&&ua.match(/HTC|Xda|Mini|Vario|SAMSUNG\-GT\-i8000|SAMSUNG\-SGH\-i9/i)?'mobile':ua.match(/Windows.(NT|XP|ME|9)/)&&!ua.match(/Phone/i)||ua.match(/Win(9|.9|NT)/i)?'desktop':ua.match(/Macintosh|PowerPC/i)&&!ua.match(/Silk/i)?'desktop':ua.match(/Linux/i)&&ua.match(/X11/i)?'desktop':ua.match(/Solaris|SunOS|BSD/i)?'desktop':ua.match(/Bot|Crawler|Spider|Yahoo|ia_archiver|Covario-IDS|findlinks|DataparkSearch|larbin|Mediapartners-Google|NG-Search|Snappy|Teoma|Jeeves|TinEye/i)&&!ua.match(/Mobile/i)?'desktop':'mobile'}};$(function(){Mattel.Analytics.init();});var comicconIds;var device;var hasNext=false;var ytplayer;if(window.location.host.indexOf('americangirl')<0){if(window.location.host.indexOf('mqa2')>=0){comicconIds=["33489","33490","33492","33493","33494","33507"];}else if(window.location.host.indexOf('mdev2')>=0){comicconIds=["26063"];}else{comicconIds=["91458","91459","91460","91462","91464","91465"];}}
dojo.addOnLoad(function(){window.fp=window.fp||{};window.fp.playerModalOpened=false;window.fp.isModalOpened=false;showBumper();$("#contactUsForm button[type=Submit]").on('click',function(e){e.preventDefault();submitCSForm();});if(sfIndicator=='AG'&&window.innerWidth>=1024){$('.collapse','footer').on('shown.bs.collapse',function(){if($('#floatingMyOrder').length&&$('#floatingMyOrder').data('bs.affix')!=undefined){$('#floatingMyOrder').data('bs.affix').options.offset.bottom=$("footer").height();$('#floatingMyOrder').affix('checkPosition');}
scrollTo(0,pageYOffset-1);});}
$(".search-box .close-btn").on('click',function(){$("input.input-search").val("");});$('.searchIconHeader').on('hide.bs.dropdown',function(){$('.search-dropdown-menu',this).removeAttr('style');$('#SimpleSearchForm_SearchTerm').val('');});$('.searchIconHeader, .dropdown.search').on('show.bs.dropdown',function(){if($('.navbar-collapse').hasClass('in')){$('.navbar-collapse').removeClass('in');$('.navbar-toggle').removeClass('active').attr("aria-expanded",'false').addClass('collapsed');$('.navbar-brand').addClass('collapsed').attr("aria-expanded",'false').text('MENU');$('.main-navigation').removeClass('mmactive');$('.navbar-toggle').next('span').text('MENU');}});$('ol').each(function(){if($(this).attr('type')=="a"||$(this).attr('type')=="i")$(this).addClass('lower');if($(this).attr('type')=="A"||$(this).attr('type')=="I")$(this).addClass('upper');});$("#main-top-header .search-icon, .go-btn").on('click',function(e){if((window.fp.device==="desktop"&&$("#main-top-header .input-search.tt-input").val()!="")||($("#searchBox .search-box").hasClass('active')&&$("#main-top-header .input-search.tt-input").val()!="")){searchPage($("#main-top-header .input-search.tt-input").val());}else{e.stopPropagation();$("#searchBox .search-box").toggleClass("active");$("#main-top-header .input-search.tt-input").focus();}});$(".search-result-wrapper .search-icon").on('click',function(e){if((window.fp.device==="desktop"&&$(".search-result-wrapper .input-search.tt-input").val()!="")||($(".search-result-wrapper #searchBox .search-box").hasClass('active')&&$(".search-result-wrapper .input-search.tt-input").val()!="")){searchPage($(".search-result-wrapper .input-search.tt-input").val());}else{e.stopPropagation();$(".search-result-wrapper #searchBox .search-box").toggleClass("active");$(".search-result-wrapper .input-search.tt-input").focus();}});$('.content-filter .dropdown-accordion').on('show.bs.dropdown',function(event){var accordion=$(this).find($(this).data('accordion'));accordion.find('.panel-collapse.in').collapse('hide');accordion.find('.panel-heading').addClass('collapsed');});$('.content-filter .dropdown-accordion').on('click','h5[data-toggle="collapse"], .panel-collapse',function(event){if($(event.toElement).find('a').length==0&&!$(event.toElement).is('a')){event.preventDefault();event.stopPropagation();$($(this).data('parent')).find('.panel-collapse.in').collapse('hide');$($(this).attr('data-target')).collapse('show');}})
$('.content-filter .panel-collapse').on('click','li',function(event){if($(this).find('input[type=checkbox]').length>0){event.preventDefault();event.stopPropagation();if($(this).find('input[type=checkbox]').is(":checked")){$(this).find('input[type=checkbox]').prop('checked',false);$(this).removeClass('checked');}else{$(this).find('input[type=checkbox]').prop('checked',true);$(this).addClass('checked');}}})
$('.panel-collapse li').on('click','input[type=checkbox]',function(event){event.stopPropagation();if($(this).is(":checked")){$(this).closest('li').addClass('checked');}else{$(this).closest('li').removeClass('checked');}})
$('#playerPop').on('show.bs.modal',function(e){$('.modal-dialog').css({'width':(window.fp.device!="mobile")?'70%':'90%'});window.fp.playerModalOpened=true;reposition();var button=$(e.relatedTarget);var $medType=(typeof button.attr("med-type")!="undefined")?button.attr("med-type").toLowerCase():"";var $url=button.data("url");var $width=(typeof button.attr("player-width")!="undefined")?button.attr("player-width").toLowerCase():"";var $height=(typeof button.attr("player-height")!="undefined")?button.attr("player-height").toLowerCase():"";var embedObj='';switch($medType){case'ooyala':refreshFlashPlayer(button.attr('data-pid'),button.attr('data-id'));break;}
$(".modal-body #ooyalaplayer").css("display","block");});$('#playerPop').on('hide.bs.modal',function(e){if(!$.trim($("#ooyalaplayer").html())==''){if(window.fp){window.fp.player.pause();window.fp.player.justStartedPlaying=false;}}
if(ytplayer&&ytplayer.pauseVideo){ytplayer.pauseVideo();}});$('.emailsignup').addClass('click-link').on('click',function(e){e.preventDefault();});$('#floatingProductInfo').on('affixed.bs.affix ',function(){resetStopAffix();})
var agesArray=$("#ageGift").val()||"";if(agesArray!=""){agesArray=agesArray.split(",");var uiVariableSet=[];var toBePassedBack=[];for(var i=0;i<agesArray.length;i++){var temp=agesArray[i].split("|");uiVariableSet.push(temp[0]);toBePassedBack.push(temp[1]);}
$(".age_selected_range").text(uiVariableSet[0]+" - "+uiVariableSet[1]);$("#giftAge").val(toBePassedBack[0]+","+toBePassedBack[1]);$("#age-range-slider").ionRangeSlider({type:"double",values:uiVariableSet,grid:true,from:0,to:1,onChange:function(data){var temp="";for(var i=data.from;i<data.to;i++){temp+=toBePassedBack[i]+",";}
$("#giftAge").val(temp);$(".age_selected_range").text(uiVariableSet[data.from]+" - "+uiVariableSet[data.to]);}});}
var priceArray=$("#priceGift").val()||"";if(priceArray!=""){priceArray=priceArray.split(",");$(".price_selected_range").text("$"+priceArray[0]+" -"+" $"+priceArray[1]);$("#giftPrice").val(priceArray[0]+" TO "+priceArray[1]);$("#price-range-slider").ionRangeSlider({type:"double",values:priceArray,grid:true,from:0,to:1,onChange:function(data){$("#giftPrice").val(priceArray[data.from]+" TO "+priceArray[data.to]);$(".price_selected_range").text("$"+priceArray[data.from]+" -"+" $"+priceArray[data.to]);}});}
var floatBottomInMobiles=$("#product-detail .product-section .floatBottominMobiles")||'';if(floatBottomInMobiles.length>0){var screenWidth=(window.innerWidth>0)?window.innerWidth:screen.width;if(screenWidth<1024){if(sfIndicator==="AG"){var addToCartButton=$(".hide_add_to_cart_button_mobile");if(addToCartButton.hasClass("hasSwatches")){addToCartButton.toggleClass("hide");}}
$("footer .footer-wrappper").css("padding","80px 0");var definingAttributes=$(".definingAttributes")||"";var notify_me=$(".widget_notify_me")||"";var pdpMobileOptionsContainer=$('<div class="pdpOptionsContainer"></div>');$(pdpMobileOptionsContainer).append(definingAttributes);$(pdpMobileOptionsContainer).append(notify_me);(sfIndicator==="AG")?$(pdpMobileOptionsContainer).append('<i class="closeButton fa fa-times" aria-hidden="true"></i>'):$(pdpMobileOptionsContainer).append('<i class="closeButton" aria-hidden="true"></i>');floatBottomInMobiles.prepend(pdpMobileOptionsContainer);if(sfIndicator==="AG"){$(".productOptions").click(function(){$(pdpMobileOptionsContainer).toggleClass("displayOptions",0,"easeInOutExpo");$(floatBottomInMobiles).toggleClass("displayOptions");$(".showOptions").toggleClass("hide");$(".overlay").toggleClass("show");$(".floatBottominMobiles .productOptions").toggleClass("extraMarginForHideOptions");var thisProductObject=null;try{thisProductObject=eval("InventoryStatusJS_"+productDisplayJS.productId);}catch(e){thisProductObject=eval("InventoryStatusJS_"+$("#productParentId").val());}
if(thisProductObject.isSwatchSelected){$(".hideOptions").addClass("hide");$(".hide_add_to_cart_button_mobile").removeClass("hide");}else{$(".hideOptions").toggleClass("hide");}});$(".floatBottominMobiles .closeButton").click(function(){$(pdpMobileOptionsContainer).toggleClass("displayOptions",0,"easeInOutBack");$(floatBottomInMobiles).toggleClass("displayOptions");$(".showOptions").removeClass("hide");$(".hideOptions").addClass("hide");$(".overlay").toggleClass("show");$(".floatBottominMobiles .productOptions").toggleClass("extraMarginForHideOptions");$(".hide_add_to_cart_button_mobile").addClass("hide");});}else{$(".productOptions, .floatBottominMobiles .closeButton").click(function(){$(pdpMobileOptionsContainer).toggleClass("displayOptions",0,"easeInOutBack");$(floatBottomInMobiles).toggleClass("displayOptions");$(".showOptions").toggleClass("hide");$(".hideOptions").toggleClass("hide");$(".overlay").toggleClass("show");$(".floatBottominMobiles .productOptions").toggleClass("extraMarginForHideOptions");});}}}
$('h1').each(function(){if($(this).text().replace(/\s/g,"")==""){$(this).remove();}});if(window.location.pathname.indexOf("search-by-sku")>0){$.getJSON("/wcs/resources/store/10151/productview/"+getQueryVariable("sku"),function(data){var sf=$('html').attr('id').toLowerCase();var internalId=data.CatalogEntryView[0].uniqueID;window.location="/shop/en-us/"+sf+"/"+internalId;});}
if(window.location.pathname.indexOf("wtb-by-sku")>0){$.getJSON("/wcs/resources/store/10151/productview/"+getQueryVariable("sku"),function(data){var internalId=data.CatalogEntryView[0].uniqueID;window.location="/where-to-buy/"+internalId+"?ps-sku="+getQueryVariable("sku");});}});if((document.getElementById('ps_SA')!=null)&&(document.querySelectorAll('[name="ps-account"]').length==0)){document.getElementById('ps_SA').remove();}
function showProfileUrl(){$('.show-url-control').toggleClass('active').closest('.profile-url').find('.profile-url-toogle').slideToggle().toggleClass('collapsed');return false;}
function onYouTubePlayerAPIReady(){}
function vidPlayer(id){if(YT.Player){ytplayer=new YT.Player('ytPlayer',{height:'100%',width:'100%',videoId:id,playerVars:{rel:0},events:{'onReady':onPlayerReady}});}}
function onPlayerReady(event){if(window.fp.device!="mobile")
ytplayer.playVideo();ytplayer.addEventListener("onStateChange","onPlayerStateChange");}
function onPlayerStateChange(newState){var newStateObj;if(typeof(newState.data)!="undefined")newStateObj=newState.data;else newStateObj=newState;switch(newStateObj){case 0:break;case 1:break;case 2:break;}}
function refreshFlashPlayer(player,embed,LoadType){if(window['OO_FLASH']&&window['OO_FLASH'].Player&&window.fp.player.currentItem.embed_code!=embed){jQuery('#ooyalaplayer').empty();delete window['OO_FLASH'];}
$.getScript('https://player.ooyala.com/v3/'+player+'?namespace=OO_FLASH&platform=html5-priority',function(script,textStatus,jqXHR){window.fp=window.fp||{};if(typeof(LoadType)!='undefined'&&LoadType[0].element=="Loadinline"){var $inexVal=$("#VideoThumbGallery .owl-item.synced").index();if(window.fp.player&&window.fp.player.state=="playing"){window.fp.player.pause();window.fp.player.justStartedPlaying=false;}
window.fp.player=OO_FLASH.Player.create('ooyalaplayer'+$inexVal,embed,{onCreate:function(player){window.messageBus=player.mb;},autoplay:(window.fp.device=='desktop'?false:true)});if(LoadType[0].FirstTime){if(window.fp.device=='desktop'){window.fp.player.play();}
window.fp.player.justStartedPlaying=true;}}else{window.fp.player=OO_FLASH.Player.create('ooyalaplayer',embed,{autoplay:true,onCreate:function(player){window.messageBus=player.mb;}});window.fp.player.justStartedPlaying=true;}
if($("#eventDes").length&&$('#eventPos').length){window.fp.player.justStartedPlaying=true;var event_pos=$("#eventPos").val();var event_Des=$("#eventDes").val();window.messageBus.intercept('playing','example',function(eventName){var idindex=$("#"+window.fp.player.elementId).index();$($("#VideoThumbGallery .owl-item")[0]).removeClass('first-synced');if(window.fp.player.justStartedPlaying){utag.link({eve_cat:"videos",eve_act:"play",eve_lab:window.fp.player.item.title,eve_des:event_Des,eve_pos:event_pos});}else{utag.link({eve_cat:"videos",eve_act:"replay",eve_lab:window.fp.player.item.title,eve_des:event_Des,eve_pos:event_pos});}});window.messageBus.intercept('played','example',function(eventName){utag.link({eve_cat:"videos",eve_act:"complete",eve_lab:window.fp.player.item.title,eve_des:event_Des,eve_pos:event_pos});window.fp.player.justStartedPlaying=false;});}});}
function reposition(){var modal=$(this),dialog=modal.find('.modal-dialog');modal.css('display','block');dialog.css("margin-top",Math.max(0,($(window).height()-dialog.height())/2));}
function openEmailSignup(){if(window.location.hash.indexOf("email-sign-up")>=0||window.location.search.indexOf("?email-sign-up")>=0||window.location.search.indexOf("&email-sign-up")>=0){if($('.desktop-tile').is(":visible")){$('.desktop-tile a .click-link').trigger("click");}
else{$('.mobile-tile a .click-link').trigger("click");}}}
dojo.addOnLoad(function(){setTimeout(function(){window.thumbnail_slider=$(".thumbnailWrapper #carousel").html();deviceType();imgSwap();imgSwapTab();imgSwapDesktop();imgSwapHiRes();carouselInit();initSlider();carouselInitWithDestroy();hamburgerAnimate();contentEqualize();subbrandLogoSwap();swaptoMobile();swaptoTablet();footerAccordion();ProductDetailSlider2();ProductDetailAccordion();float_labels();initAffix();fixAffix();initMyOrder();initEspots();moveFAPBanner();fixMenu();fakeFocus();fixHashLinks();},200);});dojo.addOnLoad(function(){var $productList=$(".product-wrapper  .slides");if($productList.length){$productList.owlCarousel({autoPlay:false,navigation:true,navigationText:["&#x3C","&#x3E"],scrollPerPage:true,rewindNav:false,itemsCustom:[[0,2],[641,3],[1024,4]]});}
var $productCard=$(".product-wrapper .product");if($productCard.length){$productCard.removeAttr("style");$productCard.equalize();}
var $productCard=$("#product-wrapper .product");if($productCard.length){$productCard.removeAttr("style");$productCard.equalize();}
var $promoCard=$(".product-wrapper .promo");if($promoCard.length){$promoCard.css('height',$productCard.height());$promoCard.find('.product-bottom').css('width',$promoCard.width()+1);}
var ws=$(window).scrollTop();if(ws>100){$("header").removeClass("fixed-header");}
var $playtimeWrapper=$('.help-info-wrapper');$playtimeWrapper.each(function(index){if($('.help-info-wrapper img').eq(index).height()>$('.help-info-wrapper').eq(index).height()){$('.help-info-wrapper img').eq(index).css('max-height',$('.help-info-wrapper').eq(index).outerHeight(true));}});});dojo.addOnLoad(function(){$(window).resize(function(){deviceType();imgSwap();imgSwapTab();imgSwapDesktop();imgSwapHiRes();hamburgerAnimate();carouselInitWithDestroy();contentEqualize();subbrandLogoSwap();swaptoMobile();swaptoTablet();footerAccordion();initAffix();fixAffix();initMyOrder();moveFAPBanner();var $productCard=$(".product-wrapper .product");if($productCard.length>0){$productCard.removeAttr("style");$productCard.equalize();}
var $promoCard=$(".product-wrapper .promo");if($promoCard.length){$promoCard.css('height',$productCard.height());$promoCard.find('.product-bottom').css('width',$promoCard.width()+1);}});$.fn.equalize=function(){var maxHeight=0;this.each(function(){if($(this).height()>maxHeight){maxHeight=$(this).height();}});this.height(maxHeight);};});function contentEqualize(){if($(".article-tile-carousel ul li .article-info").length){$(".article-tile-carousel ul li .article-info").removeAttr('style')
$(".article-tile-carousel ul li .article-info").equalize();}
if(Modernizr.mq('all and (min-width: 641px)')){$('.why-power-wheels .promo-wrapper-1 .right-promo').css('height',$('.promo-wrapper-1 img').height());$('.why-power-wheels .promo-wrapper-2 .right-promo').css('height',$('.promo-wrapper-2 img').height());}
else{$('.why-power-wheels .promo-wrapper-1 .right-promo').removeAttr('style');$('.why-power-wheels .promo-wrapper-2 .right-promo').removeAttr('style');}}
function initSlider(){$(".landingSlider .slides").owlCarousel({navigation:true,navigationText:false,slideSpeed:300,paginationSpeed:400,singleItem:true,loop:true,autoPlay:true,autoPlayTimeout:1000,stopOnHover:true});if(Modernizr.mq('all and (max-width: 640px)')){var $landingSlider=$(".landingSlider .slides").data('owlCarousel');if($landingSlider)$landingSlider.stop();}}
function sliderAnimation(){TweenMax.staggerFrom("#carousel .owl-item",0.6,{scale:0.7,opacity:0,ease:Quint.easeOut});TweenMax.staggerTo("#carousel .owl-item",0.7,{scale:1,opacity:1,ease:Quint.easeOut});}
function deviceType(){if(Modernizr.mq('all and (max-width: 640px)')){device='mobile';window.fp.device='mobile';}else if(Modernizr.mq('all and (max-width: 1023px) and (min-width: 641px)')){device='tablet';window.fp.device='tablet';}else if(Modernizr.mq('all and (min-width: 1024px)')){device='desktop';window.fp.device='desktop';}}
function carouselDestroy(onBreakPoint,carouselSelector){onBreakPoint=onBreakPoint||"1024px";carouselSelector=carouselSelector||{};if(carouselSelector!={}&&typeof carouselSelector!='undefined'){if(Modernizr.mq('all and (min-width: '+onBreakPoint+')')){carouselSelector.data('owlCarousel').destroy();}}}
function panelistCarouselInit(elem){$('.quotes-tile-carousel .owl-next').on('click',function(){if(hasNext){utag.link({eve_cat:"promo",eve_act:"next arrow click",eve_lab:"ECD Panelists",eve_des:"The Happy Factor",eve_pos:"Panelists"});hasNext=false;}});}
function carouselMove(elem){hasNext=true;}
function carouselInit(){var owl=$("#carousel .slides");owl.owlCarousel({autoPlay:false,navigation:true,navigationText:["&#x3C","&#x3E"],rewindNav:false,scrollPerPage:true,itemsCustom:[[0,2],[768,3],[1024,4]],afterMove:sliderAnimation,afterUpdate:(function(){$('#carousel .slides p').removeAttr('style');$('#carousel .slides p').equalize();}),afterInit:(function(){$('#carousel .slides p').removeAttr('style');$('#carousel .slides p').equalize();})});var owl2=$("#brand-tiles-landing-carousel .items");owl2.owlCarousel({autoPlay:false,navigation:true,navigationText:["&#x3C","&#x3E"],scrollPerPage:true,slideSpeed:1000,rewindNav:false,itemsCustom:[[0,3],[641,5],[1024,7]]});var owl3=$("#play-learn-carousel .items");owl3.owlCarousel({autoPlay:false,navigation:true,navigationText:["&#x3C","&#x3E"],scrollPerPage:true,rewindNav:false,itemsCustom:[[0,1],[641,2],[768,3],[1024,4]]});var owl5=$(".ourStory-article #carouselItems");owl5.owlCarousel({autoPlay:false,navigation:true,navigationText:["&#x3C","&#x3E"],scrollPerPage:true,rewindNav:false,itemsCustom:[[0,2],[1024,3]]});var owl6=$(".ga-article #carouselItems");owl6.owlCarousel({autoPlay:false,navigation:false,scrollPerPage:true,rewindNav:false,itemsCustom:[[641,2],[1024,3]]});var owl7=$(".quotes-tile-carousel ul");owl7.owlCarousel({autoPlay:false,navigation:true,navigationText:["&#x3C","&#x3E"],slideSpeed:300,paginationSpeed:400,scrollPerPage:true,rewindNav:false,afterInit:panelistCarouselInit,afterMove:carouselMove,itemsCustom:[[0,1],[1024,3]]});var owl8=$(".map-tiles ul.map-items");owl8.owlCarousel({autoPlay:false,navigation:false,slideSpeed:300,paginationSpeed:400,singleItem:true,rewindNav:false});}
function carouselInitWithDestroy(){}
function ProductDetailSlider(){var sync1=$("#ProductGallery");var sync2=$("#ProductThumbGallery");if(sync1.length>0){if(Modernizr.mq('all and (max-width: 1023px)')){if(sync1.hasClass('slick-initialized')&&sync2.hasClass('slick-initialized')){sync1.slick("unslick");sync2.slick("unslick");$(sync2).removeAttr("style");}
sync1.owlCarousel({singleItem:true,navigation:false,pagination:true,afterAction:syncPosition,responsiveRefreshRate:200,});sync2.owlCarousel({items:4,itemsDesktop:[1199,4],itemsDesktopSmall:[979,3],itemsTablet:[768,3],itemsMobile:[479,3],scrollPerPage:true,navigation:true,navigationText:["&#x3C","&#x3E"],pagination:false,responsiveRefreshRate:100,itemsScaleUp:false,afterInit:function(el){el.find(".owl-item").eq(0).addClass("synced");}});function syncPosition(el){var current=this.currentItem;$("#ProductThumbGallery").find(".owl-item").removeClass("synced").eq(current).addClass("synced")
if($("#ProductThumbGallery").data("owlCarousel")!==undefined){center(current)}}
$("#ProductThumbGallery").on("click",".owl-item",function(e){e.preventDefault();var number=$(this).data("owlItem");sync1.trigger("owl.goTo",number);});function center(number){var sync2visible=sync2.data("owlCarousel").owl.visibleItems;var num=number;var found=false;for(var i in sync2visible){if(num===sync2visible[i]){var found=true;}}
if(found===false){if(num>sync2visible[sync2visible.length-1]){sync2.trigger("owl.goTo",num-sync2visible.length+2)}else{if(num-1===-1){num=0;}
sync2.trigger("owl.goTo",num);}}else if(num===sync2visible[sync2visible.length-1]){sync2.trigger("owl.goTo",sync2visible[1])}else if(num===sync2visible[0]){sync2.trigger("owl.goTo",num-1)}}}
else{if($(sync1).length&&$(sync2).length&&typeof $(sync1).data('owlCarousel')!='undefined'&&typeof $(sync2).data('owlCarousel')!='undefined'){$(sync1).data('owlCarousel').destroy();$(sync1).removeClass('owl-carousel');$(sync2).data('owlCarousel').destroy();$(sync2).removeClass('owl-carousel');}
$(sync1).slick({slidesToShow:1,slidesToScroll:1,arrows:false,infinite:false,asNavFor:sync2});var Height=$(sync1).height();$(sync2).css({'height':Height,'overflow':'hidden'});$(sync2).slick({slidesToShow:5,slidesToScroll:1,asNavFor:sync1,dots:false,arrows:true,infinite:false,prevArrow:"<span class='glyphicon glyphicon-chevron-up' aria-hidden='true'></span>",nextArrow:"<span class='glyphicon glyphicon-chevron-down' aria-hidden='true'></span>",focusOnSelect:true,vertical:true,verticalSwiping:true});$(sync1).on('beforeChange',function(slick,currentSlide,nextSlide,i){$(sync2).find('.slick-slide').removeClass('slick-current');$(sync2).find('.slick-slide').eq(i).addClass('slick-current');});}}}
function gallertTest2(){var sync1=$("#ProductGallery2");var sync2=$("#ProductThumbGallery2");sync1.owlCarousel({singleItem:true,navigation:false,pagination:true,afterAction:syncPosition,responsiveRefreshRate:200,});sync2.owlCarousel({items:4,itemsDesktop:[1199,4],itemsDesktopSmall:[979,4],itemsTablet:[768,3],itemsMobile:[479,3],pagination:false,responsiveRefreshRate:100,itemsMobile:false,itemsScaleUp:false,afterInit:function(el){el.find(".owl-item").eq(0).addClass("synced");}});function syncPosition(el){var current=this.currentItem;$("#ProductThumbGallery2").find(".owl-item").removeClass("synced").eq(current).addClass("synced")
if($("#ProductThumbGallery2").data("owlCarousel")!==undefined){center(current)}}
$("#ProductThumbGallery2").on("click",".owl-item",function(e){e.preventDefault();var number=$(this).data("owlItem");sync1.trigger("owl.goTo",number);});function center(number){var sync2visible=sync2.data("owlCarousel").owl.visibleItems;var num=number;var found=false;for(var i in sync2visible){if(num===sync2visible[i]){var found=true;}}
if(found===false){if(num>sync2visible[sync2visible.length-1]){sync2.trigger("owl.goTo",num-sync2visible.length+2)}else{if(num-1===-1){num=0;}
sync2.trigger("owl.goTo",num);}}else if(num===sync2visible[sync2visible.length-1]){sync2.trigger("owl.goTo",sync2visible[1])}else if(num===sync2visible[0]){sync2.trigger("owl.goTo",num-1)}}}
function ProductDetailSlider2(){var sync1=$("#ProductGallery2"),sync2=$("#ProductThumbGallery2");if(typeof(OoyalaURL)!="undefined"){$.get(OoyalaURL,function(data){data.items.forEach(function(element){console.log(element);sync1.append('<div class="item"><a data-id="'+element.embed_code+'" data-pid="'+element.player_id+'" med-type="ooyala"  data-url="" title="Design Video"  class="design_video"  data-toggle="modal" href="#playerPop" tealiumtrack="Int. Promo|power-wheels|'+element.name+'"><img src="'+element.preview_image_url_ssl+'" alt="" /><span class="play-icon glyphicon glyphicon-play-circle"></span></a></div>');sync2.append('<div class="item"><a class="video-thumb"><img src="'+element.preview_image_url_ssl+'" url="" rel="" title="'+element.name+'" med-type="ooyala"/></a><p class="tile-label">'+element.name+'</p></div>');});sync1.owlCarousel({items:1,nav:true,dots:false,callback:true}).on('dragged.owl.carousel',function(e){if(e.relatedTarget.state.direction=='left'){sync2.trigger('next.owl.carousel')}else{sync2.trigger('prev.owl.carousel')}});sync2.owlCarousel({items:4,responsive:{0:{items:2},768:{items:3},1024:{items:4}},nav:false,dots:true,callback:true,}).on('click','.owl-item',function(){var i=$(this).index();sync2.trigger('to.owl.carousel',[i,200,true]);sync1.trigger('to.owl.carousel',[i,200,true]);}).on('changed.owl.carousel',function(e){sync1.trigger('to.owl.carousel',[e.item.index-thumbs,200,true]);});});}}
function imgSwap(){if(Modernizr.mq('all and (max-width: 640px)')){$(".imgswap").each(function(){imgSrc=$(this).attr("mobile-img");$(this).attr("src",imgSrc);});}
else{$(".imgswap").each(function(){imgSrc=$(this).attr("desk-img");$(this).attr("src",imgSrc);});}}
function imgSwapTab(){var imgSrc="";if(Modernizr.mq('all and (max-width: 1023px)')){$(".imgswapTab").each(function(){imgSrc=$(this).attr("mobile-img");$(this).attr("src",imgSrc);});}
else{$(".imgswapTab").each(function(){imgSrc=$(this).attr("desk-img");$(this).attr("src",imgSrc);});}
return;}
function imgSwapDesktop(){var imgSrc="";if(Modernizr.mq('all and (max-width: 640px)')){$(".imgswapDesktop").each(function(){imgSrc=$(this).attr("mobile-img");$(this).attr("src",imgSrc);});}
else if(Modernizr.mq('all and (min-width: 641px) and (max-width: 1023px)')){$(".imgswapDesktop").each(function(){imgSrc=$(this).attr("tablet-img");$(this).attr("src",imgSrc);});}
else{$(".imgswapDesktop").each(function(){imgSrc=$(this).attr("desk-img");$(this).attr("src",imgSrc);});}
return;}
function imgSwapHiRes(){var imgSrc="";if(Modernizr.mq('all and (max-width: 1439px)')){$(".imgswapHiRes").each(function(){imgSrc=$(this).attr("normal-img");$(this).attr("src",imgSrc);});}
else{$(".imgswapHiRes").each(function(){imgSrc=$(this).attr("hiRes-img");$(this).attr("src",imgSrc);});}
return;}
function hamburgerAnimate(){if(Modernizr.mq('all and (max-width: 1023px)')){$(".navbar-toggle").off('click').on("click",function(){$(this).toggleClass("active");if(sfIndicator=='FP'){$el=$(this).siblings('.navbar-brand');}else{$el=$(this).next('span');}
$(this).parents('#main-top-header').siblings(".main-navigation").toggleClass("mmactive");if(sfIndicator=='AG'){$(this).hasClass("active")?$el.text("Close"):$el.text("Menu");}else{$(this).hasClass("active")?$el.text("CLOSE"):$el.text("MENU");}});$('#main-top-header >.headerLink').removeAttr('style');}
else{$('#main-top-header >.headerLink').css('right',$('#keywordsearch').outerWidth(true)+30);}}
function subbrandLogoSwap(){$el=$(".sub-brand-logo");$el2=$("#ProductGallery .caption");if(Modernizr.mq('all and (max-width: 640px)')){$el.insertAfter("#main-top-header .fp-logo");var text=$el2.data("touch");$el2.text(text);}
else{$el.insertBefore(".main-navigation");$el.insertBefore(".ecd-navigation");var text=$el2.data("desktop");$el2.text(text);}
$el3=$('.shakira .share-news .right-bottom');if(Modernizr.mq('all and (min-width: 1024px)')){$el3.insertAfter('.shakira .share-news .right-promo-info');}else{$el3.insertAfter('.shakira .share-news .promo-wrapper');}}
dojo.addOnLoad(function(){$(window).scroll(function(){var scroll=$(window).scrollTop();if(scroll>=100&&Modernizr.mq('all and (max-width: 640px)')){if($(".main-navigation .navbar-collapse").hasClass('in')||$(".ga-topNavigation .navbar-collapse").hasClass('in')){$("header").removeClass("fixed-header");}
else{$("header").addClass("fixed-header");}}
else{$("header").removeClass("fixed-header");}})});function swaptoMobile(){$el=$(".research-wrapper .testToysRtCnt");$el2=$(".research-wrapper .participateCnt .participateCnt2");$el3=$(".promo-1 .thomas-button");$el4=$(".promo-2 .thomas-button");if(Modernizr.mq('all and (max-width: 640px)')){$el.insertBefore(".research-wrapper .testToysLftCnt");$el2.insertBefore(".research-wrapper .participateCnt .participateCnt3");$el3.insertAfter(".promo-1 .tile-info");$el4.insertAfter(".promo-2 .tile-info");}
else{$el.insertAfter(".research-wrapper .testToysLftCnt");$el2.insertAfter(".research-wrapper .participateCnt .participateCnt3");$el3.appendTo(".promo-1 .tile-info");$el4.appendTo(".promo-2 .tile-info");}}
function swaptoTablet(){$el=$("#product-detail-wrapper .share-info .middle");$el1=$(".testToysRtCnt img");if(Modernizr.mq('all and (min-width: 641px) and (max-width: 1023px)')){$el.insertAfter("#product-detail-wrapper .share-info .right");$el1.insertBefore(".testToysLftCnt .titleCnt");}
else{$el.insertBefore("#product-detail-wrapper .share-info .right");$(".testToysRtCnt .expertsImg").append($el1);}}
function scrollPane(){if($('.product-detail-container .product-fetaure .scroll-pane').length>0){$('.product-detail-container .product-fetaure .scroll-pane').jScrollPane({verticalDragMinHeight:120,verticalDragMaxHeight:120});}}
function footerAccordion(){$('.footer-tiles .accordion-toggle h5').on('click',function(){$(this).toggleClass("shown");});}
function ProductDetailAccordion(){$('#product-detail-wrapper .product-fetaure li h2').on('click',function(){$('#product-detail-wrapper .product-fetaure li h2').not(this).removeClass('shown');$(this).toggleClass("shown");});}
dojo.addOnLoad(function(){if($('#main-top-header .input-search,.search-result-wrapper .input-search').length>0){$('#main-top-header .input-search,.search-result-wrapper .input-search').typeahead({hint:true,highlight:true,minLength:2},{name:'states',source:function(query,sync,async){$.get(localInfo+'/Search/GetSearchSuggestions',{q:query,limit:10},function(data){var $results=[];data=data.split('\n');$.each(data,function(i,resultText){$results.push(resultText.split(',')[1]);});async($results.filter(Boolean));});},templates:{suggestion:function(data){return"<div onclick = \"searchPage('"+data+"')\">"+data+"</div>";}}});}});function searchPage(data){window.location.href=localInfo+"/search/index.html?Ntt="+data;}
dojo.addOnLoad(function(){$("#main-top-header .input-search,.search-result-wrapper .input-search").on('keyup keypress',function(e){if(e.which==13){var data=$(this).val();window.location.href=localInfo+"/search/index.html?Ntt="+data;}});});function moveFAPBanner(){if(Modernizr.mq('all and (min-width: 1024px)')){var $dropdownAccordion=$('.filter-wrapper .dropdown.dropdown-accordion'),$dropdownPanel=$('.filter-wrapper .dropdown-menu.panel-group');if($dropdownAccordion.length){$dropdownAccordion.removeAttr('data-accordion').addClass('filterNav').removeClass('dropdown dropdown-accordion');}
if($dropdownPanel.length){$dropdownPanel.addClass('filterNav-list').removeClass('dropdown-menu panel-group').find('h5').removeAttr('data-target data-toggle data-parent class');$dropdownPanel.find('ul').removeClass('collapse panel-collapse').css('height','auto');$dropdownPanel.find('li').removeAttr('role');}
$('.findProduct .content-filter .banner-wrapper').insertBefore('.findProduct .result-wrapper');}
else{var $dropdownAccordion=$('.filter-wrapper .filterNav'),$dropdownPanel=$('.filter-wrapper .filterNav-list');if($dropdownAccordion.length){$dropdownAccordion.attr('data-accordion','#accordion').addClass('dropdown dropdown-accordion').removeClass('filterNav');}
if($dropdownPanel.length){$dropdownPanel.addClass('dropdown-menu panel-group').removeClass('filterNav-list').find('h5').addClass('panel-heading').attr('data-parent','#accordion').attr('data-toggle','collapse').each(function(){$(this).attr('data-target','#'+$(this).next().attr('id'));});$dropdownPanel.find('ul').addClass('collapse panel-collapse');$dropdownPanel.find('li').attr('role','presentation');}
$('.findProduct .content-result .banner-wrapper').insertBefore('.findProduct .filter-wrapper');if(Modernizr.mq('all and (max-width: 640px)')){$('.findProduct .title-section .title-info').insertBefore('.findProduct .banner-wrapper');}
else{$('.findProduct .title-info').insertBefore('.findProduct .title-section .number-info');}}}
dojo.addOnLoad(function(){$(document).on("click","#ProductThumbGallery2 .item",function(){var $el=$($('#ProductGallery2 .owl-stage-outer .owl-item')[$('#ProductThumbGallery2 .owl-item.synced').index()]).find("audio");if($(this).hasClass('audio')){$el.trigger("play");}
else{$('audio').each(function(){this.pause();});}});$(document).on("click","#ProductThumbGallery .item",function(){var $el=$($('#ProductGallery .owl-stage-outer .owl-item')[$('#ProductThumbGallery .owl-item.synced').index()]).find("audio");if($(this).hasClass('audio')){$el.trigger("play");}
else{$('audio').each(function(){this.pause();});}});dojo.subscribe("ajaxRequestCompleted",initEllipsis);dojo.subscribe("ajaxRequestCompleted",fakeFocus);dojo.subscribe("ajaxRequestCompleted",fixHashLinks);dojo.subscribe("ajaxRequestCompleted",float_labels);dojo.subscribe("ajaxRequestCompleted",updateMyOrderTotals);});function initEllipsis(){$(".dot-ellipsis").trigger("destroy.dot").dotdotdot({watch:window});}
function fakeFocus(){$("a,input,select,label,textarea").on('keyup.tab',function(){var t=$(this);$('.focus-ring').each(function(){$(this).removeClass('focus-ring');});t.addClass('focus-ring');});}
function fixHashLinks(){$('a[href="#"]').on('mousedown',function(e){MessageHelper.resetErrors();e.preventDefault();});}
function float_labels(){$('select:not(.nolabel),input[type="text"]:not(.nolabel),input[type="password"]:not(.nolabel),input[type="email"]:not(.nolabel),input[type="tel"]:not(.nolabel),textarea').keyup(function(){$(this).trigger("change");});$('select:not(.nolabel),input[type="text"]:not(.nolabel),input[type="password"]:not(.nolabel),input[type="email"]:not(.nolabel),input[type="tel"]:not(.nolabel),textarea').change(function(){if($(this).val()!=""){$(this).addClass('filled');$('label[for="'+$(this).attr('id')+'"]').addClass('filled');$('label[for="'+$(this).attr('id')+'"]').parent().parent().addClass('filled');}else{$(this).removeClass('filled');$('label[for="'+$(this).attr('id')+'"]').removeClass('filled');$('label[for="'+$(this).attr('id')+'"]').parent().parent().removeClass('filled');}});$('select:not(.nolabel),input[type="text"]:not(.nolabel),input[type="password"]:not(.nolabel),input[type="email"]:not(.nolabel),input[type="tel"]:not(.nolabel),textarea').each(function(){if($(this).val()!=""){$(this).addClass('filled');$('label[for="'+$(this).attr('id')+'"]').addClass('filled');$('label[for="'+$(this).attr('id')+'"]').parent().parent().addClass('filled');}else{$(this).removeClass('filled');$('label[for="'+$(this).attr('id')+'"]').removeClass('filled');$('label[for="'+$(this).attr('id')+'"]').parent().parent().removeClass('filled');}});}
function updateMyOrderTotals(){$('#myorder').collapse('show');}
function calcStopAffix(){var headerWrapper=Math.floor($('#headerWrapper').outerHeight(true)),productInfo=Math.floor($("#product-detail-content").outerHeight(true)),documentHeight=Math.floor($(document).innerHeight()),stopAffix=((documentHeight-(headerWrapper+productInfo))+60);return stopAffix;}
function resetStopAffix(){if($('#floatingProductInfo').length&&window.innerWidth>=1024&&($('#floatingMyOrder').data('bs.affix')!=undefined)||$('#floatingProductInfo').data('bs.affix')!=undefined){$('#floatingProductInfo').data('bs.affix').options.offset.bottom=calcStopAffix();$('#floatingProductInfo').affix('checkPosition');}}
dojo.addOnLoad(function(){$(".collapse").each(function(){$(this).on("shown.bs.collapse",initAffix);$(this).on("hidden.bs.collapse",initAffix);});});function initAffix(){if(window.innerWidth>=1024){scrollTo(0,pageYOffset-1);var mo=$('#floatingMyOrder'),pi=$('#floatingProductInfo'),bi=$("#floatingBundleInfo"),bis=$("#floatingBundleInfoSection");if(pi.length>0){var stopAffix=calcStopAffix();pi.affix({offset:{top:Math.floor(pi.position().top-1),bottom:function(){return(this.bottom=stopAffix)}}});pi.width(pi.parent().width());pi.attr("data-affixed","true");hasAffixed=true;}else if(mo.length>0){mo.affix({offset:{top:Math.floor(mo.position().top-1),bottom:function(){maximumHeight=0;$("footer").each(function(i){if(maximumHeight<$(this).outerHeight(true))maximumHeight=$(this).outerHeight(true);});if(maximumHeight!=0){return(this.bottom=maximumHeight)}}}});mo.width(mo.parent().width());mo.attr("data-affixed","true");hasAffixed=true;}else if(bi.length>0){productDisplayJS.waitForElement('.rsMobileZoomContainer img',function(){bis.css({"minHeight":Math.floor(bi.height()-$(".widget_product_image_viewer").height())});bi.css({"position":"absolute"});});}}}
function fixAffix(){var affix=$('[data-affixed="true"]');if(affix.length>0){affix.width(affix.parent().width());}}
function showBumper(){try{if(window.sfIndicator!='BA'&&window.sfIndicator!='HW'){return;}
$('#bumperPop img:not([src])').each(function(){$(this).attr('src',$(this).attr('data-src'));});var hasClosed=false,cookie=null;require(["dojo/cookie"],function(dojoCookie){cookie=dojoCookie;});hasClosed=cookie("bumperPopClosed");if(window.location.pathname!='/shop'||hasClosed=="true"||document.referrer.indexOf(location.hostname)>0){console.log("ignoring bumper modal",document.referrer,location.hostname);window.onload=function(){openEmailSignup();}
return;}
$('#bumperPop').on('show.bs.modal',function(e){$('.modal-dialog').css({'width':(window.innerWidth>=1024)?'70%':'100%'});window.fp.playerModalOpened=true;reposition();});$('#bumperPop').on('hide.bs.modal',function(e){cookie("bumperPopClosed","true",{expires:(new Date().setHours(1))});window.utag=void(0);window.utag_cfg_ovrd.noload=void(0);a=tealiumURL;b=document;c='script';d=b.createElement(c);d.src=a;d.type='text/java'+c;d.async=true;a=b.getElementsByTagName(c)[0];a.parentNode.insertBefore(d,a);openEmailSignup();});$(window).resize(function(){$('.modal-dialog').css({'width':(window.innerWidth>=1024)?'70%':'100%'});reposition();});$("#bumperPop").on("shown.bs.modal",function(){var f=$(this).find("area").focus();});$('#bumperPop').modal({backdrop:'static',keyboard:false});}catch(e){console.log(e);}}
function initExclusives(){if(window.innerHeight<=1024){$(".exclusives.carousel").swipe({swipe:function(event,direction,distance,duration,fingerCount,fingerData){if(direction=='left')$(this).carousel('next');if(direction=='right')$(this).carousel('prev');},allowPageScroll:"vertical"});}}
function initMyOrder(){$('[href="#myorder"]').off('click');$("#myorder").off('show.bs.collapse');$("#myorder").off('hide.bs.collapse');if(window.innerWidth<1024){$("#myorder").on('show.bs.collapse',function(){$("#mobile_order_total").html("");});$("#myorder").on('hide.bs.collapse',function(){var order_total_markup=$("#mobile_order_total");if(order_total_markup.is(':empty')){var orderDetails=$("#total_breakdown").clone();console.log(orderDetails);orderDetails.appendTo(order_total_markup);}});$("#collapse-my-order-reward,#collapse-my-order-promo").on('hide.bs.collapse',function(e){$("#mobile_order_total").html("");e.stopPropagation();});}else{$('[href="#myorder"]').on('click',function(){return false;});}
$('#myorder').collapse('show');}
function errorMessageDisplay(errorMsg){try{if(errorMsg.message.indexOf("user.mattel.com")<0){MessageHelper.displayStatusMessage(errorMsg)}}catch(e){}}
function validateEmail(emailId){MessageHelper.setMessage("ERROR_EmailEmpty",storeNLS['ERROR_EmailEmpty']);MessageHelper.setMessage("ERROR_INVALIDEMAILFORMAT",storeNLS['ERROR_INVALIDEMAILFORMAT']);MessageHelper.setMessage("ERROR_EmailTooLong",storeNLS['ERROR_EmailTooLong']);reWhiteSpace=new RegExp(/^\s+$/);emailId.value=trim(emailId.value);if(emailId.value==""||reWhiteSpace.test(emailId.value)){MessageHelper.formErrorHandleClient(emailId.id,MessageHelper.messages["ERROR_EmailEmpty"]);return false;}
else if(!MessageHelper.isValidUTF8length(emailId.value,256)){MessageHelper.formErrorHandleClient(emailId.id,MessageHelper.messages["ERROR_EmailTooLong"]);return false;}
else if(!MessageHelper.isValidEmail(emailId.value)){MessageHelper.formErrorHandleClient(emailId.id,MessageHelper.messages["ERROR_INVALIDEMAILFORMAT"]);return false;}
return true;}
function emailSignup(){try{var email=dojo.byId("emailSignupNewsletterEmail");if(email!=null&&validateEmail(email)){client.renderSignup(email.value)}}catch(e){console.log(e);}}
function collectorsEmailsignUp(siteId){var emailId=dojo.byId("collectorsEmailSignupNewsletterEmail");if(emailId!=null&&validateEmail(emailId)){if(siteId!=null&&siteId!='')
client.SaveEmailSignup(emailId.value,siteId);else
client.SaveEmailSignup(emailId.value);}}
function initEspots(){$('img[usemap]').each(function(){$(this).rwdImageMaps();});if(navigator.userAgent.match(/(iPod|iPhone|iPad)/i)){$('.showIOS').show();}
else if(navigator.userAgent.match(/(kindle)/i)){$('.showKindle').show();}
else if(navigator.userAgent.match(/(android)/i)){$('.showAndroid').show();}
var espotCarousels=[],espotCarouselOptions={aspot:{autoplay:true,autoplayTimeout:4000,autoplaySpeed:500,autoplayHoverPause:true,loop:true,lazyLoad:false,touchDrag:false,responsive:{0:{items:1,loop:true}}},brand:{autoplay:false,autoplayTimeout:4000,autoplaySpeed:500,autoplayHoverPause:true,lazyLoad:false,loop:true,responsive:{0:{items:1,loop:true},768:{items:2,loop:true},1024:{items:4,loop:true},1280:{items:5,loop:true}}}};$('[class*="-a-spot-carousel"]').each(function(index){var _context=$(this),_carousel=$(".owl-carousel",_context).owlCarousel(espotCarouselOptions.aspot);$('.next',_context).click(function(){_carousel.trigger('next.owl');});$('.prev',_context).click(function(){_carousel.trigger('prev.owl');});if(_context.hasClass("mobile")){espotCarousels.push({"mobile":_carousel});}else{espotCarousels.push({"desktop":_carousel});}});$('[class*="-brand-carousel"]').each(function(index){var _context=$(this),_carousel=$(".owl-carousel",_context).owlCarousel(espotCarouselOptions.brand);$('.next',_context).click(function(){_carousel.trigger('next.owl');});$('.prev',_context).click(function(){_carousel.trigger('prev.owl');});if(_context.hasClass("mobile")){espotCarousels.push({"mobile":_carousel});}else{espotCarousels.push({"desktop":_carousel});}});$(".barbie-home .youCanBeAnything .menu li > a").click(function(){var selected=$(this).attr("href"),models=$(".barbie-home .youCanBeAnything .models");try{models.each(function(index){$(this).fadeOut(200);if((index+1)===models.length){$(selected+"_image").fadeIn();}});}catch(e){console.debug(e);}});}
dojo.addOnLoad(function(){$(window).on("orientationchange",function(){setTimeout(fixMenu,500);});});function fixMenu(){$(".dropdown-menu li a").off('click');$(".dropdown-menu li a").on('click',function(){var selText=$(this).text();$(this).parents('.dropdown').find('.dropdown-toggle span.data').html(selText);});if(sfIndicator=='FP'){$(".second-level-menus .subMenus-list").removeClass('active').removeAttr('style');$(".second-level-menus .subMenus-list ul").removeAttr('style');$("#main-nav-list").removeClass("mm-active");$("#main-nav-list >li").removeAttr('style');$('#main-nav-list>li>a').each(function(){$(this).removeAttr('style');$(this).attr('aria-expanded','false');$(this).collapse('hide');$(this).parent().find('.second-level-menus').removeClass('in');});$(".second-level-menus .subMenus-list .title").off('mouseover mousedown click');$("#parenting-subMenus .title-cat").off('click');$("#main-nav-list>li").off("mouseenter mouseleave");$("#main-nav-list>li>a").off("keyup.tab blur mousedown click");$("#main-nav-list>li>a>i").off("click");if(!Modernizr.touch&&window.innerWidth>=1024){$('#main-nav-list>li>a').each(function(){$(this).removeAttr('data-toggle');});$(".second-level-menus .subMenus-list.list1").addClass('active');$(".second-level-menus .subMenus-list .title").on('keyup.tab mouseover',function(e){$(".second-level-menus .subMenus-list.active").removeClass("active");$(this).parent().toggleClass('active');});$("#main-nav-list>li").on('mouseenter',function(e){$(".second-level-menus",this).addClass('in');setTimeout(function(){$("#main-nav-list").addClass("mm-active")},150);});$("#main-nav-list>li").on('mouseleave',function(e){$("#main-nav-list").removeClass("mm-active");$(".second-level-menus",this).removeClass('in');});$("#main-nav-list>li>a").on('keyup.tab',function(e){if(e.which==9){$("#main-nav-list").removeClass("mm-active");$(".second-level-menus").removeClass('in');$(this).next().css({"transformOrigin":"top","transform":"scale(1, 1)","transition":"all 0.45s 0.1s"});$(".second-level-menus",$(this).next()).addClass('in');$(this).parents("li").trigger("mouseover");setTimeout(function(){$("#main-nav-list").addClass("mm-active")},150);}});}else if(window.innerWidth>=1024){$(".second-level-menus .subMenus-list.list1").addClass('active');$(".second-level-menus .subMenus-list .title").on('mousedown',function(e){$(".second-level-menus .subMenus-list.active").removeClass("active");$(this).parent().toggleClass('active');e.preventDefault();});$("#main-nav-list>li>a").on("blur",function(e){$('#main-nav-list>li>a').each(function(){$(this).removeAttr('style');$(this).attr('aria-expanded','false');$(this).collapse('hide');$(this).parent().find('.second-level-menus').removeClass('in');});});$("#main-nav-list>li>a").on("mousedown",function(e){console.log(e);if($(this).attr("aria-expanded")=="true"){e.preventDefault();e.stopPropagation();location.href=$(this).attr("href");}else{var anchors=$('#main-nav-list>li>a').not(this);anchors.collapse('hide');anchors.attr('aria-expanded','false');anchors.parent().find('.second-level-menus').removeClass('in');}});}else{$(".second-level-menus .subMenus-list .title").on('click',function(e){$(this).parent().toggleClass('active');$(this).parent().find('ul').toggle();$(".second-level-menus").find('div.subMenus-list').not($(this).parent().show()).toggle(300);$("#main-nav-list").find('>li').not($(this).parent().parent().parent().parent().show()).toggle(300);$(this).parent().parent().parent().prev().toggle(300);});$("#parenting-subMenus .title-cat").on('click',function(e){$(this).parent().toggleClass('opened');$(this).toggleClass('active');$(this).next().toggle();$("#parenting-subMenus").find('div.title-cat').not($(this).show()).toggle(300);$("#main-nav-list").find('>li').not($(this).parent().parent().parent().show()).toggle(300);$(this).parent().parent().prev().toggle(300);});$("#main-nav-list>li>a>i").on("click",function(e){e.preventDefault();e.stopPropagation();$(this).parent().trigger("click");});$("#main-nav-list>li>a").on("click",function(e){if($(this).attr("aria-expanded")=="true"&&typeof e.isTrigger=="undefined"){e.preventDefault();e.stopPropagation();location.href=$(this).attr("href");}});}}else{$("header .topLevel .dropdown").removeClass("open");$("header .topLevel .dropdown > a > i").off('click');$("header .topLevel .dropdown > a").off('click');$("header .topLevel > li > a").off('focus');$("header .topLevel .dropdown > a > i").on('click',function(e){e.stopPropagation();e.preventDefault();$(this).parents(".dropdown").toggleClass("open");});$("header .topLevel .dropdown > a").on('click',function(e){if(window.innerWidth<=1024){e.stopPropagation();e.preventDefault();if($(this).parents(".dropdown").hasClass("open")){location.href=$(this).attr("href");}else{$("header .topLevel .dropdown").removeClass("open");$(this).parents(".dropdown").addClass("open");}}});if(!Modernizr.touch){$("header .topLevel > li > a").on('focus',function(e){$(this).parents(".topLevel").find(".dropdown.open").removeClass("open");$(this).parent().addClass("open");});}}}
function submitCSForm(){$('.emailError').remove();var re=/^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;var validated=true;if(!re.test($('#custSer_email').val())){validated=false;$("#contactUsForm button[type=Submit]").before('<div class="emailError"><b>Please enter a valid e-mail address.</b></div>')}
if($('#custSer_topic').val()==""){validated=false;$("#contactUsForm button[type=Submit]").before('<div class="emailError"><b>Please select a topic.</b></div>')}
if($('#custSer_comments').val()==""){validated=false;$("#contactUsForm button[type=Submit]").before('<div class="emailError"><b>Please enter a message.</b></div>')}
if($('#custSer_fName').val()==""){validated=false;$("#contactUsForm button[type=Submit]").before('<div class="emailError"><b>Please enter First Name.</b></div>')}
if($('#custSer_lName').val()==""){validated=false;$("#contactUsForm button[type=Submit]").before('<div class="emailError"><b>Please enter Last Name.</b></div>')}
if($('#custSer_address').val()==""){validated=false;$("#contactUsForm button[type=Submit]").before('<div class="emailError"><b>Please enter an address.</b></div>')}
if($('#custSer_phone').val()==""){validated=false;$("#contactUsForm button[type=Submit]").before('<div class="emailError"><b>Please enter a phone number.</b></div>')}
if(validated){var msg="First Name: "+$('#custSer_fName').val()+"\n";msg=msg+"Last Name: "+$('#custSer_lName').val()+"\n";msg=msg+"Address: "+$('#custSer_address').val()+"\n";msg=msg+"Phone#: "+$('#custSer_phone').val()+"\n";msg=msg+"Comments: "+$('#custSer_comments').val()+"\n";$.post("/webapp/wcs/stores/servlet/ContactUsServiceCmd",{storeId:"10151",catalogId:$('[name="catalogId"]').val(),langId:"-1",emailSubject:$('#custSer_topic').val(),msgContent:msg,userEmail:$('#custSer_email').val(),requesttype:"ajax"}).fail(function(){$("#contactUsForm button[type=Submit]").before('<div class="emailError"><b>Sorry, there has been an error sending your message.  Please try again.</b></div>')}).done(function(){$("#contactUsForm").html("<p><b>Thank you, your message has been submitted</b></p>");})}}
function GetStarted(){$('#emailSignupNewsletterEmail').val($('#emailMobile').val());emailSignup();}
var Mattel=Mattel||{Utils:{fixImgAspectRatio:function(){$('.aspectRatioFix').each(function(){$(this).load(function(){var orgImgHeight=$(this).height();var orgImgWidth=$(this).width();var desImgHeight=$(this).attr('data-img-height');var desImgWidth=$(this).attr('data-img-width');if(typeof desImgHeight!=undefined&&typeof desImgWidth!=undefined){desImgHeight=desImgHeight.replace('px','');desImgWidth=desImgWidth.replace('px','');var newHeight=desImgHeight;var newWidth=desImgWidth;if(orgImgHeight>=orgImgWidth){newHeight=desImgHeight;newWidth=Mattel.Utils.getWidth(newHeight,{height:orgImgHeight,width:orgImgWidth});}else{newWidth=desImgWidth;newHeight=Mattel.Utils.getHeight(newWidth,{height:orgImgHeight,width:orgImgWidth});}
this.height=newHeight;this.width=newWidth;}});});},log:function(){console.debug(arguments);},cachedScript:function(url,options){options=$.extend(options||{},{dataType:"script",cache:true,asynch:true,timeout:3000,url:url});return $.ajax(options);},validateJSVar:function(variable){if(variable==null||$.trim(variable)==''){return null;}
if(typeof variable==Array){return variable.slice(0);}
return variable;},getWidth:function(newHeight,dimensions){if(dimensions.height==0)return newHeight;var aspectRatio=(dimensions.width/dimensions.height);return Math.ceil(newHeight*aspectRatio);},getHeight:function(newWidth,dimensions){if(dimensions.width==0)return newWidth;var aspectRatio=(dimensions.height/dimensions.width);return Math.ceil(newWidth*aspectRatio);},getSize:function(){if(this.getUserDevice()=='mobile')
{return'small';}
if(this.getUserDevice()=='tablet'||this.getUserDevice()=='desktop')
{return'medium';}
return'large'},getReferringURL:function(){var documentReferer=document.referrer;if(null!=documentReferer&&$.trim(documentReferer)!=''){documentReferer=documentReferer.substring(0,documentReferer.indexOf('?'));return documentReferer;}else{return this.getCurrentURL();}},getCurrentURL:function(){var currentPageURL=location.href;currentPageURL=currentPageURL.substring(0,currentPageURL.indexOf('?'));return currentPageURL;},getJSVariable:function(variable){return(typeof variable!='undefined')?variable:'';},getUserDevice:function(){var ua=navigator.userAgent;return(Mattel.storeName=="HWCStore")?'desktop':ua.match(/GoogleTV|SmartTV|Internet.TV|NetCast|NETTV|AppleTV|boxee|Kylo|Roku|DLNADOC|CE\-HTML/i)?'tv':ua.match(/Xbox|PLAYSTATION.3|Wii/i)?'tv':ua.match(/iPad/i)||ua.match(/tablet/i)&&!ua.match(/RX-34/i)||ua.match(/FOLIO/i)?'tablet':ua.match(/Linux/i)&&ua.match(/Android/i)&&!ua.match(/Fennec|mobi|HTC.Magic|HTCX06HT|Nexus.One|SC-02B|fone.945/i)?'tablet':ua.match(/Kindle/i)||ua.match(/Mac.OS/i)&&ua.match(/Silk/i)?'tablet':ua.match(/GT-P10|SC-01C|SHW-M180S|SGH-T849|SCH-I800|SHW-M180L|SPH-P100|SGH-I987|zt180|HTC(.Flyer|\_Flyer)|Sprint.ATP51|ViewPad7|pandigital(sprnova|nova)|Ideos.S7|Dell.Streak.7|Advent.Vega|A101IT|A70BHT|MID7015|Next2|nook/i)||ua.match(/MB511/i)&&ua.match(/RUTEM/i)?'tablet':ua.match(/BOLT|Fennec|Iris|Maemo|Minimo|Mobi|mowser|NetFront|Novarra|Prism|RX-34|Skyfire|Tear|XV6875|XV6975|Google.Wireless.Transcoder/i)?'mobile':ua.match(/Opera/i)&&ua.match(/Windows.NT.5/i)&&ua.match(/HTC|Xda|Mini|Vario|SAMSUNG\-GT\-i8000|SAMSUNG\-SGH\-i9/i)?'mobile':ua.match(/Windows.(NT|XP|ME|9)/)&&!ua.match(/Phone/i)||ua.match(/Win(9|.9|NT)/i)?'desktop':ua.match(/Macintosh|PowerPC/i)&&!ua.match(/Silk/i)?'desktop':ua.match(/Linux/i)&&ua.match(/X11/i)?'desktop':ua.match(/Solaris|SunOS|BSD/i)?'desktop':ua.match(/Bot|Crawler|Spider|Yahoo|ia_archiver|Covario-IDS|findlinks|DataparkSearch|larbin|Mediapartners-Google|NG-Search|Snappy|Teoma|Jeeves|TinEye/i)&&!ua.match(/Mobile/i)?'desktop':'mobile'}}}
if(window.location.pathname.indexOf("where-to-buy/")>0){var SKU;if(getQueryVariable("ps-sku")==undefined){var re=/.*\/.*-([a-z0-9]{4,5})(-\d)?$/;var matches=re.exec(window.location.pathname);SKU=matches[1].toUpperCase();}
else{SKU=getQueryVariable("ps-sku");}
if(SKU.length<5){SKU="0".repeat(5-SKU.length)+SKU;}
var productLink="/shop"+window.location.pathname.substr(window.location.pathname.indexOf("/en-us/")).replace(/\/[a-z]{2}-where-to-buy/i,"");var canonicalLink=window.location.pathname.replace(/(.*)(\/[a-z]{2,3}-where-to-buy)([^?]*)/i,"$1$3");var widget=document.getElementsByClassName("ps-widget")[0];widget.setAttribute("ps-sku",SKU);var meta1=document.createElement("meta");meta1.setAttribute("name","ps-account");meta1.setAttribute("content","1427");document.getElementsByTagName('head')[0].appendChild(meta1);var meta2=document.createElement("meta");meta2.setAttribute("name","ps-country");meta2.setAttribute("content","US");document.getElementsByTagName('head')[0].appendChild(meta2);var meta3=document.createElement("meta");meta3.setAttribute("name","ps-language");meta3.setAttribute("content","en");document.getElementsByTagName('head')[0].appendChild(meta3);var scriptTag=document.createElement('script');firstScriptTag=document.getElementsByTagName('script')[0];scriptTag.src='//cdn.pricespider.com/1/lib/ps-widget.js';firstScriptTag.parentNode.insertBefore(scriptTag,firstScriptTag);document.getElementsByClassName("right")[0].className="acol12 right col12 ccol12";var link=document.createElement('link');link.setAttribute('rel','canonical');link.setAttribute('href',location.protocol+'//'+location.host+canonicalLink);document.head.appendChild(link);var cartTotal=0.00;var cartCounter=0;var cartCurrency="USD";var cartData=getCookie("WC_CartTotal_"+getCookie("WC_CartOrderId_"+getQueryVariable("ps-storeId")));if(cartData!=undefined){cartData=cartData.split(";");cartTotal=cartData[1];cartCounter=cartData[0];cartCurrency=cartData[2];}
utag_data={page_id:getQueryVariable("ps-sfIndicator")+':US:PriceSpiderWTB',page_name:getQueryVariable("ps-sfIndicator")+':US:PriceSpiderWTB',page_type:"Product Index",platform:"Mobile",site_section:'shop',site_type:'commerce',site_region:'US',site_currency:cartCurrency,product_id:[getQueryVariable("ps-productId")],product_sku:[SKU],product_name:[getQueryVariable("ps-name")],product_brand:[getQueryVariable("ps-sfIndicator")],product_url:[productLink],product_pricing_indicator:[cartCurrency],product_category:['Shop'],store_id:getQueryVariable("ps-storeId"),customer_id:'-1002',customer_email:'',cart_total_items:cartCounter,cart_total_value:cartTotal,event_id:getQueryVariable("ps-sfIndicator")+':US:PriceSpiderWTB : '+SKU,event_category:"Product Detail"}}
function getQueryVariable(variable){var query=window.location.search.substring(1);var vars=query.split('&');for(var i=0;i<vars.length;i++){var pair=vars[i].split('=');if(decodeURIComponent(pair[0])==variable){return decodeURIComponent(pair[1]);}}
console.log('Query variable %s not found',variable);}
var el=document.getElementsByTagName("HTML")[0];var environmentClass="";if(location.host.indexOf("corp.mattel.com")>0){environmentClass="Env"+location.host.substr(0,location.host.indexOf(".")).toUpperCase();}
else{environmentClass="EnvPROD"}
if(el.classList)
el.classList.add(environmentClass);else
el.className+=' '+environmentClass;el.className+=' '+window.location.pathname.substr(window.location.pathname.lastIndexOf("/")+1);if(getCookie("comiccon1")>0){var element=document.getElementById("WC_CheckoutPayInStore_div_1");if(element!=null){var elementChild=element.getElementsByClassName("shipping");element.removeChild(elementChild[0]);}}
dojo.addOnLoad(function(){$('#WCSGenericEmailForm').submit(function(event){event.preventDefault();var emailForm;if(emailForm=document.getElementById("WCSGenericEmailForm")){var emailJson={};var temp;var error="";if(temp=emailForm.querySelector("[name=email]")){emailJson.EmailAddress=temp.value;}
if(emailJson.EmailAddress==undefined||emailJson.EmailAddress==""){if($('#WCSGenericEmailEmailError').length>0){error="<br>"+$('#WCSGenericEmailEmailError').val();}
else{error="<br>Please enter a valid e-mail address";}}
emailJson.storeId=document.getElementById("searchBox").querySelector("[name=storeId]").value;emailJson.CatalogId=document.getElementById("searchBox").querySelector("[name=catalogId]").value;emailJson.createPartyNow="true";emailJson.addAllContPref="true";var children;if(children=emailForm.querySelectorAll("[name*=child_birthdate_year_]")){emailJson.Children=[];for(i=1;i<=children.length;i++){emailJson.Children[i-1]={};if(temp=emailForm.querySelector("[name=child_birthdate_gender_"+i+"]")){emailJson.Children[i-1].Gender=temp.value;}
var day=emailForm.querySelector("[name=child_birthdate_day_"+i+"]");var month=emailForm.querySelector("[name=child_birthdate_month_"+i+"]");var year=emailForm.querySelector("[name=child_birthdate_year_"+i+"]");if(day==undefined||month==undefined||year==undefined){if($('#WCSGenericEmailBirthdateError').length>0){error=error.concat("<br>"+$('#WCSGenericEmailBirthdateError').val());}
else{error=error.concat("<br>Please enter a valid birthdate");}
i=children.length+1;}
else if(day.value==""||month.value==""||year.value==""){if($('#WCSGenericEmailBirthdateError').length>0){error=error.concat("<br>"+$('#WCSGenericEmailBirthdateError').val());}
else{error=error.concat("<br>Please enter a valid birthdate");}
i=children.length+1;}
else{day=parseInt(day.value);month=parseInt(month.value);year=parseInt(year.value);emailJson.Children[i-1].BirthDate=((month<10)?"0":"")+month+"/"+((day<10)?"0":"")+day+"/"+((year<20)?year+2000:((year<100)?year+1900:year));}
if(temp=emailForm.querySelector("[name=child_birthdate_relationship_"+i+"]")){emailJson.Children[i-1].RelationShip=temp.value;}}}}
if(error!=""){$('#WCSGenericEmailForm .error').remove();$('#WCSGenericEmailForm').append('<p class="error">'+error+'</p');}
else{$.ajax({url:"/webapp/wcs/stores/servlet/en-us/SubscribeToEmail?json="+JSON.stringify(emailJson),type:"GET",processData:false,success:function(){if($('#WCSGenericEmailThankYou').length>0){$('#WCSGenericEmailForm').html('<p class="done">'+$('#WCSGenericEmailThankYou').val()+'</p');}
else{$('#WCSGenericEmailForm').html('<p class="done">Thank you for your registration.</p');}
if(typeof(WCSGenericEmailSuccess)=="function"){WCSGenericEmailSuccess();}}});}});});function loadInstagram(userid,token){if($('.instagram-spot').length>0){var parseIGURL=function(url){var url=url||null,a=document.createElement("a");if(url){a.href=url;url=a.pathname.split("/");for(var x in url){if(url[x].indexOf("s")==0){url[x]="s480x480";}
if(url[x].indexOf("c")==0)url.splice(x,1);}
url=a.protocol+"//"+a.hostname+"/"+url.join("/");return url;}}
if(sfIndicator=='BA'){var num_photos=4,instagram_image='/wcsstore/MattelSAS/images/ba-instagram.png',instagram_link='https://www.instagram.com/Barbie/';}
if(sfIndicator=='HW'){var num_photos=4,instagram_image='/wcsstore/MattelSAS/images/hw-instagram.png',instagram_link='https://www.instagram.com/hotwheelsofficial/';}
$.ajax({url:'https://images.mattel.com/instagram/v1/users/'+userid+'/media/recent',dataType:'jsonp',type:'GET',cache:true,jsonpCallback:'instagramFeed',data:{access_token:token,count:num_photos,size:'t'},success:function(data){console.log(data);for(x in data.data){console.log(data.data[x]);$(".instagram-spot").append('<div class="insta-image-container"><a href="'+data.data[x].link+'" target="_blank"><div style="background-image: url(\''+parseIGURL(data.data[x].images.thumbnail.url)+'\');"></div></a></div>');}
$(".instagram-spot").append('<div class="insta-image-container"><a href="'+instagram_link+'"><div class="instagram-logo" style="background-image: url(\''+instagram_image+'\');"></div></a></div>');},error:function(data){console.log(data);}});}}
function InventoryStatusJS(storeParams,catEntryParams,physicalStores,productId){this.storeParams=storeParams;this.catEntryParams=catEntryParams;this.physicalStores=physicalStores;this.productId=productId;this.isFetchInventoryStatus=false;this.itemId=-1;this.isSwatchSelected=false;this.setCatEntry=function(catEntryId,productId){if(this.catEntryParams.type!="ItemBean"){dojo.style("InventoryStatus_Availability_Section_"+this.productId,"display","none");dojo.style("InventoryStatus_ShowLink_Section_"+this.productId,"display","block");if(catEntryId!=-1){this.itemId=catEntryId;this.checkAvailability(this.isFetchInventoryStatus);this.isFetchInventoryStatus=false;}}};this.restoreDefaultState=function(catEntryId,productId){if(catEntryId==null){dojo.style("InventoryStatus_Availability_Section_"+this.productId,"display","none");dojo.style("InventoryStatus_ShowLink_Section_"+this.productId,"display","block");}};this.checkAvailability=function(allowParallelCall){try{MessageHelper.hideAndClearMessage();}catch(e){console.log("Exception "+e);}
var params=this.setCommonParams();if(-1==this.itemId){MessageHelper.displayErrorMessage(storeNLS['ERR_RESOLVING_SKU']);return;}
params.itemId=this.itemId;dojo.style("InventoryStatus_ShowLink_Section_"+this.productId,"display","none");setCurrentId('progressbar_'+this.productId);if(!allowParallelCall){if(!submitRequest()){return;}}
cursor_wait();wc.service.invoke("getInventoryStatus",params);};this.toggleAddtoCartVisibility=function(action){var isAGStore=(sfIndicator==="AG")?true:false;if(isAGStore){var screenWidth=(window.innerWidth>0)?window.innerWidth:screen.width;if(screenWidth<1024){var addToCartButton=$(".hide_add_to_cart_button_mobile")||false;var hideOptionsButton=$(".hideOptions");if(addToCartButton){if(action="show"){hideOptionsButton.addClass("hide");addToCartButton.removeClass("hide");this.isSwatchSelected=true;}else{addToCartButton.addClass("hide");hideOptionsButton.removeClass("hide");this.isSwatchSelected=false;}}}}};this.populateInvDetails=function(serviceResponse,ioArgs){if(serviceResponse.onlineInventory){var inventoryStatus=serviceResponse.onlineInventory.invStatus;var backOrderedDate="";var backOrderDateMainToy="";var flag1=false;var flag=false;if(productDisplayJS.productId!=null&&productDisplayJS.productId!=undefined){this.productId=productDisplayJS.productId;}
var productIdMainToy=$("#productIdMainToy").val();var prodInvStatus=dojo.byId("InventoryStatus_Dispatch_Details_"+this.productId);if(serviceResponse.inStoreInventory.backorderDate!=null&&serviceResponse.inStoreInventory.backorderDate!=undefined&&serviceResponse.inStoreInventory.backorderDate!=""){var backOrderedDate=serviceResponse.inStoreInventory.backorderDate;}
if(typeof productIdMainToy!='undefined'&&productIdMainToy!=""){$("#InventoryStatus_Availability_Section_"+productIdMainToy).css("display","none");var backOrderDateTextMainToy=$("#InventoryStatus_Dispatch_Details_"+productIdMainToy).text();if(typeof productIdMainToy!='undefined'&&backOrderDateTextMainToy!=""){backOrderDateMainToy=backOrderDateTextMainToy.split("until")[1].trim();if(typeof backOrderDateMainToy!='undefined'&&backOrderDateMainToy!=""){flag1=true;}
var date1=new Date(backOrderDateMainToy);var date2=new Date(backOrderedDate);flag=this.comparedate(date1,date2);if(flag){backOrderedDate=backOrderDateMainToy;}}}
if(flag1&&inventoryStatus!='S'){dojo.html.set(dojo.byId("InventoryStatus_OnlineStatus_"+this.productId),"Backordered");}else{dojo.html.set(dojo.byId("InventoryStatus_OnlineStatus_"+this.productId),serviceResponse.onlineInventory.status);}
if(inventoryStatus=='B'&&(serviceResponse.inStoreInventory.preOrderFlag=='Y'||serviceResponse.inStoreInventory.preOrderFlag=='1')){if(prodInvStatus==null||prodInvStatus==undefined||prodInvStatus==''){var element="<span id='InventoryStatus_Dispatch_Details_"+this.productId+"' class='warehouse_dispatch_details'></span>";$("#InventoryStatus_Availability_Section_"+this.productId+" .sublist").append(element);dojo.html.set(dojo.byId("InventoryStatus_Dispatch_Details_"+this.productId),"AVAILABLE "+backOrderedDate);}else{dojo.html.set(dojo.byId("InventoryStatus_Dispatch_Details_"+this.productId),"AVAILABLE "+backOrderedDate);}}else if(inventoryStatus=='B'){if(prodInvStatus==null||prodInvStatus==undefined||prodInvStatus==''){var element="<span id='InventoryStatus_Dispatch_Details_"+this.productId+"' class='warehouse_dispatch_details'></span>";$("#InventoryStatus_Availability_Section_"+this.productId+" .sublist").append(element);dojo.html.set(dojo.byId("InventoryStatus_Dispatch_Details_"+this.productId)," UNTIL "+backOrderedDate);}else{dojo.html.set(dojo.byId("InventoryStatus_Dispatch_Details_"+this.productId)," UNTIL "+backOrderedDate);}}else if(flag1&&inventoryStatus!='S'){if(prodInvStatus!=null&&prodInvStatus!=undefined&&prodInvStatus!=''){$("#InventoryStatus_Dispatch_Details_"+this.productId).remove();var element="<span id='InventoryStatus_Dispatch_Details_"+this.productId+"' class='warehouse_dispatch_details'></span>";$("#InventoryStatus_Availability_Section_"+this.productId+" .sublist").append(element);dojo.html.set(dojo.byId("InventoryStatus_Dispatch_Details_"+this.productId)," UNTIL "+backOrderDateMainToy);}else{$("#InventoryStatus_Dispatch_Details_"+this.productId).remove();var element="<span id='InventoryStatus_Dispatch_Details_"+this.productId+"' class='warehouse_dispatch_details'></span>";$("#InventoryStatus_Availability_Section_"+this.productId+" .sublist").append(element);dojo.html.set(dojo.byId("InventoryStatus_Dispatch_Details_"+this.productId)," UNTIL "+backOrderDateMainToy);}}else{if(prodInvStatus!=null&&prodInvStatus!=undefined&&prodInvStatus!=''){dojo.html.set(dojo.byId("InventoryStatus_Dispatch_Details_"+this.productId));}}
if(sfIndicator!='AG'){if(inventoryStatus!='T'){if(prodInvStatus!=null&&prodInvStatus!=undefined&&prodInvStatus!='')
dojo.html.set(dojo.byId("InventoryStatus_Dispatch_Details_"+this.productId));}
else{if(prodInvStatus!=null&&prodInvStatus!=undefined&&prodInvStatus!='')
dojo.html.set(dojo.byId("InventoryStatus_Dispatch_Details_"+this.productId),":Get notified when this item is back in stock");}}
if(inventoryStatus){var notifyBtn=dojo.byId("notifyMe");var cartBtn=dojo.byId("add2CartBtn");if(cartBtn==null||cartBtn==undefined){cartBtn=$("a[id^='add2CartBtn']");if(cartBtn!=null){var cartBtnLength=cartBtn.length;if(cartBtnLength>1){addToBagId=$('a[id ^=add2CartBtn]a[id $='+this.productId+']');cartBtn=addToBagId[0];}else{cartBtn=cartBtn[0];}}
this.toggleAddtoCartVisibility("hide");}
if(cartBtn!=null){dojo.setStyle(cartBtn,"pointer-events","auto");}
if(inventoryStatus=='T'){if(notifyBtn!=null){dojo.setStyle(notifyBtn,"display","block");if(cartBtn!=null){dojo.setStyle(cartBtn,"pointer-events","none");dojo.addClass(cartBtn,"inactiveLink");}}else{if(cartBtn!=null){dojo.setStyle(cartBtn,"pointer-events","none");dojo.addClass(cartBtn,"inactiveLink");}}
this.toggleAddtoCartVisibility("hide");}
else if(inventoryStatus=='S'){if(notifyBtn!=null){dojo.setStyle(notifyBtn,"display","none");if(cartBtn==null){cartBtn=$("a[id^='add2CartBtn']");if(cartBtn!=null){cartBtn=cartBtn[0];}}
if(cartBtn!=null){dojo.setStyle(cartBtn,"pointer-events","none");dojo.addClass(cartBtn,"inactiveLink");}}else{if(cartBtn!=null){dojo.setStyle(cartBtn,"pointer-events","none");dojo.addClass(cartBtn,"inactiveLink");}}
this.toggleAddtoCartVisibility("hide");}
else{var notifyBtn=dojo.byId("notifyMe");if(notifyBtn!=null){dojo.setStyle(notifyBtn,"display","none");if(cartBtn==null){cartBtn=$("a[id^='add2CartBtn']");if(cartBtn!=null){cartBtn=cartBtn[0];}
this.toggleAddtoCartVisibility("hide");}
if(cartBtn!=null){dojo.setStyle(cartBtn,"display","block");this.toggleAddtoCartVisibility("show");}}}
if(inventoryStatus=='A'&&!flag1){dojo.removeClass("InventoryStatus_OnlineStatus_"+this.productId);dojo.addClass("InventoryStatus_OnlineStatus_"+this.productId,"text in_stock")}
else{dojo.removeClass("InventoryStatus_OnlineStatus_"+this.productId);dojo.addClass("InventoryStatus_OnlineStatus_"+this.productId,"text Limited")}}
dojo.query("#InventoryStatus_InStore_Section_"+this.productId).orphan();if(null!=dojo.byId("InventoryStatus_InStore_Heading_"+this.productId)){dojo.place("<div id='InventoryStatus_InStore_Section_"+this.productId+"' class='sublist'>","InventoryStatus_InStore_Heading_"+this.productId,"after");this.physicalStores=serviceResponse.inStoreInventory.stores;for(idx=0;idx<serviceResponse.inStoreInventory.stores.length;idx++){var store=serviceResponse.inStoreInventory.stores[idx];dojo.place("<a id='WC_InventoryStatus_Link_"+this.productId+"_store_"+(idx+1)+"' href='javascript:InventoryStatusJS_"+this.productId+".fetchStoreDetails("+store.id+");' class='store_name'>"+store.name
+"</a>","InventoryStatus_InStore_Section_"+this.productId);dojo.place("<div class='clear_float'></div>","InventoryStatus_InStore_Section_"+this.productId);dojo.place("<span> <img src='"+imageDirectoryPath+styleDirectoryPath+store.image
+"' alt='"+store.altText+"' /> </span>","InventoryStatus_InStore_Section_"+this.productId);dojo.place("<span class='text'>"+store.statusText+"</span>","InventoryStatus_InStore_Section_"+this.productId);dojo.place("<div class='clear_float'></div>","InventoryStatus_InStore_Section_"+this.productId);dojo.place("<div class='item_spacer_10px'></div>","InventoryStatus_InStore_Section_"+this.productId);}
dojo.html.set(dojo.byId("InventoryStatus_SelectStoreLink_"+this.productId),serviceResponse.inStoreInventory.checkStoreText);}
dojo.style("InventoryStatus_Availability_Section_"+this.productId,"display","block");}else{MessageHelper.displayErrorMessage(storeNLS["INV_STATUS_RETRIEVAL_ERROR"]);}
cursor_clear();};this.comparedate=function(date1,date2){if(date1>date2){return true;}
if(date1<date2){return false;}
return false;};this.resolveSKU=function(){for(idx=0;idx<this.catEntryParams.skus.length;idx++){var matches=0;var attributeCount=0;for(attribute in this.catEntryParams.skus[idx].attributes){attributeCount++;if(this.catEntryParams.attributes&&this.catEntryParams.skus[idx].attributes[attribute]==this.catEntryParams.attributes[attribute]){matches++;}else{break;}}
if(matches==attributeCount){return this.catEntryParams.skus[idx].id;}}
return-1;};this.setCommonParams=function(){var params=new Object();params.storeId=this.storeParams.storeId;params.catalogId=this.storeParams.catalogId;params.langId=this.storeParams.langId;return params;};this.fetchStoreDetails=function(storeId){MessageHelper.hideAndClearMessage();var params=new Object();params.physicalStoreId=storeId;if(!submitRequest()){return;}
cursor_wait();wc.service.invoke("getPhysicalStoreDetails",params);};this.populateStoreDetails=function(serviceResponse,ioArgs){var store=serviceResponse;store.hours=this.unEscapeXml(serviceResponse.hours);var storeInventory=this.fetchInventoryStatus(ioArgs.args.content.physicalStoreId);store.imageTag="<img src='"+imageDirectoryPath+styleDirectoryPath+storeInventory.image+"' alt='"+storeInventory.altText+"'/>";store.statusText=storeInventory.statusText;if(storeInventory.status=='Available'){store.availabilityDetails="("+storeInventory.availableQuantity+")";}else if(storeInventory.status=='Backorderable'){store.availabilityDetails="("+storeInventory.availableDate+")";}else{store.availabilityDetails="";}
var storeDetails=dojo.byId("Store_Details_Template_"+this.productId).innerHTML;dojo.byId("Store_Details_"+this.productId).innerHTML=dojo.replace(storeDetails,store);var popup=dijit.byId("InventoryStatus_Store_Details_"+this.productId);if(popup!=null){popup.closeButtonNode.style.display='none';closeAllDialogs();popup.show();}else{console.debug("InventoryStatus_Store_Details_"+this.productId+" does not exist");}
cursor_clear();};this.fetchInventoryStatus=function(storeId){for(idx=0;idx<this.physicalStores.length;idx++){if(this.physicalStores[idx].id==storeId){return this.physicalStores[idx];}}
return{};};this.unEscapeXml=function(str){var str=str.replace(/&lt;/gm,"<").replace(/&gt;/gm,">");return str;};this.loadStoreLocator=function(storeLocatorUrl,bundleId){var catalogEntryId=bundleId;if(null==catalogEntryId||''==catalogEntryId){catalogEntryId=this.itemId;if(-1==catalogEntryId){catalogEntryId=productId;}}
loadLink(storeLocatorUrl+"&productId="+catalogEntryId);}}
if(typeof(MerchandisingAssociationJS)=="undefined"||MerchandisingAssociationJS==null||!MerchandisingAssociationJS){MerchandisingAssociationJS={storeParams:{},baseItemParams:{},merchandisingAssociations:[],associationIndex:0,setValues:function(storeParams,baseItemParams,merchandisingAssociations){this.storeParams=storeParams;this.baseItemParams=baseItemParams;this.baseItemParams.quantity=1;this.merchandisingAssociations=merchandisingAssociations;},setBaseItemQuantity:function(baseItemQuantity){var baseItemQuantity=dojo.fromJson(baseItemQuantity);if(baseItemQuantity.length){for(idx=0;idx<baseItemQuantity.length;idx++){for(idx2=0;idx2<MerchandisingAssociationJS.baseItemParams.components.length;idx2++){if(MerchandisingAssociationJS.baseItemParams.components[idx2].skus){for(idx3=0;idx3<MerchandisingAssociationJS.baseItemParams.components[idx2].skus.length;idx3++){if(MerchandisingAssociationJS.baseItemParams.components[idx2].skus[idx3].id==baseItemQuantity[idx].id){MerchandisingAssociationJS.baseItemParams.components[idx2].id=baseItemQuantity[idx].id;break;}}}
if(MerchandisingAssociationJS.baseItemParams.components[idx2].id==baseItemQuantity[idx].id){MerchandisingAssociationJS.baseItemParams.components[idx2].quantity=baseItemQuantity[idx].quantity;break;}}}}else{MerchandisingAssociationJS.baseItemParams.quantity=baseItemQuantity;}},setBaseItemAttributes:function(baseItemAttributes){this.baseItemParams.attributes=dojo.fromJson(baseItemAttributes);},setBaseItemAttributesFromProduct:function(catEntryId,productId){var selectedAttributes=productDisplayJS.selectedAttributesList["entitledItem_"+productId];MerchandisingAssociationJS.setBaseItemAttributes(dojo.toJson(selectedAttributes));},changeItem:function(direction){if((this.associationIndex+direction)>=0&&(this.associationIndex+direction)<this.merchandisingAssociations.length){this.associationIndex=this.associationIndex+direction;dojo.byId("association_item_name").innerHTML=this.merchandisingAssociations[this.associationIndex].name;if(document.getElementById("ProductInfoName_"+this.merchandisingAssociations[this.associationIndex-direction].productId)!=null){document.getElementById("ProductInfoName_"+this.merchandisingAssociations[this.associationIndex-direction].productId).value=this.merchandisingAssociations[this.associationIndex].name;document.getElementById("ProductInfoName_"+this.merchandisingAssociations[this.associationIndex-direction].productId).id="ProductInfoName_"+this.merchandisingAssociations[this.associationIndex].productId;}
dojo.byId("association_thumbnail").src=this.merchandisingAssociations[this.associationIndex].thumbnail;if(document.getElementById("ProductInfoImage_"+this.merchandisingAssociations[this.associationIndex-direction].productId)!=null){document.getElementById("ProductInfoImage_"+this.merchandisingAssociations[this.associationIndex-direction].productId).value=this.merchandisingAssociations[this.associationIndex].thumbnail;document.getElementById("ProductInfoImage_"+this.merchandisingAssociations[this.associationIndex-direction].productId).id="ProductInfoImage_"+this.merchandisingAssociations[this.associationIndex].productId;}
dojo.byId("association_thumbnail").alt=this.merchandisingAssociations[this.associationIndex].name;dojo.byId("combined_total").innerHTML=this.merchandisingAssociations[this.associationIndex].offeredCombinedPrice;if(document.getElementById("ProductInfoPrice_"+this.merchandisingAssociations[this.associationIndex-direction].productId)!=null){document.getElementById("ProductInfoPrice_"+this.merchandisingAssociations[this.associationIndex-direction].productId).value=this.merchandisingAssociations[this.associationIndex].skuOfferPrice;document.getElementById("ProductInfoPrice_"+this.merchandisingAssociations[this.associationIndex-direction].productId).id="ProductInfoPrice_"+this.merchandisingAssociations[this.associationIndex].productId;}
dojo.byId("list_total").innerHTML=this.merchandisingAssociations[this.associationIndex].listedCombinedPrice;if(dojo.byId("association_url").ontouchend==undefined){dojo.byId("association_url").href=this.merchandisingAssociations[this.associationIndex].url;}
dojo.byId("association_url").title=this.merchandisingAssociations[this.associationIndex].shortDesc;if(dojo.byId("association_url").ontouchend!=undefined){currentPopup="";dojo.byId("association_url").setAttribute("ontouchend","handlePopup('"+this.merchandisingAssociations[this.associationIndex].url+"','merchandisingAssociation_QuickInfoDiv"+this.merchandisingAssociations[this.associationIndex].id+"')");}
dojo.byId("merchandisingAssociation_QuickInfo").href="javascript:QuickInfoJS.showDetails("+this.merchandisingAssociations[this.associationIndex].id+");";if(0==this.associationIndex){dojo.query("#up_arrow").removeClass("up_active");dojo.query("#down_arrow").addClass("down_active");dojo.byId("down_arrow").focus();}else if((this.merchandisingAssociations.length-1)==this.associationIndex){dojo.query("#down_arrow").removeClass("down_active");dojo.query("#up_arrow").addClass("up_active");dojo.byId("up_arrow").focus();}else{dojo.query("#up_arrow").addClass("up_active");dojo.query("#down_arrow").addClass("down_active");}}},setCommonParams:function(){var params=new Object();params.storeId=this.storeParams.storeId;params.catalogId=this.storeParams.catalogId;params.langId=this.storeParams.langId;params.orderId=".";params.calculateOrder="0";params.inventoryValidation="true";return params;},validate:function(){if(this.baseItemParams.type=='BundleBean'){for(idx=0;idx<this.baseItemParams.components.length;idx++){if(!isPositiveInteger(this.baseItemParams.components[idx].quantity)){MessageHelper.displayErrorMessage(storeNLS['QUANTITY_INPUT_ERROR']);return;}}}else if(this.baseItemParams.type=='ProductBean'&&(null==this.baseItemParams.attributes||"undefined"==this.baseItemParams.attributes)){MessageHelper.displayErrorMessage(storeNLS['ERR_RESOLVING_SKU']);return;}else if(!isPositiveInteger(this.baseItemParams.quantity)){MessageHelper.displayErrorMessage(storeNLS['QUANTITY_INPUT_ERROR']);return;}},addBoth2ShopCart:function(catEntryID_baseItem,catEntryID_MA,catEntryID_MA_quantity,associationIndex){this.associationIndex=associationIndex;this.validate();if(!isPositiveInteger(catEntryID_MA_quantity)){MessageHelper.displayErrorMessage(storeNLS['QUANTITY_INPUT_ERROR']);return;}
var params=this.setCommonParams();shoppingActionsJS.productAddedList=new Object();if(this.baseItemParams.type=='ItemBean'||this.baseItemParams.type=='PackageBean'||this.baseItemParams.type=='DynamicKitBean'){updateParamObject(params,"catEntryId",this.baseItemParams.id,false,-1);updateParamObject(params,"quantity",this.baseItemParams.quantity,false,-1);if(this.baseItemParams.type=='DynamicKitBean'){updateParamObject(params,"catalogEntryType","dynamicKit",-1);}
if(this.baseItemParams.type=='ItemBean'){shoppingActionsJS.saveAddedProductInfo(Math.abs(this.baseItemParams.quantity),this.baseItemParams.productId,this.baseItemParams.id,this.baseItemParams.attributes);}else{shoppingActionsJS.saveAddedProductInfo(Math.abs(this.baseItemParams.quantity),this.baseItemParams.productId,this.baseItemParams.id,shoppingActionsJS.selectedAttributesList['entitledItem_'+this.baseItemParams.id]);}}else if(this.baseItemParams.type=='BundleBean'){for(idx=0;idx<this.baseItemParams.components.length;idx++){updateParamObject(params,"catEntryId",this.baseItemParams.components[idx].id,false,-1);updateParamObject(params,"quantity",this.baseItemParams.components[idx].quantity,false,-1);if(this.baseItemParams.components[idx].productId!=undefined){var selectedAttrList=new Object();for(attr in shoppingActionsJS.selectedProducts[this.baseItemParams.components[idx].productId]){selectedAttrList[attr]=shoppingActionsJS.selectedProducts[this.baseItemParams.components[idx].productId][attr];}
shoppingActionsJS.saveAddedProductInfo(Math.abs(this.baseItemParams.components[idx].quantity),this.baseItemParams.components[idx].productId,this.baseItemParams.components[idx].id,selectedAttrList);}else{shoppingActionsJS.saveAddedProductInfo(Math.abs(this.baseItemParams.components[idx].quantity),this.baseItemParams.components[idx].id,this.baseItemParams.components[idx].id,shoppingActionsJS.selectedProducts[this.baseItemParams.components[idx].id]);}}}else{var sku=this.resolveSKU();if(-1==sku){MessageHelper.displayErrorMessage(storeNLS['ERR_RESOLVING_SKU']);return;}else{updateParamObject(params,"catEntryId",sku,false,-1);updateParamObject(params,"quantity",this.baseItemParams.quantity,false,-1);shoppingActionsJS.saveAddedProductInfo(Math.abs(this.baseItemParams.quantity),this.baseItemParams.id,sku,this.baseItemParams.attributes);}}
if(this.merchandisingAssociations[this.associationIndex].type=='ItemBean'||this.merchandisingAssociations[this.associationIndex].type=='PackageBean'||this.merchandisingAssociations[this.associationIndex].type=='DynamicKitBean'){updateParamObject(params,"catEntryId",this.merchandisingAssociations[this.associationIndex].id,false,-1);updateParamObject(params,"quantity",catEntryID_MA_quantity,false,-1);if(this.merchandisingAssociations[this.associationIndex].productId!=undefined){shoppingActionsJS.saveAddedProductInfo(Math.abs(catEntryID_MA_quantity),this.merchandisingAssociations[this.associationIndex].productId,this.merchandisingAssociations[this.associationIndex].id,shoppingActionsJS.selectedAttributesList['entitledItem_'+this.merchandisingAssociations[this.associationIndex].id]);}else{shoppingActionsJS.saveAddedProductInfo(Math.abs(catEntryID_MA_quantity),this.merchandisingAssociations[this.associationIndex].id,this.merchandisingAssociations[this.associationIndex].id,shoppingActionsJS.selectedAttributesList['entitledItem_'+this.merchandisingAssociations[this.associationIndex].id]);}
this.addItems2ShopCart(params);}else if(this.merchandisingAssociations[this.associationIndex].type=='BundleBean'){for(idx=0;idx<this.merchandisingAssociations[this.associationIndex].components.length;idx++){updateParamObject(params,"catEntryId",this.merchandisingAssociations[this.associationIndex].components[idx].id,false,-1);updateParamObject(params,"quantity",catEntryID_MA_quantity,false,-1);shoppingActionsJS.saveAddedProductInfo(Math.abs(catEntryID_MA_quantity),this.merchandisingAssociations[this.associationIndex].components[idx].id,this.merchandisingAssociations[this.associationIndex].components[idx].id,shoppingActionsJS.selectedProducts[this.merchandisingAssociations[this.associationIndex].components[idx].id]);}
this.addItems2ShopCart(params);}else{var entitledItemJSON=null;if(dojo.byId(catEntryID_MA)!=null){entitledItemJSON=eval('('+dojo.byId(catEntryID_MA).innerHTML+')');}else{entitledItemJSON=shoppingActionsJS.getEntitledItemJsonObject();}
shoppingActionsJS.setEntitledItems(entitledItemJSON);var catEntryID_MA_SKU=shoppingActionsJS.getCatalogEntryId(catEntryID_MA);if(null==catEntryID_MA_SKU){MessageHelper.displayErrorMessage(storeNLS['ERR_RESOLVING_SKU']);return;}else{updateParamObject(params,"catEntryId",catEntryID_MA_SKU,false,-1);updateParamObject(params,"quantity",catEntryID_MA_quantity,false,-1);shoppingActionsJS.saveAddedProductInfo(catEntryID_MA_quantity,catEntryID_MA.split("_")[1],catEntryID_MA_SKU,shoppingActionsJS.selectedAttributesList['entitledItem_'+this.merchandisingAssociations[this.associationIndex].id]);this.addItems2ShopCart(params);}}},resolveSKU:function(){for(idx=0;idx<this.baseItemParams.skus.length;idx++){var matches=0;var attributeCount=0;for(attribute in this.baseItemParams.skus[idx].attributes){attributeCount++;if(this.baseItemParams.attributes&&this.baseItemParams.skus[idx].attributes[attribute]==this.baseItemParams.attributes[attribute]){matches++;}else{break;}}
if(matches==attributeCount){return this.baseItemParams.skus[idx].id;}}
return-1;},addItems2ShopCart:function(params){var shopCartService="AddOrderItem";if(params['catalogEntryType']=='dynamicKit'){shopCartService="AddPreConfigurationToCart";}
if(!submitRequest()){return;}
cursor_wait();wc.service.invoke(shopCartService,params);},subscribeToEvents:function(baseCatalogEntryId){dojo.topic.subscribe("Quantity_Changed",MerchandisingAssociationJS,MerchandisingAssociationJS.setBaseItemQuantity);dojo.topic.subscribe("DefiningAttributes_Resolved_"+baseCatalogEntryId,MerchandisingAssociationJS.setBaseItemAttributesFromProduct);}}}