﻿function updateMiniCart(totaItem,sumPrice)
{
    if($('span[id*=TotalQtyLabel]') && $('span[id*=TotalAmountLabel]'))
    { 
        $('span[id*=TotalQtyLabel]').text(totaItem);
        $('span[id*=TotalAmountLabel]').text("$"+sumPrice.toFixed(2));
    } 
}

function openFixWin(address, winname, height, width, scrollbars,resizeable) {
    var iHeight = height;
    var iWidth = width;
    var iLeft = (screen.width - iWidth)/2;
    var iTop = (screen.height- iHeight)/2;
    var iScrollbars = scrollbars;
    var iResizeable = resizeable;
    if(iScrollbars == null || iScrollbars=="") {
        iScrollbars = "yes";
    } 
    var feature = "left="+iLeft+",top="+iTop+",fullscreen=0,width= " + iWidth + ",height=" + iHeight +",toolbar=no, menubar=no, scrollbars=" + iScrollbars + ", resizable=" + iResizeable+ ", location=no, status=no";
    var win =window.open(address,winname,feature);
    win.focus();
    win = null;
}

function appendRandomToUrl(url) {    
    if (url) {
        var appendParam = "random=";
        var index = url.indexOf(appendParam);
        if (index > 0) {
            url = url.substring(0, index);
        }
        var concatStr = "";
        var lastChar = url.charAt(url.length-1);
        if (lastChar != '&' && lastChar != '?') {
            if (url.indexOf('?') > 0) concatStr = "&";
            else concatStr = "?";
        }
        url += concatStr + appendParam + Math.random();        
    }
    return url;
}
function blockMultiClick(button,time)
{
    if(!time || time==""){
        time=500;
    }
    button.disabled='disabled';
    setTimeout(function(){button.disabled="";},500);
}

function updateSignName()
{
    var url = "/AjaxHandler/GetCustomerFirstName.ajax?random="+Math.random();
    var userName = ajaxSync(url);
    if(userName==""){//show sign in
        $("#signInLi").css("display","block");
        $("#signOutLi").css("display","none");
        //$("#frontHomeLinkLi").css("display","block");
        //$("#backHomeLinkLi").css("display","none");
    }else{ //show welcome and sign out
        $("#signInLi").css("display","none");
        $("#signOutLi").css("display","block");
        //$("#frontHomeLinkLi").css("display","none");
        //$("#backHomeLinkLi").css("display","block");
        $("#welcomeUserNameSpan").attr("innerHTML","Welcome "+userName);
    }
}

//var webConfig=new Object();
//webConfig.cDNModeOfHttp=true;
//webConfig.cDNModeOfHttps=true;
//webConfig.hostIndex=0;
//webConfig.hostOfHttp=new Array();
//webConfig.hostOfHttp[0]='c1';
//webConfig.hostOfHttp[1]='c2';
//webConfig.hostOfHttp[2]='c3';
//webConfig.hostOfHttps=new Array();
//webConfig.hostOfHttps[0]='c1';
//webConfig.hostOfHttps[1]='c2';
//webConfig.hostOfHttps[2]='c3';
//webConfig.domainOfHttp='diapers.com';
//webConfig.domainOfHttps='diapers.com';

var webConfig=new Object();
webConfig.cDNModeOfHttp=true; 
webConfig.hostOfHttp=new Array();
webConfig.hostOfHttp[webConfig.hostOfHttp.length]='c1';
webConfig.hostOfHttp[webConfig.hostOfHttp.length]='c2'; 
webConfig.hostOfHttp[webConfig.hostOfHttp.length]='c3';
webConfig.hostOfHttps=new Array(); 
webConfig.cDNModeOfHttps=false; 
webConfig.hostIndex=0; 
webConfig.domainOfHttp='diapers.com'; 
webConfig.domainOfHttps='diapers.com'; 
function getDomain()
{
    if(!webConfig)
    {
        return '';
    } 
    if(webConfig.cDNModeOfHttp && window.location.protocol=="http:")
    {
        webConfig.hostIndex=webConfig.hostIndex<webConfig.hostOfHttp.length?webConfig.hostIndex:0;
        return "http://"+ webConfig.hostOfHttp[webConfig.hostIndex++]+"."+webConfig.domainOfHttp;
    } 
    else if(webConfig.cDNModeOfHttps && window.location.protocol=="https:")
    {
        webConfig.hostIndex=webConfig.hostIndex<webConfig.hostOfHttps.length?webConfig.hostIndex:0;
        return "https://"+ webConfig.hostOfHttps[webConfig.hostIndex++]+"."+webConfig.domainOfHttp;
    } 
    else
    {
        return ''; 
    }  
}

function getDomainById(id)
{
    if(!webConfig)
    {
        return '';
    } 
    if(webConfig.cDNModeOfHttp && window.location.protocol=="http:")
    {
        return "http://"+ webConfig.hostOfHttp[id%webConfig.hostOfHttp.length]+"."+webConfig.domainOfHttp;
    } 
    else if(webConfig.cDNModeOfHttps && window.location.protocol=="https:")
    {
        return "https://"+ webConfig.hostOfHttps[id%webConfig.hostOfHttps.length]+"."+webConfig.domainOfHttp;
    } 
    else
    {
        return ''; 
    }  
}


function SetCookie(name,value)//两个参数，一个是cookie的名子，一个是值
{
    var Days = 30; //此 cookie 将被保存 30 天
    var exp  = new Date();    //new Date("December 31, 9998");
    exp.setTime(exp.getTime() + Days*24*60*60*1000);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}
function getCookie(name)//取cookies函数        
{
    var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
     if(arr != null) return unescape(arr[2]); return null;

}
function delCookie(name)//删除cookie
{
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval=getCookie(name);
    if(cval!=null) document.cookie= name + "="+cval+";expires="+exp.toGMTString();
}

function refreshHeader()
{
    var url = "/AjaxHandler/GetShopCartAndShipFee.ajax?random="+Math.random();
    ajaxGetFromUrl(url, bindShopCartAndFee);
}

function bindShopCartAndFee(data,status)
{ 
    var result =eval(data);    
    $(".totalQty").attr("innerHTML",result[0]);
    $(".totalAmount").attr("innerHTML",result[1]);
    $("#fastFreeShippingText").attr("innerHTML",result[2]);
}
 function trim(str)
   {
     s = str.replace(/^(\s)*/, '');
     s = s.replace(/(\s)*$/, '');
     return s;
   }

function limitTextBoxMaxLength(textBox,maxLength){
    //if(textBox && length && maxLength>0){
        //if(textBox.value.length>maxLength){
            //textBox.value = textBox.value.substring(0,maxLength);
        //}
    //}
    var leftNum = 0;
    var descText = textBox;
    if((/\r\n/g).test(descText.value))
    {
        leftNum = maxLength - descText.value.length;
    }
    else
    {
        var countLF= descText.value.match(/\n/g);
        leftNum = maxLength - descText.value.length-(countLF==null?0:countLF.length);
   }   
    if (leftNum < 0)
    {
        descText.value = descText.value.substr(0, maxLength);
        leftNum = 0;
    }
}

function limitGiftNoteTextBoxMaxLength(textBox,maxLength){
    var leftNum = 0;
    var descText = textBox;
    if ($.trim(descText.value) == "Enter your message here") {
        leftNum = maxLength;
    }
    else if ((/\r\n/g).test(descText.value))
    {
        leftNum = maxLength - descText.value.length;
    }
    else
    {
        var countLF= descText.value.match(/\n/g);
        leftNum = maxLength - descText.value.length-(countLF==null?0:countLF.length);
   }   
    if (leftNum < 0)
    {
        descText.value = descText.value.substr(0, maxLength);
        leftNum = 0;
    }
    var numSpan = document.getElementById("numSpan");
    numSpan.innerHTML = leftNum;
}

function limitGiftWrapItemNoteTextBoxMaxLength(textBox,maxLength,numSpan){
    var leftNum = 0;
    var descText = textBox;
    if ($.trim(descText.value) == "Enter your message here") {
        leftNum = maxLength;
    }
    else if((/\r\n/g).test(descText.value))
    {
        leftNum = maxLength - descText.value.length;
    }
    else
    {
        var countLF= descText.value.match(/\n/g);
        leftNum = maxLength - descText.value.length-(countLF==null?0:countLF.length);
   }   
    if (leftNum < 0)
    {
        descText.value = descText.value.substr(0, maxLength);
        leftNum = 0;
    }
    numSpan.innerHTML = leftNum;
}

function sendTellApartRequest(updateCartType,cartList) 
{
    if(typeof(__cmbLoaded) != "undefined" && __cmbLoaded)
    {
	    var action = TellApartCrumb.makeCrumbAction("HFvqUjcldZsQ","updatecart");
	    action.setActionAttr("UpdateCartType", updateCartType);
        for(i=0;i<cartList.length;i++)
        {
	        action.beginItem();
            action.setItemAttr("SKU", cartList[i].sku);
            action.setItemAttr("ProductPrice", cartList[i].price);
            action.setItemAttr("ItemCount", cartList[i].itemCount);
            action.endItem();
        }
        if (typeof (__customerNumber) != "undefined" && __customerNumber) 
        {
            action.setUserId(__customerNumber);
        }
	    action.finalize();
	}
}

function getCdnDomainByKnownSrcUrl(url)
{
    if(!url || window.location.protocol=="https:")
    {
        return '';
    }
    var a = document.createElement("a");
    a.href= url;
    return "http://" + a.hostname;
}

function openShippingPolicyHopup(isFaceBook, topObj){
    var top = (isFaceBook != undefined && isFaceBook.toLowerCase() == "true") ? (topObj.offset().top + 20) : null;
    openStikcyHopup('/shippingpolicy.aspx', '', 600, true, null, top);
}

function openShipToZipHopup(isFaceBook, topObj){
    var top = (isFaceBook != undefined && isFaceBook.toLowerCase() == "true") ? (topObj.offset().top + 10) : null;
    openStikcyHopup('/ShipToZip.aspx', '', 388, true, null, top);
}

function openUSPSPolicyHopup(isFaceBook, topObj){
    var top = (isFaceBook != undefined && isFaceBook.toLowerCase() == "true") ? (topObj.offset().top + 20) : null;
    openStikcyHopup('/HelpCenter/UspsShippingPolicyHopup.aspx', '', 547, true, null, top);
}

function openGreenShippingHopup(isFaceBook, topObj){
    var top = (isFaceBook != undefined && isFaceBook.toLowerCase() == "true") ? (topObj.offset().top + 30) : null;
    openStikcyHopup('/helpcenter/greenshippinghopup.aspx', '', 445, true, null, top);
}

// open Gift Wrap Hopup
function showGiftWrapHopup(isFaceBook, topObj)
{
    var posTop = (isFaceBook != undefined && isFaceBook.toLowerCase() == "true") ? (topObj.offset().top + 20) : null;
    
    var giftWrapHtml= "<div class='giftWrapHopup'>"
	                        +"<div class='giftWrapFlag'></div>"
	                        +"<div class='giftWrapImg'></div>"
							+"<div class='giftWrapTitle'>"
							    +"Gift giving just got easier with our gift wrapping option*"
							+"</div>"
							+"<p>"
							    + "We will individually wrap each item according to its size in either a charming white gift box (with tissue paper inside) or a reusable fabric bag. A grosgrain ribbon and a special note card with your personal message complete the gift."
							+"</p>"
							+"<p style='font-size:12px;'>"
							    + "*Gift wrap is not available for some larger items or for items that ship directly from the vendor. These products are clearly marked on our site."
							+"</p>"
					 +"</div>";
	var htmlPopupPara={width:650,height:null,top:posTop,left:null,title:'',content:giftWrapHtml,showMask:true,language:'en-us',closeCallBack:null};
	var htmlPopup = new HtmlPopup(htmlPopupPara);
    htmlPopup.show();
    
    // set hopup position
	var htmlPopupHeight = htmlPopup.element["popupContent"].offsetHeight + 65;
	htmlPopup.size.height = htmlPopupHeight;
	
	if (posTop!=null){ //adjust the top of hopup if the rest height of window is not enough for the hopup
	    var restHeight = document.documentElement.offsetHeight - (posTop + htmlPopupHeight);
	    posTop = (restHeight<0)?(document.documentElement.offsetHeight - htmlPopupHeight):posTop;
	    htmlPopup.position["top"] = posTop;
	}
	
	htmlPopup.setPosition();
}

function setQuery(query,key,value)
{
	//var query=window.location.search;
	if(!query || query=="?")
	{
		return "?"+key+"="+escape(value);
	}
	var regex=new RegExp("([?]|&)"+key+"=([^&]*)(&|$)","i");
	if(regex.test(query))
	{
		return query.replace(regex,function(keyvalue,start,oldvalue,end)
		{
			return start+key+"="+value+end;
		});
	}
	return query+"&"+key+"="+escape(value);
}

function htmlEncode(str) {
    return $('<div/>').text(str).html();
}
function editPersonalizationHopup(productid, basketitemid) {
    openStikcyHopup("/personalization/personalizationedit.aspx?productid=" + productid + "&basketitemid=" + basketitemid, "Edit You Personalization Details", 420, true, 240);
}

function openTaxLegalHopup() {
    openHopup(0, 0, 456, 687, 'blueBolder', '', '/HelpCenter/TaxLegalHopup.aspx', true, false);
}
function openTakeFiveHopup() {
    if ($(window.document).find("#quickShop").length) {
        parent.UrlPopupWindow(640, '/HelpCenter/TakeFiveHopup.aspx', true);
    }
    else{
        openHopup(0, 0, 458, 660, 'blueBolder', '', '/HelpCenter/TakeFiveHopup.aspx', true, true);
    }
}
/*Scroll Bar of Left Menu*/
function initLeftMenuScrollBar (){
    var initScrollBarHeight = 196;
    if ($(".leftMenuList").length>0) {
        $(".leftMenuList").find(".leftMenuScrollPanel").each(function () {
	        if ($(this).height() >= initScrollBarHeight) {
	            $(this).css("height", initScrollBarHeight + "px");
	            $(this).scrollBarPanel({ showArrows: true, scrollbarWidth: 16, dragMinHeight:46, dragMaxHeight:46 });
	        }
	    });

	    //add footer solid line
	    $(".leftMenuList").find(".customScrollBar").each(function () {
	        if ($(this).find(".scrollBarPanelTrack").length > 0) {
	            $(this).addClass("scrollFooterLine");
	        } else {
	            $(this).find(".scrollBarPanelContainer").css("height", "auto");
	            $(this).find(".leftMenuScrollPanel").css("height", "auto");
	            var isSelected = true;
	        }
	    });
    }
}

//show Local Delivery Hopup and Extra-mail Item Hopup on PDP and Quickshop
function toggleDeliveryDateMessage(sku, message){
    $("#deliveryDateMessage").html("").hide();
    if(sku && sku!='' && message!="" && message!=undefined){
        $("#deliveryDateMessage").html(message);
        judgeForAddMessage();
        $("#deliveryDateMessage").show();
    }
}

function judgeForAddMessage() {
    var Extra_MIleHtml = "<span class=\"clickWindow\">\
                    	<span class=\"extraMileItemButton clickWindowButton\"></span>\
                    	<span class=\"rolloverWindow\">\
                    	    <span class=\"top\"></span>\
                    	    <span class=\"middle extraMileItemList\">\
                    	        <span class=\"extraMileItemButton\"></span><br />\
                    	        <ul>\
                    	            <li class=\"bold\">We put our warehouses near to where you live so you'll receive your order in 1-2 days.</li>\
                    	            <li> On rare occasions, your local warehouse will be out-of-stock of an item. No worries!</li>\
                    	            <li>We're happy to go that extra mile and send it to you from the next nearest warehouse for free (on any order over $49).</li>\
                    	        </ul>\
                    	    </span>\
                    	    <span class=\"bottom\"></span>\
                    	</span>\
                    </span>";
    var localServiceHtml = "<a  class=\"helpButton\" href=\"javascript:openStikcyHopup('/HelpCenter/LocalDeliveryHopup.aspx','',529,true); void(0);\"></a>";
    if ($(".shipByLocalDelivery").length >= 1) {
        $(".shipByLocalDelivery").each(function () {
            if ($(this).find(".helpButton").length == 0)
                $(this).append(localServiceHtml);
        });
    }
    $(".quickShopDeliveryMsg").removeClass("withExtraMile");
    if ($(".extraMileItemTipHopup").length >= 1) {
        $(".extraMileItemTipHopup").each(function () {
            if ($(this).find(".extraMileItemButton").length == 0)
                $(this).append(Extra_MIleHtml);
            if ($(this).parents("#quickShop").length > 0)
                $(this).parents(".quickShopDeliveryMsg").addClass("withExtraMile");
        });
    }
}

function extraMileHopupShow(obj){
    if ($(obj).parents(".groupProductItem").length > 0){//for Group
        if ($(obj).parents(".groupOtherOptions").length > 0)
            showClickWindowAutoPosition($(obj).find(".clickWindowButton"),$(obj).parents(".groupItemTable"),"all");//for the other options on Group
        else
            showClickWindowAutoPosition($(obj).find(".clickWindowButton"),"body","all");//for the top option on Group
    }
    else if ($(obj).parents(".gridProductItem").length > 0){//for Grid
        showClickWindowAutoPosition($(obj).find(".clickWindowButton"),$(obj).parents(".productItemTable"),"all");
    }
    else{
        showClickWindowAutoPosition($(obj).find(".clickWindowButton"),"body","all");//for the top option on Group
    }
    //remove the close action on hopup
    $(obj).find(".rolloverWindow").find(".closeText").attr("onclick",""); 
    //set Z-index on current hopup for IE6/7
    $(".deliveryDateMsgBox").css("z-index","0");
    $(obj).parents(".deliveryDateMsgBox").css("z-index","1");
}
