var isShow=false;
var autoCloseHopop=false;
var openingMiniCart;
$(document).ready(
	function()
	{   
		$('#cartHopupOpen').bind(
			'mouseover',
			function(){
			    isShow=true;
                openingMiniCart=setTimeout("showCartHopup();",500);
			}
		);
		$('#cartHopupOpen').bind(
			'click',
			function(){
			    clearTimeout(openingMiniCart);
			    window.location.href="/ShoppingCart.aspx";
			}
		);

		$('#cartHopupOpen').bind(
			'mouseout',
			function(){
			    isShow=false;
			} 
		);
		
		
		$('#cartHopupClose').bind(
			'click',
			function()
			{
			    $("#cartHopupOpen").unbind("click"); 
                removeMask(); 
                $('#cartHopup').css("display","none");
                $('#cartHopMask ').css("display","none");
                $("#transfererMask").animate({  width:"0",height:"0" },500);
                    setTimeout(function(){$('#cartHopupOpen').click(function(){window.location.href="/ShoppingCart.aspx";});},550);
			}
		);
		
		$('#hopupWindowClose').bind(
			'click',
			function()
			{
			    if($('#hopupMask').css('display') == 'block') removeMask();
			    $('#hopupIfame').attr("src",(getDomainById(1)+"/Images/Spacer.gif"));  
			    $('#hopupWindow').addClass("closeBolder"); // hide background
                $("#hopupWinContentBg").removeClass("hopupWinBolder"); //hide border 
				$('#hopupWindow').css("display","none");
			}
		);
		//seach  productDetail list
//        $(".showImg ").hover(
////			function() { 
////			    var filePath=window.location.pathname.substr(window.location.pathname.lastIndexOf('/')+1).toLowerCase();
////			    switch(filePath)
////			    {
////			        case "category.aspx":
////			        case "searchresults.aspx":
////			        case "subcategory.aspx":
////			        case "allcategories.aspx":
////			            return false;
////			            break;
////			    }  
////			    this.canShow=true;
////			    var show=showQuickViewBtnFunctionBuilder(this);
////			    setTimeout(show,250); 
////			         
//////			    $(".quickViewBtn").css("display","none");
//////			    $(this).prev().css("display","block");
////            },
//            function(){
//                this.canShow=false; 
//                $(".quickViewBtn").css("display","none"); 
//            }
//		);
		
//		$(".quickViewBtn").hover(
//			function() {                    
//			    $(this).css("display","block");
//            },
//            function(){
//                $(".quickViewBtn").css("display","none"); 
//            }
//		);
		
//		$(".quickViewBtn").bind(
//		    "click",
//		    function()
//		    {
//                var y= document.documentElement.scrollTop;
//                var attrValue = $(this).attr("alt"); 
//                var redirectUrl;
//                var pos = attrValue.indexOf(",");
//                if (pos > 0)
//               {
//                    redirectUrl="/Product/QuickView.aspx?ProductId="+attrValue.substring(0, pos) + "&type=" + attrValue.substring(pos + 1);
//               }  
//               else
//               {
//                    redirectUrl="/Product/QuickView.aspx?ProductId="+$(this).attr("alt");
//               }
//   
//                openHopup(0,0,576,850,"blueBolder","quick",redirectUrl,true,true);//576
//                $(this).css("display","none"); 
//                this.blur();
//                return false; 
//		    }
//		);
		$('#essentialsLi').bind(
			'click',
			function()
			{
			    //showMask();
			    var obj = $("#"+$(this).find("img").attr("id").replace("Img","Div"));
                var newLeft = ($(this).offset().left + $(this).width()) - $("#wrap").offset().left - obj.width() + 10;
                obj.css("display","block");
                obj.css("left",newLeft + "px");
			}
		);	
		$('#registryLi').bind(
			'click',
			function()
			{
			    //showMask();
			    var obj = $("#"+$(this).find("img").attr("id").replace("Img","Div"));
                var newLeft = ($(this).offset().left + $(this).width()) - $("#wrap").offset().left - obj.width() + 10;
                obj.css("display","block");
                obj.css("left",newLeft + "px");
                $("#sortSelect").css("display","none"); // IE6 hack - Inputs always show at top level
			}
		);	
		
//		$("#personalizeLi").click(
//		     function()
//		    {
//		        showMask();
//		       	$('#hopupMask').css("z-index","150");  
//                $("#"+$(this).find("img").attr("id").replace("Img","Div")).css("display","block"); 
//                if ($("#shopDropFrame").attr("src")==(getDomainById(1)+"/Images/Spacer.gif") || $("#shopDropFrame").attr("scr")==undefined)
//               { 
//                    $("#shopDropFrame").attr("src","/Personalization/NewUser.aspx");
//                    $('#shopDropFrame').before(newHopupLoading($("#shopDropFrame").parent()));
//                }
//		    }
//		);		
        
		$("#registryDiv").find("li,.quickTitle").bind(
			'click',
			function()
			{
			    removeMask();
                $("#registryDiv").css("display","none");
                $("#sortSelect").css("display","block"); // IE6 hack - Inputs always show at top level 
            }
		);		
//		$("#shopDiv").find("li,.quickTitle,#shopDropClose,.ContinueShop").bind(
//			'click',
//			function()
//			{
//			    removeMask();
//			    $("#hopupMask").css("z-index","199");   
//                $("#shopDiv").css("display","none");
//               //reload for refresh item for you 
//               if(window.location.href.toLowerCase().indexOf("/mydiapers.aspx")>=0)
//               {  
//                    window.location.href=window.location.href; 
//               }else if(window.location.pathname=='/'||window.location.pathname.toLowerCase().indexOf("/index.aspx")>=0){
//                    window.location.href=window.location.href; 
//               }else{ 
//                    updateSignName();
//               }
//			}
//		);	
		$("#essentialsDiv").find("li,.quickTitle").bind(
			'click',
			function()
			{
			    removeMask();
                $("#essentialsDiv").css("display","none");
			}
		);	
		//mouseover action for all image buttons
		$(".hoverImg").hover(
		    function()
		    {
		        $(this).attr("src",$(this).attr("src" ).replace("off","on"));
		    },
		    function()
		    {
		        $(this).attr("src",$(this).attr("src" ).replace("on","off"));
		    }
		);	
	}
);
function closeHopupWindow()
{
    if($('#hopupMask').css('display') == 'block') removeMask();
    parent.$('#hopupIfame').attr("src",(getDomainById(1)+"/Images/Spacer.gif"));  
    //$('#hopupWindow').hide();	safari do not work
    $('#hopupWindow').css("display","none");
}
function showMask()
{
  if($('#hopupMask')) {
       setHopupMaskSize(); 
       $('#hopupMask').css("display","block");
   } 
}
function removeMask()
{
   if($('#hopupMask')) {
       $('#hopupMask').width(0);
       $('#hopupMask').height(0);
       $('#hopupMask').css("display","none");
   }
}
var clientNameId;
var timeID=null;
function initHopup()
{
		$('#hopupWindow').css("display","block");
		$("#hopupWindowTop").css({"display":"block"}); 
		$('#hopupWindowTopContent').empty();   
		$('#hopupWindowClose').css({"right": "17px", "top":"17px"});
		$('#hopupWindowContent').find("#loadingDiv").css("display","none");
        $('#hopupWindowContent').find(".alertHopupWinBtn").remove();
        $('#hopupWindowContent').find("#hopupWarningBox").remove();		
        $("#hopupWinContentBg").removeClass("hopupWinBolder"); //hide border 
        $('#hopupWindow').addClass("closeBolder"); // hide background
        clearTimeout(timeID);//if Alert, clear its timeID to turn off the auto-close function
}
function openHopup(left,top,height,width,bgImg,pageTitle,openPage,maskFlag,pageFooter,clientId,itemName)
{
   clientNameId=clientId;
   initHopup();
    var imgUrl;
    if($('#hopupWindow')){
        //if "maskFlag" is false, do not move the hopup window to the center of screen, if true, move the hopup to center
         if (maskFlag)
         {
            if (pageTitle=="quick")
            {
                height=160;
                width = 400; 
            }
              showMask() ;
              $('#hopupWindow').css({"width":width,"height":height+25});
              setHopupToCenter(width, height); //move the hopup window to the center of screen, 
         }
         else
         {
                $('#hopupWindow').css({"left":left+"px","top":top+"px","width":width,"height":height});
         }
          if (bgImg!="blueBolder") 
           {
                imgUrl= "url("+getDomain()+"/Images/"+bgImg+")";
                $("#hopupWindowTopContent").css("padding-top","5px");
                $('#hopupWindow').css({"width":width, "height":height+10});
                $('#hopupWinContentBg').css({"width":width-4}); 
               $('#hopupWindowClose').css({"top":10+"px", "right":25+"px"});
               if (bgImg == "brandHopupBg.png")
               {
                	$('#hopupPNGMask').addClass("hopupRedOutline");
                	$('#hopupPNGMask').css({"width":width, "height":height+10});
                	$('#hopupIfame').css("display","block");
              }
              else
                    $('#hopupWindow').css({"background":imgUrl,"backgroundRepeat":"no-repeat"});
           }
           else
           {
                $('#hopupWindow').removeClass("closeBolder");
                $('#hopupWinContentBg').css({"width":width-4,"height":height-24});
                $("#hopupWinContentBg").addClass("hopupWinBolder");
                $("#hopupWindowTop").css({"padding-top":"0px"});
                $('#hopupPNGMask').removeClass("hopupRedOutline");
                $('#hopupWindow').css({"background":"none"}); 
            }
            $('#hopupIfame').height(height-60);
            if (openPage != "" && openPage != null) //load hopupIframe and show Loading text
            {
                $('#hopupIfame').attr("src",openPage);
                $('#hopupWindowContent').prepend(newHopupLoading($('#hopupWindowContent')));
                $("#loadingDiv > span").css("line-height", (height-120)+"px"); 
                showHopupLoading("#hopupIfame"); 
            }
            if(pageTitle=="quick"){
                $('#hopupWindowTopContent').append("<h2  id='quickViewTitle'>QUICK <strong>SHOP</strong></h2>");
                $('#hopupWindowClose').css({"right":20+"px"});
            }
            else if (pageTitle==""){
               $("#hopupWindowTop").css({"display":"none"}); 
            }
            else if(pageTitle=="alert")
            {
                $('#hopupWindowTopContent').append("<h2  class='hopupTitle'></h2>");
               if(itemName=='cancelOrder')
              {
                        $('#hopupWindowTopContent > h2').text("Are you sure you want to cancel this order?");
              } 
              else if(itemName=='removeAddress')
              {
                        $('#hopupWindowTopContent > h2').text("Are you sure you want to remove this address?");
              }
              else
              {
                   if(itemName!="" && itemName!= undefined)
                        $('#hopupWindowTopContent > h2').text("Are you sure you want to remove this child?");
                   else
                        $('#hopupWindowTopContent > h2').text("Are you sure you want to REMOVE this item?");
              } 
                $('#hopupWindowTopContent > h2').css({"font-size":"17px","padding-top":"15px"});
                $('#hopupWindowClose').css({"top":"10px","right":"15px"});
                $('#hopupWindowContent').prepend("<div class='btnsBox alertHopupWinBtn'><input id='divYes' type='button' class='redBtn' onclick='__doPostBack(\""+clientNameId+"\",\"\");' value='Yes' /><input id='divNo' value='No' type='button' class='cancelBtn' /></div>");
                $('#hopupWindowContent'). find('#hopupIfame').height(0);
               if ($(window.parent.document).find("#shopDiv").css("display")=="block")
               {
                    $('#hopupMask').width($(document.body).width());
                    $('#hopupMask').height($(document.body).height());
               }
                $('#divNo').bind(
			    'click',
			        function()
			        {
			            if($('#hopupMask').css('display') == 'block') removeMask();
			            $('#hopupWindowContent').find(".alertHopupWinBtn").remove();
				        $('#hopupWindow').css("display","none");
			        }
		        );
		        
		        myStiky = $('#hopupWindow');
                var availTop = null;
                var availLeft = null;
                if (availTop==null)
                {
                        scrollTop = (window.parent.pageYOffset== undefined)?window.parent.document.documentElement.scrollTop:window.parent.pageYOffset;
                        availHeight = window.parent.document.documentElement.clientHeight;
                        availTop=(availHeight - myStiky.height())/2 + scrollTop - 50;
                        if ((availTop + myStiky.height()) > document.documentElement.clientHeight && window.parent!=window)
                        {
                            availTop = document.documentElement.clientHeight - myStiky.height() - 45;
                        }
                        availTop=(availTop<0)?0:availTop;
                }
                if (availLeft==null)
                {
                      scrollLeft = (window.pageYOffset== undefined)?document.documentElement.scrollLeft:window.pageXOffset;
                      if ($("#wrap").width()!=null && document.documentElement.clientWidth>$("#wrap").width() )
                      {
                            availLeft=($("#wrap").width() - myStiky.width())/2 + scrollLeft;
                      }
                      else
                      {
                            availWidth = document.documentElement.clientWidth;
                            availLeft=(availWidth - myStiky.width())/2 + scrollLeft;
                      }
                     availLeft=(availLeft<0)?0:availLeft; 
                }
                myStiky.css({"top":availTop,"left":availLeft }); 
                }
                else{
                $('#hopupWindowTopContent').append("<h2  class='hopupTitle'></h2>");
                $('#hopupWindowTopContent > h2').text(pageTitle);

                }
//			if(openPage!='')
//			{
//				$('#hopupWindowContent').attr("innerHTML",
//					"<iframe id=\"hopupIfame\" scrolling=\"no\" frameborder=\"0\" width=\"96%\" style=\"height: 60px; \" src=\"\"></iframe>");
//				$('#hopupIfame').height(height-60);
//				$('#hopupIfame').attr("src",openPage);
//				$('#hopupIfame').show();
//			}
            if (pageFooter==true)
            {
               if (pageTitle=="quick")
               {
                        $("#hopupWindowFooterContent").css({"top":height-30, "width":width-50}); 
                        }
                       else if(pageTitle =="Suggest a Product")
                      {
                            $("#hopupWindowFooterContent").css({"top":height-40, "width":width-50}); 
                      }  
                      else
                            $("#hopupWindowFooterContent").css({"top":height-40, "width":width-30}); 
                      $("#hopupWindowFooterContent").css("display","block");
                      $(".ContinueShop").click(
                        function()
                        {
                            parent.$('#hopupWindowClose').click();
                        }); 
             } 
            else
            {
                $("#hopupWindowFooterContent").css("display","none");
             }   
    }  
}
function closeHopup(flag)
{
    parent.$('#hopupWindowClose').click();
    if(flag) 
        parent.$('.RefreshButton').click(); 
        //parent.eval('refreshHeader();');
 }
function closeCartHopup()
{
    if(autoCloseHopop)
   {
        autoCloseHopop=false;
   } 
    parent.$('#cartHopupClose').click();
 } 
function autoOpenMiniCartHopup(qty,amount)
{
//    if(qty && amount)
//    {
//        parent.$('#ctl00_TotalQtyLabel').attr("innerHTML",qty); 
//        parent.$('#ctl00_TotalAmountLabel').attr("innerHTML",amount); 
//    }
    parent.$('#hopupWindowClose').click();
    parent.$('#cartHopupOpen').mouseover();
}

function  SetCwinHeight(obj) 
{ 
        var iframeHeight=getCookie("iframeHeight");
        if(iframeHeight)
       {
           obj.height=iframeHeight;
           delCookie("iframeHeight");
           return; 
       } 
        if  ($(obj).height()>0 && document.getElementById && obj  &&  !window.opera) 
        { 
            var  cwin=obj; 
            if  (cwin.contentDocument  &&  cwin.contentDocument.body.offsetHeight) //safari
                cwin.height  =  cwin.contentDocument.body.offsetHeight + 10;  
            else  if(cwin.Document  &&  cwin.Document.body.scrollHeight) 
                cwin.height  =  cwin.Document.body.scrollHeight + 10; 
        }
} 
function SetPersonalizeCwinHeight(obj)
{
   if ($(obj).attr("src").indexOf((getDomainById(1)+"/Images/Spacer.gif"))<0)
   {
       closeHopupLoading(obj); 
       SetCwinHeight(obj);
   }
}

function resetHopupHeight(height)
{
    
    $('#hopupWindow').css("height",height+25); 
    $("#hopupWinContentBg").css("height", height-24);
    $("#hopupWindowFooterContent").css("top",height-30); 
    $('#hopupIfame').height(height-60);
    setHopupToCenter($("#hopupWindow").width(), height); 
}
function resetHopupWidth(width)
{
    $('#hopupWindow').css("width",width);
    $('#hopupWinContentBg').css({"width":width-4});
    $("#hopupWindowFooterContent").css({"width":width-50});   
}
function setHopupToCenter(width, height)
{
      if (window.pageYOffset== undefined)
     {
            scrollTop =  document.documentElement.scrollTop;//ie,ff
            scrollLeft =  document.documentElement.scrollLeft;
     }
     else
     {
            scrollTop =  window.pageYOffset;// safari
            scrollLeft =  window.pageXOffset;// safari
      }
      hopupTop=(document.documentElement.clientHeight - height)/2 + scrollTop;
      if ($("#wrap").width()!=null && document.documentElement.clientWidth>$("#wrap").width() )
      {
            hopupLeft=($("#wrap").width() - width)/2 + scrollLeft;
      }
      else
      {
            hopupLeft=(document.documentElement.clientWidth - width)/2 + scrollLeft;
      }
      if (hopupLeft<0) 
            hopupLeft = 0;
      if (hopupTop<scrollTop) 
            hopupTop = scrollTop + 20;
       $('#hopupWindow').css({"left":hopupLeft+"px","top":hopupTop+"px"});
}
function helpCenterHopup()
{
   if ($(".titleText")[0].innerHTML!="Welcome to our Help Center")
   {
        title = $(".titleText")[0].innerHTML + " - Top Questions";
   }
   else if ($(".titleText")[0].innerHTML=="Welcome to our Help Center")
   {
        title = "Top Questions";
   }
   openHopup(0,0,443,630,'blueBolder',title,'HelpCenterHopup.aspx',true, false); 
}

function showCartHopup()
{
    $("#cartHopupOpen").unbind("click"); 
    if(isShow)
    {   
        $("#cartRemoveMsg").css("display","none");
        var url = "/AjaxHandler/GetMiniCartItemList.ajax?random="+Math.random();
        ajaxGetFromUrl(url, bindMiniCartItemList);
     }
}

function bindMiniCartItemList(data,status)
{
    $("#miniCartItemList").attr("innerHTML",data);
    if(data.indexOf("Your cart is empty")>-1){ //hide check out button
        $("input[id*=imgBtnCheckout]").hide();
    }else{
        $("input[id*=imgBtnCheckout]").show();
    }
    $("#transfererMask").animate({width:"480px",height:"150px" },500,function(){
         $('#cartHopup').show();
         if(jQuery.browser.msie && parseInt(jQuery.browser.version)<=6)
         {
             $('#cartHopMask').css('display','block');
         }  
         $('#cartHopMask').height($("#cartHopup").height() - 90) ;
         
   });
    setTimeout(function(){$('#cartHopupOpen').click(function(){window.location.href="/ShoppingCart.aspx";});},550);
    if(autoCloseHopop)
    {
        setTimeout("closeCartHopup();",4000); 
    } 
    parent.scroll(0,0);
    getCartQtyAndPriceCount();
}

function removeBasketItem(basketItemId)
{
    var url = "/AjaxHandler/RemoveMiniCartItem.ajax?ajax_param1="+basketItemId+"&random="+Math.random();
    ajaxGetFromUrl(url, function(data,status){
    bindMiniCartItemList(data,status);
    if(typeof(showShoppingCart)!="undefined" && showShoppingCart)
    {
        showShoppingCart();  
    } 
    if(typeof(showOrderSummary)!="undefined" && showOrderSummary)
    {
        showOrderSummary();
    } 
    }); 
    $("#cartRemoveMsg").css("display","block");
}

function getCartQtyAndPriceCount()
{ 
//    alert(arguments.callee.caller);
    var url = "/AjaxHandler/GetCartQtyAndPriceCount.ajax?ajax_param1=N&random="+Math.random();
    var jsonResult = ajaxSync(url);
    var result = eval(jsonResult);
    if(result && result.totalQty && result.totalPrice){
        var totalQtyLabel =$('#ctl00_TotalQtyLabel') || parent.$('#ctl00_TotalQtyLabel') ;
        var totalAmountLabel =$('#ctl00_TotalAmountLabel')|| parent.$('#ctl00_TotalAmountLabel') ;
        totalQtyLabel.attr("innerHTML",result.totalQty); 
        totalAmountLabel.attr("innerHTML",result.totalPrice); 
    }

    if (result && result.shippingMsg != '')
    {
        var fastFreeShippingText = $('#fastFreeShippingText') || parent.$('#fastFreeShippingText'); 
        fastFreeShippingText.attr('innerHTML',result.shippingMsg); 
    }  
}

//show the  QuickView button
function showQuickViewBtn(obj)
{
    if(obj.canShow){ 
        $(".quickViewBtn").css("display","none");
        $(obj).find(".quickViewBtn").css("display","block");
    } 
}

//builder the show function
//becase the arguments could not specified when calling the setTimeout function
//so use the transitive function
function showQuickViewBtnFunctionBuilder(obj)
{
    return function(){
       showQuickViewBtn(obj);
   } 
} 

function showQuickViewHopup(productId)
{
    var  redirectUrl="../Product/QuickView.aspx?ProductId="+productId;
    openHopup(0,0,576,850,"blueBolder","quick",redirectUrl,true,true);
}

function setHopupMaskSize()
{
       var leftValue=0;
       var widthValue=981; 
       var parent=$('#hopupMask').parent().parent();
       if(($(document.body).width()-980)>0){
//           leftValue=-($(document.body).width()-980)/2;

            //different position value cause different left value
           switch(parent.css("position"))
           {
               case "static":
                break;
               case "relative":
                    leftValue=-($(document.body).width()-980)/2; 
                break;
               case "abosulte":
                break;     
           }
           widthValue=$(document.body).width();
       } 
       else
       {
           //11 value of cartHopup css right 
           widthValue+=11;
       }
       $('#hopupMask').css("left",leftValue);
       $('#hopupMask').width(widthValue);
       $('#hopupMask').height($(document.body).height()+250);
}

$(window).resize(
    function(){
   if($("#hopupMask") && $("#hopupMask").css("display")=="block")
   {
       setHopupMaskSize();
   }
   }
); 
//Hopup Loading Text functions begin-------------------------------------------------------
function newHopupLoading(obj) // ex. $("#test").append(loadingHTML())
{
   if (obj.find("#loadingDiv").length==0) 
        return "<div id='loadingDiv'><span><img src='"+getDomain()+"/Images/loading.gif'></span><span>Please Wait ...</span></div>";
  else
        return "";
}
function showHopupLoading(obj)
{
   $(obj).css("display","none");
   $(obj).parent().find("#loadingDiv").css("display","block");   
}
function closeHopupLoading(obj)
{
   $(obj).css("display","block");
   $(obj).parent().find("#loadingDiv").css("display","none"); 
}
function closeHopupIframeLoading(obj)
{
    if ($(obj).attr("src")!="" && $(obj).parent().find("#loadingDiv").css("display")=="block")
   { 
        closeHopupLoading(obj);
    }
}
//Hopup Loading Text functions end---------------------------------------------------------