// Global Variables
//var ajaxServerUrl = "http://localhost:4470/httpdocs/BabyHavenAJAXServer.aspx";
//var ajaxServerUrl = "http://207.150.201.110/BabyHavenAJAXServer.aspx";
var ajaxServerUrl = "http://www.babyhaven.com/BabyHavenAJAXServer.aspx";
//var ajaxServerUrl = "http://207.150.201.111/BabyHavenAJAXServer.aspx";

var vItemGUId = '';

// Called when the COLOR DDL is changed
function selectColor(oDDLColor) {    
    var vDDLSizeValue = '', vDDLTypeValue = '';
    var oDDLType = $('#' + g_IDs.TypeDDLId)[0];
    var oDDLSize = $('#' + g_IDs.SizeDDLId)[0];

    if (oDDLColor.selectedIndex == 0) {
        alert('Please select Color');
        return false;
    }
    if (oDDLType != null && oDDLType != undefined && oDDLType.options.length > 0 && oDDLType.selectedIndex > 0)
        vDDLTypeValue = replaceSplChars(GetInnerText(oDDLType.options[oDDLType.selectedIndex]));
    else {
        if (oDDLType != null && oDDLType != undefined) {
            alert("Please select a Type");
            return false;
        }
    }
    if (oDDLSize != null && oDDLSize != undefined && oDDLSize.options.length > 0 && oDDLSize.selectedIndex > 0)
        vDDLSizeValue = replaceSplChars(GetInnerText(oDDLSize.options[oDDLSize.selectedIndex]));
    else {
        if (oDDLSize != null && oDDLSize != undefined) {
            alert("Please select a Size");
            return false;
        }
    }

    var reqXml = '<reqXml Id="3" item_guid="' + g_IDs.ItemGUId + '"><variation name="Color" value="'
            + replaceSplChars(GetInnerText(oDDLColor.options[oDDLColor.selectedIndex])) + '"';

    if (vDDLTypeValue != '') {
        reqXml = reqXml + ' type_value = "'
        + vDDLTypeValue + '"';
    }
    else
        reqXml = reqXml + ' type_value = ""';

    if (vDDLSizeValue != '') {
        reqXml = reqXml + ' size_value = "'
        + vDDLSizeValue + '"';
    }
    else
        reqXml = reqXml + ' size_value = ""';
    reqXml = reqXml + '></variation></reqXml>';

    $.ajax({
        url: ajaxServerUrl
        , type: "POST"
        , contentType: "text/xml"
        , processData: false
        , data: reqXml
        , dataType: "xml"
        , success: function(response) {            
            populateItemOptions(response.documentElement);
        }
    });
}

function nonMasterChangeMainImage(medImageUrl, bigImageUrl) {
    //Set the main image
    var imgMediumImage = $('#' + g_IDs.MediumImage)[0];
    imgMediumImage.src = medImageUrl;

    //Set the full image
    var lnkFullImage = $('#' + g_IDs.FullImage)[0];
    lnkFullImage.href = bigImageUrl;
    var lnkFullImage1 = $('#' + g_IDs.FullImage1)[0];
    lnkFullImage1.href = bigImageUrl;
}

function reloadImageUrls(aSmallImageUrl, aMediumImageUrl, aBigImageUrl) {
    var maxColumns = 14;
    var columns = 0;
    var tableHtml = "<table width='100%'><tr>";
    var MorePhotos = $("#MorePhotos")[0];
    if ((aSmallImageUrl !== undefined) && (aSmallImageUrl !== null)) {
        if (aSmallImageUrl.length != 0) {
            if (aSmallImageUrl.length == 1) {
                MorePhotos.style.display = "none";
            }
            else {
                for (var i = 0; i < aSmallImageUrl.length; i++) {
                    if (columns > maxColumns) {
                        tableHtml = tableHtml + "</tr><tr style='height:108px'>";
                        columns = 0;
                    }

                    tableHtml += "<td><img src='" + aSmallImageUrl[i] +
                         "' onmouseover='javascript:nonMasterChangeMainImage(\"" +
                         aMediumImageUrl[i] + "\",\"" + aBigImageUrl[i] +
                         "\");' /></td>";

                    columns = columns + 1;
                }

                tableHtml += "</tr></table>";
                //change on 9/4/2009 by jrose
                //created reference to div with id divThumbnails, and assigned tableHTML to it
                var myDiv = $("#divThumbnails");
                myDiv.innerHTML = tableHtml;
            }

            //Set the first image as the default
            var lnkFullImage = $('#' + g_IDs.FullImage)[0];
            lnkFullImage.href = aBigImageUrl[0];

            var lnkFullImage1 = $('#' + g_IDs.FullImage1)[0];
            lnkFullImage1.href = aBigImageUrl[0];

            var imgMediumImage = $('#' + g_IDs.MediumImage)[0];
            imgMediumImage.src = aMediumImageUrl[0];
            var lnkMain = $('#' + g_IDs.MainLink)[0];
            lnkMain.href = aBigImageUrl[0];
            lnkMain.rev = aMediumImageUrl[0];

            // Updating the Magic Zoom
            MagicZoom.update(lnkFullImage, aBigImageUrl[0], aMediumImageUrl[0], 'show-title: false');
        }
        else {
            //TODO: No image?
        }
    }
}

//function populateItemOptions(resXmlRoot) {
//    var oHdnItemGUId = $('#' + g_IDs.CartItemGUId)[0];
//    var oItemRegPrice = $('#' + g_IDs.RetailPrice)[0];
//    var oItemSalePrice = $('#' + g_IDs.Price)[0];
//    var oYouSavePrice = $('#' + g_IDs.YouSavePrice)[0];
//    var nodeItemData = resXmlRoot.firstChild;
//    var nodeItemImages = resXmlRoot.getElementsByTagName("item_images")[0];
//    
//    oHdnItemGUId.value = nodeItemData.getAttribute("item_guid");
//    SetInnerText(oItemRegPrice, nodeItemData.getAttribute("item_reg_price"));
//    SetInnerText(oItemSalePrice, nodeItemData.getAttribute("item_sale_price"));
//    SetInnerText(oYouSavePrice, nodeItemData.getAttribute("you_save_price") + ' (' + nodeItemData.getAttribute("you_save_percentage") + '%)');

//    // Loading Images for the Variation Items
//    var imgMain = $('#' + g_IDs.MediumImage)[0];
//    var lnkFullImage = $('#' + g_IDs.FullImage)[0];
//    var lnkFullImage1 = $('#' + g_IDs.FullImage1)[0];
//    var lnkMain = $('#' + g_IDs.MainLink)[0];
//    var nodeImageMain = nodeItemImages.getElementsByTagName("main_image");
//    var newImageUrl = '';
//    if (nodeImageMain != null && nodeImageMain != undefined) {
//        //imgMain[0].src = nodeImageMain[0].getAttribute("image_url");
//        newImageUrl = nodeImageMain[0].getAttribute("image_url");
//        aMediumImageUrl[0] = newImageUrl;
//        aBigImageUrl[0] = newImageUrl.substring(0, newImageUrl.length - 1) + '2';
//        aSmallImageUrl[0] = newImageUrl.substring(0, newImageUrl.length - 1) + '0';
//        reloadImageUrls(aSmallImageUrl, aMediumImageUrl, aBigImageUrl);
//    }
//}

function populateItemOptions(resXmlRoot) {
    var oHdnItemGUId = $('#' + g_IDs.CartItemGUId)[0];
    var oItemRegPrice = $('#' + g_IDs.RetailPrice)[0];
    var oItemSalePrice = $('#' + g_IDs.Price)[0];
    var oYouSavePrice = $('#' + g_IDs.YouSavePrice)[0];
    var nodeItemData = resXmlRoot.firstChild;
    var nodeItemImages = resXmlRoot.getElementsByTagName("item_images")[0];
    
    
    if (nodeItemData != null && nodeItemData != undefined){
        var itemGuid = nodeItemData.getAttribute("item_guid");
        var regPrice = nodeItemData.getAttribute("item_reg_price");
        var salePrice = nodeItemData.getAttribute("item_sale_price");
        var youSavePrice = nodeItemData.getAttribute("you_save_price");
        var youSavePer = nodeItemData.getAttribute("you_save_percentage");
        
        if(itemGuid != null && itemGuid != undefined)
            oHdnItemGUId.value = itemGuid;
        SetInnerText(oItemRegPrice, regPrice);
        SetInnerText(oItemSalePrice, salePrice);
        if(youSavePrice != null && youSavePrice != undefined && youSavePer != null && youSavePer != undefined)
            SetInnerText(oYouSavePrice, youSavePrice + ' (' + youSavePer + '%)');
    }
    
    
    // Loading Images for the Variation Items 
    if(nodeItemImages != null && nodeItemImages != undefined)   {  
        var nodeImageMain = nodeItemImages.getElementsByTagName("main_image");
        if (nodeImageMain != null && nodeImageMain != undefined){
            var imgMain = $('#' + g_IDs.MediumImage)[0];
            var lnkFullImage = $('#' + g_IDs.FullImage)[0];
            var lnkFullImage1 = $('#' + g_IDs.FullImage1)[0];
            var lnkMain = $('#' + g_IDs.MainLink)[0];
        
            
            var newImageUrl = '';
            if (nodeImageMain != null && nodeImageMain != undefined) {
                //imgMain[0].src = nodeImageMain[0].getAttribute("image_url");
                newImageUrl = nodeImageMain[0].getAttribute("image_url");
                aMediumImageUrl[0] = newImageUrl;
                aBigImageUrl[0] = newImageUrl.substring(0, newImageUrl.length - 1) + '2';
                aSmallImageUrl[0] = newImageUrl.substring(0, newImageUrl.length - 1) + '0';
                reloadImageUrls(aSmallImageUrl, aMediumImageUrl, aBigImageUrl);
            }
        }
    }
}


// This function posts the request for adding the item to the cart
function addToCart() {
    var oHdnItemGUId = $('#' + g_IDs.CartItemGUId)[0];
    var oTxtQuantity = $('#' + g_IDs.Quantity)[0];
    var oDDLType = $('#' + g_IDs.TypeDDLId)[0];
    var oDDLSize = $('#' + g_IDs.SizeDDLId)[0];
    var oDDLColor = $('#' + g_IDs.ColorDDLId)[0];

    if (oDDLType != null && oDDLType != undefined) {
        if (oDDLType.selectedIndex == 0) {
            alert("Please select a Type");
            return false;
        }
    }

    if (oDDLSize != null && oDDLSize != undefined) {
        if (oDDLSize.selectedIndex == 0) {
            alert("Please select a Size");
            return false;
        }
    }

    if (oDDLColor != null && oDDLColor != undefined) {
        if (oDDLColor.selectedIndex == 0) {
            alert("Please select a Color");
            return false;
        }
    }

    if (oTxtQuantity != null && oTxtQuantity != undefined && oTxtQuantity.value == '') {
        alert("Please enter the Quantity");
        return false;
    }

    // Creating Request XML for AddToCart
    var reqXml = '<reqXml Id="4" item_guid="' + oHdnItemGUId.value + '"'
    reqXml = reqXml + '><item_data';
    reqXml = reqXml + ' quantity="' + oTxtQuantity.value + '"';
    reqXml = reqXml + ' /></reqXml>';

    $.ajax({
        url: ajaxServerUrl
        , type: "POST"
        , contentType: "text/xml"
        , processData: false
        , data: reqXml
        , dataType: "xml"
        , success: function(response) {
            var xmlResponse = response.documentElement;
            if (xmlResponse != null && xmlResponse != undefined) {
                if (xmlResponse.getAttribute("result") == "success") {
                    window.location.href = "/cart.aspx";
                    return false;
                }
                else if (xmlResponse.getAttribute("result") == "no_stock") {
                    //oTxtQuantity.value = xmlResponse.getAttribute("curr_qty_return");
                    alert(xmlResponse.getAttribute("message"));
                }
                else {
                    alert("There is a problem while adding the item to the cart. Please contact BabyHavens support");
                    return false;
                }
            }
            else {
                alert("There is a problem while adding the item to the cart. Please contact BabyHavens support");
                return false;
            }
        }
    });
}

function ClearAndPopulateDDL(resXmlRoot, pObjDDL, pNodeName) {
    if (pObjDDL != null && pObjDDL != undefined) {
        for (var count = pObjDDL.options.length - 1; count > -1; count--) {
            pObjDDL.options[count] = null;
        }
        var ddlNodes = resXmlRoot.getElementsByTagName(pNodeName);
        var ddlValue, ddlText;
        var optionItem, optionNode;        
        for (var iCounter = 0; iCounter < ddlNodes[0].childNodes.length; iCounter++) {
            optionNode = ddlNodes[0].childNodes[iCounter];
            ddlValue = optionNode.getAttribute("value");
            ddlText = optionNode.getAttribute("text");
            optionItem = new Option(ddlText, ddlValue, false, false);
            pObjDDL.options[pObjDDL.length] = optionItem;
        }
    }
}

function replaceSplChars(pInputString) {
    var vOutputString = pInputString;
    while (vOutputString.indexOf('"') != -1) {
        vOutputString = vOutputString.replace("\"", "DQ");
        //Code Modified By Tejas [1038] to Handle special characters exception on 12/31/2010
        vOutputString = vOutputString.replace("\'", "SSQQ");
        //Ends here
    }
    vOutputString = vOutputString.replace("&", "AANNDD");
    return vOutputString;
}

// Called when the TYPE DDL is changed
function selectType(oDDLType) {
    var oDDLSize;
    var ddlValue, ddlText;
    var optionItem;
    oDDLSize = $('#' + g_IDs.SizeDDLId);

    if (oDDLType.selectedIndex == 0) {
        alert('Please select Type');
        // Clearing the SIZE DDL if any        
        if (oDDLSize != null && oDDLSize != undefined && oDDLSize.options != null && oDDLSize.options != undefined) {
            for (var count = oDDLSize.options.length - 1; count > -1; count--) {
                oDDLSize.options[count] = null;
            }
            ddlValue = "0";
            ddlText = " - Select - ";
            optionItem = new Option(ddlText, ddlValue, false, false);
            oDDLSize.options[oDDLSize.length] = optionItem;
        }
        return false;
    }
    //Code added by TEJAS[TSI-100] on 07-May-2010 - Start
    var type = replaceSplChars(GetInnerText(oDDLType.options[oDDLType.selectedIndex]));
    type = type.replace("\&","A1N1D1");
    //Code added by TEJAS[TSI-100] on 07-May-2010 - End
    var reqXml = '<reqXml Id="1" item_guid="' + g_IDs.ItemGUId + '"><variation name="Type" value="'
            + type + '"';
    reqXml = reqXml + '></variation></reqXml>'

    $.ajax({
        url: ajaxServerUrl
        , type: "POST"
        , contentType: "text/xml"
        , processData: false
        , data: reqXml
        , dataType: "xml"
        , success: function(response) {
            var xmlResponse = response.documentElement;
            var iRecordCount = parseInt(xmlResponse.getAttribute("record_count"));            
            if (iRecordCount > 0) {
                var loadDDL = xmlResponse.getAttribute("loadDDL");
                if(loadDDL == "SIZE"){                
                    var oDDLSize = $('#' + g_IDs.SizeDDLId)[0];
                    if (oDDLSize != null && oDDLSize != undefined)
                        ClearAndPopulateDDL(xmlResponse, oDDLSize, "Sizes");                
                    else
                        populateItemOptions(xmlResponse);
                }
                else if(loadDDL == "COLOR"){                
                    var oDDLColor = $('#' + g_IDs.ColorDDLId)[0];
                    if (oDDLColor != null && oDDLColor != undefined)
                        ClearAndPopulateDDL(xmlResponse, oDDLColor, "Colors");                
                    else
                        populateItemOptions(xmlResponse);
                }
                else
                    populateItemOptions(xmlResponse);
            }
        }
    });
}

// Called when the SIZE DDL is changed
function selectSize(oDDLSize) {
    var oDDLType, oDDLColor;
    var ddlValue, ddlText;
    var optionItem;
    var vDDLTypeValue = '';
    oDDLColor = $('#' + g_IDs.ColorDDLId)[0];
    oDDLType = $('#' + g_IDs.TypeDDLId)[0];

    if (oDDLSize.selectedIndex == 0) {
        alert('Please select Size');
        // Clearing the COLOR DDL if any
        if (oDDLColor != null && oDDLColor != undefined) {
            for (var count = oDDLColor.options.length - 1; count > -1; count--) {
                oDDLColor.options[count] = null;
            }
            ddlValue = "0";
            ddlText = " - Select - ";
            optionItem = new Option(ddlText, ddlValue, false, false);
            oDDLColor.options[oDDLColor.length] = optionItem;
        }
        return false;
    }
    var reqXml = '<reqXml Id="2" item_guid="' + g_IDs.ItemGUId + '"><variation name="Size" value="'
            + replaceSplChars(GetInnerText(oDDLSize.options[oDDLSize.selectedIndex])) + '"';

    if (oDDLType != null &&
            oDDLType != undefined &&
                oDDLType.options.length > 0 &&
                    oDDLType.selectedIndex > 0) {
        vDDLTypeValue = replaceSplChars(GetInnerText(oDDLType.options[oDDLType.selectedIndex]));
    }
    else {
        if (oDDLType != null && oDDLType != undefined) {
            alert("Please select a Type");
            return false;
        }
    }

    if (vDDLTypeValue != '') {
        reqXml = reqXml + ' type_value = "'
        + vDDLTypeValue + '"';
    }
    else
        reqXml = reqXml + ' type_value = ""';
    reqXml = reqXml + '></variation></reqXml>'

    $.ajax({
        url: ajaxServerUrl
        , type: "POST"
        , contentType: "text/xml"
        , processData: false
        , data: reqXml
        , dataType: "xml"
        , success: function(response) {
            var xmlResponse = response.documentElement;
            var iRecordCount = parseInt(xmlResponse.getAttribute("record_count"));
            if (iRecordCount > 0) {
                if (oDDLColor != null && oDDLColor != undefined)
                    ClearAndPopulateDDL(xmlResponse, oDDLColor, "Colors");
                else
                    populateItemOptions(xmlResponse);
            }
        }
    });
}

//Returns the node text value 
function SetInnerText(node, text) {
    if (node != null && node != undefined && text != null && text != undefined) {
        if (node.textContent != null && node.textContent != undefined)
            node.textContent = text;
        if (node.innerText != null && node.innerText != undefined)
            node.innerText = text;
        if (node.text != null && node.text != undefined)
            node.text = text;
    }
}

//Assigns the node text content
function GetInnerText(node) {
    return (node.textContent || node.innerText || node.text);
}

// Setting the drop down lists using the value instead of index
function SelectDDL(objDDL, ddlValue) {
    var iDDLIndex;
    for (iDDLIndex = 0; iDDLIndex < objDDL.length; ++iDDLIndex) {
        if (objDDL[iDDLIndex].value == ddlValue)
            objDDL.selectedIndex = iDDLIndex;
    }
}

// Function that Checks for the Numeric Value being Keyed in by the user
function checkNumeric(e) {
    var kc
    if (window.Event)
        kc = window.event.keyCode
    else
        kc = e.which
    if ((kc >= 48) && (kc <= 57) || kc == 8)
        return true
    else
        return false
}

function updateCartItem(orderItemGUId, itemGuid, idTxtQuantity, currQty) {
    // Creating Request XML for Update Cart Item
    var zip = $('#txtShipZipPostal').val().trim();
    var shipCountry = GetDDLSelectedValue("ddlCountry");
    var internationalShipping = $('#hdnInternationalShipping').val();

    var selectedShipMethodId = "";
    if (zip != ZIP_CODE_TEXT && zip != "")
        selectedShipMethodId = $('#ddlShippingMethods').val();
    else if (shipCountry > 0)
        selectedShipMethodId = $('#ddlShippingMethods2').val();

    var txtQty = $('#' + idTxtQuantity)[0];    
    var reqXml = $.format('<reqXml Id=\"6\" order_item_guid=\"{0}\" order_item_quantity=\"{1}\" zip=\"{2}\" shipCountry=\"{3}\" internationalShipping=\"{4}\" selectedShipMethodId=\"{5}\" itemGuid=\"{6}\" currentQty=\"{7}\"></reqXml>', orderItemGUId, txtQty.value, zip, shipCountry, internationalShipping, selectedShipMethodId, itemGuid, currQty);
    $.ajax({
        url: ajaxServerUrl
        , type: "POST"
        , contentType: "text/xml"
        , processData: false
        , data: reqXml
        , dataType: "xml"
        , beforeSend: function() {
            ShowProgress();
        }
        , success: function(response) {
            var xmlResponse = response.documentElement;
            var dlCart = $("#dlCart");
            var iCartRowCounter = 0;
            if (xmlResponse != null && xmlResponse != undefined) {
                if (xmlResponse.getAttribute("result") == "success") {
                    // Clearing the table before binding it with the new data
                    $("#dlCart tr").each(function() {
                        ++iCartRowCounter;
                        if (iCartRowCounter > 1)
                            $(this).remove();
                    });
                    refreshCart(dlCart, xmlResponse);

                    if (zip != ZIP_CODE_TEXT && zip != "") {
                        $('#txtShipZipPostal').val(zip);
                        bindShippingMethodsByZip(xmlResponse);
                        updateTotal(xmlResponse);
                    }
                    else if (shipCountry > 0) {
                        SetDDLSelectedValue("ddlCountry", shipCountry);
                        ConvertToImageDdl();
                        bindShippingMethodsByCountry(xmlResponse);
                        updateTotal(xmlResponse);
                    }
                }
                else if (xmlResponse.getAttribute("result") == "no_stock") {
                    txtQty.value = currQty;
                    alert(xmlResponse.getAttribute("message"));
                }
            }
        }
        , complete: function() {
            HideProgress();
        }
    });
}

function deleteCartItem(orderItemGUId) {
    // Creating Request XML for Delete Cart Item
    var reqXml = $.format('<reqXml Id=\"7\" order_item_guid=\"{0}\"></reqXml>', orderItemGUId);
    $.ajax({
        url: ajaxServerUrl
        , type: "POST"
        , contentType: "text/xml"
        , processData: false
        , data: reqXml
        , dataType: "xml"
        , beforeSend: function() {
            ShowProgress();
        }
        , success: function(response) {
            var xmlResponse = response.documentElement;
            var dlCart = $("#dlCart");
            var iCartRowCounter = 0;
            if (xmlResponse != null && xmlResponse != undefined) {
                // Clearing the table before binding it with the new data
                $("#dlCart tr").each(function() {
                    ++iCartRowCounter;
                    if (iCartRowCounter > 1)
                        $(this).remove();
                });
                refreshCart(dlCart, xmlResponse);
            }
        }
        , complete: function() {
            HideProgress();
        }
    });
}

function refreshCart(dlCart, cartResponse) {
    if (cartResponse.getAttribute("totalItems") == 0) {
        btnCheckout.css({ "display": "none" });
        btnCheckout1.css({ "display": "none" });
        btnPayPal.css({ "display": "none" });
        tblCart.css({ "display": "none" });
        trCongrats.css({ "display": "none" });
        divEmpty.css({ "display": "" });
        return true;
    }
    var cartRow = null, cartSummaryRow = null;
    var cartColQuantity, cartColItemDesc, cartColUnitPrice, cartColTotal;
    var removeBtnTableOuter = null, removeBtnTableInner = null;
    var removeBtnOuterTableRow = null, removeBtnInnerTableRow = null;
    var removeBtnOuterTableCell = null, removeBtnInnerTableCell = null;
    var descTable = null, descTableRow = null;
    var descTableImageColumn = null, descTableDescColumn = null, descTableDescColumnInnerTable = null;
    var tableCell = null;
    var hdnOrderItemGuId = null, hdnItemGuId = null;
    var txtQuantity = null, btnUpdate = null, btnRemove = null, imgPhoto = null, lnkItemDesc = null;
    if (dlCart == null || dlCart.length < 1) return;
    var iItmCounter = 0;
    var sHTML = '';
    var numericValidation = '';

    // Looping through the Cart Items and framing the CartView table dynamically
    $(cartResponse).find("mf_order_items").each(function() {
        ++iItmCounter;
        cartRow = $("<tr style='white-space: nowrap;'>");
        // Column1 : Quantity
        cartColQuantity = $("<td class=\"qtpadding\" align=\"center\" valign=\"top\" style=\"width:110px;\">")
        sHTML = '';
        sHTML += $.format("<input type=\"hidden\" name=\"hdnLineGuid_{0}\" id=\"hdnLineGuid_{0}\" value=\"{1}\" />", iItmCounter, $(this).find("order_item_guid").text());
        sHTML += $.format("<input type=\"hidden\" name=\"hdnItemGuid_{0}\" id=\"hdnItemGuid_{0}\" value=\"{1}\" />", iItmCounter, $(this).find("item_guid").text());
        sHTML += $.format("<input name=\"txtQty_{0}\" type=\"text\" value=\"{1}\" maxlength=\"5\" size=\"2\" id=\"txtQty_{0}\" /><br />", iItmCounter, $(this).find("order_item_quantity").text());
        numericValidation += $.format("AddNumericValidations(document.getElementById('txtQty_{0}'),0,0,0,0,0,'');", iItmCounter);
        sHTML += $.format("<input type=\"image\" name=\"btnUpdate_{0}\" id=\"btnUpdate_{0}\" title=\"Update Cart\" src=\"http://www.babyhaven.com/images/design/buttons/btn_update.gif\" align=\"middle\" style=\"border-width:0px;\" onclick=\"updateCartItem('{1}','{2}','txtQty_{0}','{3}');return false;\" />", iItmCounter, $(this).find("order_item_guid").text(), $(this).find("item_guid").text(), $(this).find("order_item_quantity").text());
        sHTML += "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" align=\"Center\"><tr><td align=\"Center\" style=\"padding-top:5px;\">";
        sHTML += "<table cellspacing=\"0\" cellpadding=\"0\" align=\"Center\" border=\"0\" style=\"border-collapse:collapse;\">";
        sHTML += $.format("<tr><td id=\"tcRemove_{0}\" align=\"center\" valign=\"middle\" style=\"white-space:nowrap;\">", iItmCounter);
        sHTML += $.format("<input type=\"image\" name=\"bRemove_{0}\" id=\"bRemove_{0}\" title=\"Remove\" class=\"checkoutremove\" src=\"http://www.babyhaven.com/images/design/buttons/btn_remove.gif\" alt=\"Remove\" align=\"middle\" style=\"border-width:0px;\" onclick=\"deleteCartItem('{1}');return false;\" /></td></tr></table></td></tr></table></td>", iItmCounter, $(this).find("order_item_guid").text());

        cartColQuantity.html(sHTML);
        cartColQuantity.appendTo(cartRow);
        // Column1 : Quantity - Ends

        // Column2 : Item Descrition - Starts
        cartColItemDesc = $("<td align=\"center\" valign=\"top\" style=\"width:385px;\">");
        sHTML = '';
        sHTML += "<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" style=\"width: 110px; border-collapse: collapse;\">";
        sHTML += "<tbody><tr><td valign=\"top\" style=\"padding-right:40px;\">";
        sHTML += $.format("<img id=\"imgPhoto_(0)\" src=\"http://www.babyhaven.com/mainstreet/get_image.aspx?domain=strollerbabies.com&amp;item_guid={1}&amp;size=0\"", iItmCounter, $(this).find("item_guid").text());
        sHTML += " style=\"width: 60px; border-width: 0px;\" /></td>";
        sHTML += "<td><table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" width=\"275\">";
        sHTML += "<tbody><tr><td style=\"padding: 10px 0px;\">";
        sHTML += "<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" style=\"border-collapse: collapse;\">";
        sHTML += "<tbody><tr><td style=\"width: 275px;\">";
        //        sHTML += $.format("<a id=\"lnkItemDesc_{0}\"", iItmCounter);
        //        sHTML += $.format(" href=\"#\" style=\"color: #AD4898; font-family: tahoma; font-size: 8pt; font-weight: bold; text-decoration: none;\">{0}</a></td>", $(this).find("order_item_description").text());
        //        sHTML += "</tr></tbody></table></td></tr><tr><td style=\"padding-bottom: 10px;\" class=\"checkoutav\"></td></tr>";
        //        sHTML += "<tr><td></td></tr><tr><td style=\"padding: 3px 0px;\" class=\"checkoutcolor\">";
        //        sHTML += $.format("SKU&nbsp;#&nbsp; <strong><span id=\"lblSKU_{0}\">{1}</span></strong></td></tr>", iItmCounter, $(this).find("order_item_cd").text());
        //        sHTML += "<tr><td style=\"padding: 3px 0px;\" class=\"checkoutcolor\">";
        //        sHTML += $.format("Color:&nbsp; <strong><span id=\"lblColor_{0}\">{1}</span></strong></td></tr>", iItmCounter, $(this).find("order_item_color").text());
        //        sHTML += "<tr><td style=\"padding-top: 18px; padding-bottom: 5px;\" class=\"checkoutstock\"></td></tr></tbody></table></td></tr></table>";
        sHTML += $.format("<a id=\"lnkItemDesc_{0}\"", iItmCounter);
        sHTML += $.format(" href=\"{1}\" style=\"color: #AD4898; font-family: tahoma; font-size: 8pt; font-weight: bold; text-decoration: none;\">{0}</a></td>", $(this).find("order_item_description").text(), $(this).find("item_navigate_url").text());
        sHTML += "</tr></tbody></table></td></tr>";
        if ($(this).find("item_qty_text").text().trim() != "") {
            sHTML += $.format("<tr><td style=\"padding-bottom: 10px;\" class=\"checkoutav\">{0}</td></tr>", $(this).find("item_qty_text").text());
        }
        sHTML += "<tr><td></td></tr><tr><td style=\"padding: 3px 0px;\" class=\"checkoutcolor\">";
        sHTML += $.format("SKU&nbsp;#&nbsp; <strong><span id=\"lblSKU_{0}\">{1}</span></strong></td></tr>", iItmCounter, $(this).find("order_item_cd").text());
        if ($(this).find("order_item_color").text().trim() != "") {
            sHTML += "<tr><td style=\"padding: 3px 0px;\" class=\"checkoutcolor\">";
            sHTML += $.format("Color:&nbsp; <strong><span id=\"lblColor_{0}\">{1}</span></strong></td></tr>", iItmCounter, $(this).find("order_item_color").text());
        }
        if ($(this).find("order_item_size").text().trim() != "") {
            sHTML += "<tr><td style=\"padding: 3px 0px;\" class=\"checkoutcolor\">";
            sHTML += $.format("Size:&nbsp; <strong><span id=\"lblSize_{0}\">{1}</span></strong></td></tr>", iItmCounter, $(this).find("order_item_size").text());
        }
        if ($(this).find("item_stock_text").text().trim() != "") {
            sHTML += $.format("<tr><td style=\"padding-top: 18px; padding-bottom: 5px;\" class=\"checkoutstock\">{0}</td></tr>", $(this).find("item_stock_text").text());
        }
        sHTML += "</tbody></table></td></tr></table>";


        cartColItemDesc.html(sHTML);
        cartColItemDesc.appendTo(cartRow);
        // Column2 : Item Descrition - Ends

        // Column3 : Unit Price - Starts
        cartColUnitPrice = $("<td align=\"center\" valign=\"top\" style=\"color: #837E7B; font-family: tahoma; font-size: 8pt; font-weight: bold; width: 110px;\">");
        cartColUnitPrice.text($(this).find("order_item_unit_price").text());
        cartColUnitPrice.appendTo(cartRow);
        // Column3 : Unit Price - Ends

        // Column3 : Total - Starts
        cartColTotal = $("<td align=\"center\" valign=\"top\" style=\"color: #837E7B; font-family: tahoma; font-size: 8pt; font-weight: bold; width: 110px;\">");
        cartColTotal.text($(this).find("order_item_extended_price").text());
        cartColTotal.appendTo(cartRow);
        // Column3 : Total - Ends        

        cartRow.appendTo(dlCart);

        var numericScript = $.format("<script language=\"javascript\" type=\"text/javascript\">{0}</script>", numericValidation);
        $('#numericScript').html(numericScript);
    });

    // Appending the CartShipping and CartAmountSummary Panel
    cartSummaryRow = $("<tr>");
    sHTML = '';
    sHTML += "<td colSpan=\"4\" style=\"background-color: #f4f4f4; padding: 10px;\">";
    sHTML += "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\">";
    sHTML += "<tr><td class=\"cartShipbg\" style=\"width: 289px; height: 167px; padding-left: 15px; padding-top: 10px\" valign=\"top\">";
    sHTML += "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"289\">";
    sHTML += "<tr><td class=\"cartCalShip\" style=\"padding-bottom: 5px;\">Calculate Shipping:</td></tr>";
    sHTML += "<tr><td><div><table id=\"tblShipByZip\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">";
    sHTML += "<tr><td><input name=\"txtShipZipPostal\" type=\"text\" value=\"US Shipping Zip Code\"";
    sHTML += " maxlength=\"5\" id=\"txtShipZipPostal\" class=\"cartCalShiptxt\" onclick=\"javascript:HideWaterMark(this);\" onblur=\"javascript:ShowWaterMark(this);\" /></td>";
    sHTML += "<td><input type=\"image\" name=\"btnShipUpdate\" id=\"btnShipUpdate\" onclick=\"javascript:return loadShippingMethodsByZip();\" src=\"images/btn-cartship-update.gif\" alt=\"Update\"";
    sHTML += " onclick=\"javascript:return onClick_updateShipping();\" style=\"border-width: 0px;\" /></td></tr>";
    sHTML += "<tr><td colspan=\"2\"><select name=\"ddlShippingMethods\" id=\"ddlShippingMethods\" onchange=\"javascript:updateShipping(this.id);\" class=\"cartCalShiptxt\"></select></td></tr></table></div></td></tr>";
    sHTML += "<tr><td style=\"height: 15px;\"></td></tr><tr><td class=\"cartShipOut\">Shipping Outside of the United States?</td></tr>";
    sHTML += "<tr><td><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr><td><select name=\"ddlCountry\" id=\"ddlCountry\" onchange=\"javascript:return loadShippingMethodsByCountry();\" class=\"cartCalShiptxt\" style=\"width: 210px;\">";
    // Loading the Country DropDown
    sHTML += $.format("<option value=\"{0}\">{1}</option>", "0", " -- Select Country -- ");
    $(cartResponse).find("Countries").each(function() {
        sHTML += $.format("<option value=\"{0}\" title=\"{2}\">{1}</option>", $(this).find("country_id").text(), $(this).find("country_label").text(), $.format("http://www.babyhaven.com/images/flags/{0}.gif", $(this).find("country_cd").text()));
    });
    sHTML += "</select></td><td><img src=\"http://www.babyhaven.com/images/globe.gif\" alt=\"Globe\" /></td></tr><tr><td colspan=\"2\"><select name=\"ddlShippingMethods2\" id=\"ddlShippingMethods2\" onchange=\"javascript:updateShipping(this.id);\" class=\"cartCalShiptxt\">";
    sHTML += "</select></td></tr></table></td></tr></table></td><td style=\"width: 50px;\"></td><td valign=\"top\" style=\"width: 360px;\">";
    sHTML += "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"line-height: 20px;\"><tr><td style=\"height: 10px;\" colspan=\"2\"></td></tr>";
    sHTML += "<tr><td style=\"width: 250px;\"><span id=\"lblSubTotal\" class=\"cartNewSubTotal\">Sub Total:</span><br />";
    sHTML += "<span id=\"lblStdShipping\" class=\"cartNewSubTotal\" style=\"text-decoration: underline;\">Standard Shipping:</span></td>";
    sHTML += $.format("<td style=\"width: 90px;\" align=\"right\"><span id=\"lblSubTotalPrice\" class=\"cartNewSubTotal\">{0}</span><br />", $(cartResponse).find("mf_orders").find("custom_order_sub_total").text());
    sHTML += "<span id=\"lblStdShipPrice\" class=\"cartNewSubTotal\">Enter Location</span></td></tr><tr><td style=\"height: 10px;\" colspan=\"2\"></td></tr>";

    sHTML += "<tr id=\"trSpecialPrice\" style=\"display:none;\"><td class=\"cartSpecialPrice\">Special Offer: Add&nbsp;<label id=\"lblSpecialPrice\" class=\"cartSpecialPrice\"></label>&nbsp;";
    sHTML += "to your order and qualify for FREE Standard Shipping <a class=\"cartSpecialPrice\" style=\"color:black;text-decoration:underline;\" href=\"#\" onclick=\"javascript:ShowTopUp();return false;\" toptions=\"layout=dashboard\">details</a>";
    sHTML += "<div id=\"divFreeShip\" style=\"display:none;background-color:White;padding:15px;font-family:Verdana;\">";
    sHTML += "Any order over $100 is eligible for free ground shipping in the continental United States.</div></td><td></td></tr>";

    sHTML += "<tr><td style=\"height: 10px;\" colspan=\"2\"></td></tr><tr><td colspan=\"2\" class=\"dotlinecart\"></td></tr>";
    sHTML += "<tr><td style=\"height: 10px;\" colspan=\"2\"></td></tr><tr><td class=\"cartNewTotal\">Total:</td>";
    sHTML += $.format("<td align=\"right\"><span id=\"lblCartTotal\" class=\"cartNewTotal\">{0}</span></td></tr><tr><td>&nbsp;</td></tr><tr><td align=\"left\" colspan=\"2\"><label id=\"lblDiscountMsg\" style=\"color:red;\">{1}</label></td></tr></table></td></tr>", $(cartResponse).find("mf_orders").find("custom_order_total").text(), cartResponse.getAttribute("giftText"));

    $('#hdnInternationalShipping').val(cartResponse.getAttribute("internationalShipping"));

    cartSummaryRow.html(sHTML);
    cartSummaryRow.appendTo(dlCart);
    // Converting the Country DropDown into Image DropDown using jQuery library
    ConvertToImageDdl();
    SetFreeShippingText(cartResponse);
}

function ConvertToImageDdl() {
    $('#ddlCountry').css("display", "");
    $('#ddlCountry').msDropDown();

    if ($.browser.msie)
        $('#ddlCountry_title').css("height", "24px");

    $('#ddlCountry').css("display", "none");
}

//Code added by TEJAS[TSI-1033] on 30-March-2010 - Start

//Get Shipping Methods XML Asynchronously by Zip code and bind in DropDownList
function loadShippingMethodsByZip() {
    // Creating Request XML for Load Shipping Methods and update the total
    var zip = $('#txtShipZipPostal').val();
    if (zip.trim() == "" || zip == ZIP_CODE_TEXT) {
        alert("Enter Shipping Zip Code");
        return false;
    }
    var internationalShipping = $('#hdnInternationalShipping').val();

    var reqXml = $.format('<reqXml Id=\"8\" zip=\"{0}\" internationalShipping=\"{1}\"></reqXml>', zip, internationalShipping);
    $.ajax({
        url: ajaxServerUrl
        , type: "POST"
        , contentType: "text/xml"
        , processData: false
        , data: reqXml
        , dataType: "xml"
        , beforeSend: function() {
            ShowProgress();
        }
        , success: function(response) {
            var xmlResponse = response.documentElement;
            SetDDLSelectedValue("ddlCountry", "0"); ConvertToImageDdl();
            ClearDDL("ddlShippingMethods2");
            if (xmlResponse != null && xmlResponse != undefined) {
                if (xmlResponse.getAttribute("result") == "success") {
                    ClearDDL("ddlShippingMethods");
                    if (xmlResponse.getAttribute("international_shipping") == "yes") {
                        alert(internationalShippingMsg);
                    }
                    else {
                        bindShippingMethodsByZip(xmlResponse);
                        updateTotal(xmlResponse);
                    }
                    return true;
                }
                else {
                    alert("There is a problem while loading Shipping Methods. Please contact BabyHavens support");
                    return false;
                }
            }
        }
        , complete: function() {
            HideProgress();
        }
    });
    return false;
}

//Load Shipping Methods from XML Response which genreated by given ZIP code
function bindShippingMethodsByZip(xmlResponse) {
    BindDDLFromXml(
        xmlResponse, "DT_ShippingMethods", "ddlShippingMethods",
        "shipping_method_description_ext", "shipping_method_id", null
    );
    SetDDLSelectedValueFromXML(xmlResponse, "defaultSelected", "ddlShippingMethods");
    SetFreeShippingText(xmlResponse);
}

//Get Shipping Methods XML Asynchronously by Country code and bind in DropDownList
function loadShippingMethodsByCountry() {
    // Creating Request XML for Load Shipping Methods and update the total
    var countryCd = $('#ddlCountry').val();
    var reqXml = $.format('<reqXml Id=\"10\" CountryCode=\"{0}\"></reqXml>', countryCd);
    $.ajax({
        url: ajaxServerUrl
        , type: "POST"
        , contentType: "text/xml"
        , processData: false
        , data: reqXml
        , dataType: "xml"
        , beforeSend: function() {
            ShowProgress();
        }
        , success: function(response) {
            var xmlResponse = response.documentElement;
            ClearDDL("ddlShippingMethods");
            ClearTXT("txtShipZipPostal", ZIP_CODE_TEXT);
            if (xmlResponse != null && xmlResponse != undefined) {
                if (xmlResponse.getAttribute("result") == "success") {
                    ClearDDL("ddlShippingMethods2");
                    if (xmlResponse.getAttribute("international_shipping") == "yes") {
                        alert(internationalShippingMsg);
                    }
                    else {
                        bindShippingMethodsByCountry(xmlResponse);
                        updateTotal(xmlResponse);
                    }
                    return true;
                }
                else {
                    alert("There is a problem while loading Shipping Methods. Please contact BabyHavens support");
                    return false;
                }
            }
        }
        , complete: function() {
            HideProgress();
        }
    });
    return false;
}

//Load Shipping Methods from XML which generated by given country id
function bindShippingMethodsByCountry(xmlResponse) {
    BindDDLFromXml(
        xmlResponse, "DT_ShippingMethods", "ddlShippingMethods2",
        "shipping_method_description_ext", "shipping_method_id", null
    );
    SetDDLSelectedValueFromXML(xmlResponse, "defaultSelected", "ddlShippingMethods2");
    SetFreeShippingText(xmlResponse);
}


//Updating the updated total in page
function updateTotal(xmlResponse) {
    var orderAmounts = $(xmlResponse).find("order_amounts");
    if (orderAmounts.text() != "") {
        $("#lblStdShipPrice").text(orderAmounts.find("order_shipping").text());
        $("#lblCartTotal").text(orderAmounts.find("order_total").text());
    }
}

function updateShipping(ddlId) {
    // Creating Request XML for Update Shipping
    var shippingMethodId = GetDDLSelectedValue(ddlId);
    if (shippingMethodId.trim() == "" || shippingMethodId.trim() == "0") {
        alert("Select a valid shipping method");
        return false;
    }
    var reqXml = $.format('<reqXml Id=\"9\" ShippingMethodId=\"{0}\"></reqXml>', shippingMethodId);
    $.ajax({
        url: ajaxServerUrl
        , type: "POST"
        , contentType: "text/xml"
        , processData: false
        , data: reqXml
        , dataType: "xml"
        , beforeSend: function() {
            ShowProgress();
        }
        , success: function(response) {
            var xmlResponse = response.documentElement;
            if (xmlResponse != null && xmlResponse != undefined) {
                if (xmlResponse.getAttribute("result") == "success") {
                    updateTotal(xmlResponse);
                    return true;
                }
                else {
                    alert("There is a problem while updating Shipping Methods. Please contact BabyHavens support");
                    return false;
                }
            }
        }
        , complete: function() {
            HideProgress();
        }
    });
}

function SetFreeShippingText(xmlResponse) {
    var freeShipAttr = $(xmlResponse).find("free_shipping_attributes");
    var countryCode = freeShipAttr.find("country_code").text().trim();
    var isFreeShipping = freeShipAttr.find("is_free_shipping").text().trim();
    var addMoreAmt = freeShipAttr.find("add_more_amt").text().trim();

    var trCongrats = $("#trCongrats");

    if (countryCode == US_COUNTRY_CODE) {
        trCongrats.css({ "display": "" });
        if (isFreeShipping == "TRUE") {
            $("#lblCongrats").text(CONGRATS_TEXT);
            $("#trSpecialPrice").css({ "display": "none" });
        }
        else {
            $("#lblCongrats").text($.format(ADD_MORE_TEXT_TOP, addMoreAmt));
            $("#trSpecialPrice").css({ "display": "" });
            $("#lblSpecialPrice").text(addMoreAmt);
        }
    }
    else {
        trCongrats.css({ "display": "none" });
        $("#trSpecialPrice").css({ "display": "none" });
    }
}

function applyGiftCoupon() {
    // Creating Request XML for Update Shipping
    var giftCode = $('#txtGiftCode').val().trim();
    if (giftCode == "") {
        alert("Enter Gift Code");
        return false;
    }
    var zip = $('#txtShipZipPostal').val().trim();
    var shipCountry = GetDDLSelectedValue("ddlCountry");
    var internationalShipping = $('#hdnInternationalShipping').val();

    var selectedShipMethodId = "";
    if (zip != ZIP_CODE_TEXT && zip != "")
        selectedShipMethodId = $('#ddlShippingMethods').val();
    else if (shipCountry > 0)
        selectedShipMethodId = $('#ddlShippingMethods2').val();

    var reqXml = $.format('<reqXml Id=\"11\" GiftCode=\"{0}\" shipCountry=\"{1}\" internationalShipping=\"{2}\" selectedShipMethodId=\"{3}\" zip=\"{4}\"></reqXml>', giftCode, shipCountry, internationalShipping, selectedShipMethodId, zip);
    $.ajax({
        url: ajaxServerUrl
        , type: "POST"
        , contentType: "text/xml"
        , processData: false
        , data: reqXml
        , dataType: "xml"
        , beforeSend: function() {
            ShowProgress();
        }
        , success: function(response) {
            var xmlResponse = response.documentElement;
            if (xmlResponse != null && xmlResponse != undefined) {
                if (xmlResponse.getAttribute("result") == "success") {
                    //Clear the items in cart      
                    var dlCart = $("#dlCart");
                    var iCartRowCounter = 0;
                    $("#dlCart tr").each(function() {
                        ++iCartRowCounter;
                        if (iCartRowCounter > 1)
                            $(this).remove();
                    });
                    refreshCart(dlCart, xmlResponse);
                    if (zip != ZIP_CODE_TEXT && zip != "") {
                        $('#txtShipZipPostal').val(zip);
                        bindShippingMethodsByZip(xmlResponse);
                        updateTotal(xmlResponse);
                    }
                    else if (shipCountry > 0) {
                        SetDDLSelectedValue("ddlCountry", shipCountry);
                        ConvertToImageDdl();
                        bindShippingMethodsByCountry(xmlResponse);
                        updateTotal(xmlResponse);
                    }
                    return true;
                }
                else {
                    alert(xmlResponse.getAttribute("result"));
                    return false;
                }
            }
        }
        , complete: function() {
            HideProgress();
        }
    });
}

//Remove all DropDownList items
function ClearDDL(ddlId) {
    $('#' + ddlId + ' > option').remove();
}

//Clear TextBox text
function ClearTXT(txtId, defaultText) {
    if (defaultText != "")
        $('#' + txtId).val(defaultText);
    else
        $('#' + txtId).val("");
}

//Load items into the specified dropdownlist from XML Reponse
function BindDDLFromXml(xmlResponse, xmlKey, ddlId, textField, valueField, defaultSelectedValue) {
    var options = [];
    options.push('<option value="">' + '-- Select --' + '</option>');
    $(xmlResponse).find(xmlKey).each(function() {
        var optValue = $(this).find(valueField).text();
        var optText = $(this).find(textField).text();
        if (defaultSelectedValue != null && optValue == defaultSelectedValue)
            options.push('<option SELECTED=SELECTED value="' + optValue + '" title="' + optText + '">' + optText + '</option>');
        else
            options.push('<option value="' + optValue + '" title="' + optText + '">' + optText + '</option>');
    });

    $('#' + ddlId).html(options.join(''));
}
//Set DropDownList selected value from XML Response
function SetDDLSelectedValueFromXML(xmlResponse, xmlKey, ddlId) {
    var value = xmlResponse.getAttribute(xmlKey);    
    try{
        $('#' + ddlId).val(value);
    }
    catch(ex){
        setTimeout(function(){ $('#' + ddlId).val(value); },1);
    }
}
//Set DropDownList selected value
function SetDDLSelectedValue(ddlId, valueToSelect) {    
    try{
        $('#' + ddlId).val(valueToSelect);
    }
    catch(ex){
        setTimeout(function(){ $('#' + ddlId).val(valueToSelect); },1);
    }
}

//Returns DropDownList selected value
function GetDDLSelectedValue(ddlId) {
    //var selectedVlue = $('#' + ddlId).val();
    var selectedVal = $('#' + ddlId + ' option:selected').val();
    return selectedVal;
}
//Returns DropDownList selected text
function GetDDLSelectedText(ddlId) {
    var selectedTxt = $('#' + ddlId + ' option:selected').text();
    return selectedTxt;
}

var internationalShippingMsg = "For shipping outside the 48 United States, please call or email for a shipping quote";
var ZIP_CODE_TEXT = "US Shipping Zip Code";
var US_COUNTRY_CODE = "232";
var CONGRATS_TEXT = "Congratulations! Your order is eligible for Free Shipping in the Continental US.";
var ADD_MORE_TEXT_TOP = "Wait! Add {0} to your order to get free shipping in the continental US.";

//Code added by TEJAS[TSI-1033] on 30-March-2010 - End


//Checkout Page - Start
function refreshCheckoutCart(dlCart, cartResponse) {
    var cartRow = null, cartSummaryRow = null;
    var cartColQuantity, cartColItemDesc, cartColUnitPrice, cartColTotal;
    var removeBtnTableOuter = null, removeBtnTableInner = null;
    var removeBtnOuterTableRow = null, removeBtnInnerTableRow = null;
    var removeBtnOuterTableCell = null, removeBtnInnerTableCell = null;
    var descTable = null, descTableRow = null;
    var descTableImageColumn = null, descTableDescColumn = null, descTableDescColumnInnerTable = null;
    var tableCell = null;
    var hdnOrderItemGuId = null, hdnItemGuId = null;
    var txtQuantity = null, btnUpdate = null, btnRemove = null, imgPhoto = null, lnkItemDesc = null;
    if (dlCart == null || dlCart.length < 1) return;
    var iItmCounter = 0;
    var sHTML = '';
    var numericValidation = '';

    // Looping through the Cart Items and framing the CartView table dynamically
    $(cartResponse).find("mf_order_items").each(function() {
        ++iItmCounter;
        cartRow = $("<tr style=\"white-space: nowrap;\">");
        // Column1 : Quantity
        cartColQuantity = $("<td class=\"qtpadding\" align=\"center\" valign=\"top\" style=\"width: 110px;\">")
        sHTML = '';
        sHTML += $.format("<input type=\"hidden\" name=\"hdnLineGuid_{0}\" id=\"hdnLineGuid_{0}\" value=\"{1}\" />", iItmCounter, $(this).find("order_item_guid").text());
        sHTML += $.format("<input type=\"hidden\" name=\"hdnItemGuid_{0}\" id=\"hdnItemGuid_{0}\" value=\"{1}\" />", iItmCounter, $(this).find("item_guid").text());
        sHTML += $.format("<input name=\"txtQty_{0}\" type=\"text\" value=\"{1}\" maxlength=\"5\" size=\"2\" id=\"txtQty_{0}\" /><br />", iItmCounter, $(this).find("order_item_quantity").text());
        numericValidation += $.format("AddNumericValidations(document.getElementById('txtQty_{0}'),0,0,0,0,0,'');", iItmCounter);
        //sHTML += $.format("<input type=\"image\" name=\"btnUpdate_{0}\" id=\"btnUpdate_{0}\" title=\"Update Cart\" src=\"http://www.babyhaven.com/images/design/buttons/btn_update.gif\" align=\"middle\" style=\"border-width:0px;\" onclick=\"updateCheckoutCartItem('{1}','txtQty_{0}');return false;\" />", iItmCounter, $(this).find("order_item_guid").text());
        sHTML += $.format("<input type=\"image\" name=\"btnUpdate_{0}\" id=\"btnUpdate_{0}\" title=\"Update Cart\" src=\"http://www.babyhaven.com/images/design/buttons/btn_update.gif\" align=\"middle\" style=\"border-width:0px;\" onclick=\"updateCheckoutCartItem('{1}','{2}','txtQty_{0}','{3}');return false;\" />", iItmCounter, $(this).find("order_item_guid").text(), $(this).find("item_guid").text(), $(this).find("order_item_quantity").text());
        sHTML += "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" align=\"Center\"><tr><td align=\"Center\" style=\"padding-top:5px;\">";
        sHTML += "<table cellspacing=\"0\" cellpadding=\"0\" align=\"Center\" border=\"0\" style=\"border-collapse:collapse;\">";
        sHTML += $.format("<tr><td id=\"tcRemove_{0}\" align=\"center\" valign=\"middle\" style=\"white-space:nowrap;\">", iItmCounter);
        sHTML += $.format("<input type=\"image\" name=\"bRemove_{0}\" id=\"bRemove_{0}\" title=\"Remove\" class=\"checkoutremove\" src=\"http://www.babyhaven.com/images/design/buttons/btn_remove.gif\" alt=\"Remove\" align=\"middle\" style=\"border-width:0px;\" onclick=\"deleteCheckoutCartItem('{1}');return false;\" /></td></tr></table></td></tr></table></td>", iItmCounter, $(this).find("order_item_guid").text());

        cartColQuantity.html(sHTML);
        cartColQuantity.appendTo(cartRow);
        // Column1 : Quantity - Ends

        // Column2 : Item Descrition - Starts
        cartColItemDesc = $("<td align=\"center\" valign=\"top\" style=\"width:385px;\">");
        sHTML = '';
        sHTML += "<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" style=\"width: 110px; border-collapse: collapse;\">";
        sHTML += "<tbody><tr><td valign=\"top\" style=\"padding-right:40px;\">";
        sHTML += $.format("<img id=\"imgPhoto_(0)\" src=\"http://www.babyhaven.com/mainstreet/get_image.aspx?domain=strollerbabies.com&amp;item_guid={1}&amp;size=0\"", iItmCounter, $(this).find("item_guid").text());
        sHTML += " style=\"width: 60px; border-width: 0px;\" /></td>";
        sHTML += "<td><table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" width=\"275\">";
        sHTML += "<tbody><tr><td style=\"padding: 10px 0px;\">";
        sHTML += "<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" style=\"border-collapse: collapse;\">";
        sHTML += "<tbody><tr><td style=\"width: 275px;\">";
        sHTML += $.format("<a id=\"lnkItemDesc_{0}\"", iItmCounter);
        sHTML += $.format(" href=\"{1}\" style=\"color: #AD4898; font-family: tahoma; font-size: 8pt; font-weight: bold; text-decoration: none;\">{0}</a></td>", $(this).find("order_item_description").text(), $(this).find("item_navigate_url").text());
        sHTML += "</tr></tbody></table></td></tr>";
        if ($(this).find("item_qty_text").text().trim() != "") {
            sHTML += $.format("<tr><td style=\"padding-bottom: 10px;\" class=\"checkoutav\">{0}</td></tr>", $(this).find("item_qty_text").text());
        }
        sHTML += "<tr><td></td></tr><tr><td style=\"padding: 3px 0px;\" class=\"checkoutcolor\">";
        sHTML += $.format("SKU&nbsp;#&nbsp; <strong><span id=\"lblSKU_{0}\">{1}</span></strong></td></tr>", iItmCounter, $(this).find("order_item_cd").text());
        if ($(this).find("order_item_color").text().trim() != "") {
            sHTML += "<tr><td style=\"padding: 3px 0px;\" class=\"checkoutcolor\">";
            sHTML += $.format("Color:&nbsp; <strong><span id=\"lblColor_{0}\">{1}</span></strong></td></tr>", iItmCounter, $(this).find("order_item_color").text());
        }
        if ($(this).find("order_item_size").text().trim() != "") {
            sHTML += "<tr><td style=\"padding: 3px 0px;\" class=\"checkoutcolor\">";
            sHTML += $.format("Size:&nbsp; <strong><span id=\"lblSize_{0}\">{1}</span></strong></td></tr>", iItmCounter, $(this).find("order_item_size").text());
        }
        if ($(this).find("item_stock_text").text().trim() != "") {
            sHTML += $.format("<tr><td style=\"padding-top: 18px; padding-bottom: 5px;\" class=\"checkoutstock\">{0}</td></tr>", $(this).find("item_stock_text").text());
        }
        sHTML += "</tbody></table></td></tr></table>";

        cartColItemDesc.html(sHTML);
        cartColItemDesc.appendTo(cartRow);
        // Column2 : Item Descrition - Ends

        // Column3 : Unit Price - Starts
        cartColUnitPrice = $("<td align=\"center\" valign=\"top\" style=\"color: #837E7B; font-family: tahoma; font-size: 8pt; font-weight: bold; width: 110px;\">");
        cartColUnitPrice.text($(this).find("order_item_unit_price").text());
        cartColUnitPrice.appendTo(cartRow);
        // Column3 : Unit Price - Ends

        // Column3 : Total - Starts
        cartColTotal = $("<td align=\"center\" valign=\"top\" style=\"color: #837E7B; font-family: tahoma; font-size: 8pt; font-weight: bold; width: 110px;\">");
        cartColTotal.text($(this).find("order_item_extended_price").text());
        cartColTotal.appendTo(cartRow);
        // Column3 : Total - Ends        

        cartRow.appendTo(dlCart);

        var numericScript = $.format("<script language=\"javascript\" type=\"text/javascript\">{0}</script>", numericValidation);
        $('#numericScript').html(numericScript);
    });

    if (iItmCounter == 0) {
        setTimeout('__doPostBack(\'' + PostBackId + '\',\'\')', 0);
    }

    //Update Checkout Total
    var sHTML = "";
    sHTML = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" visible=\"false\" width=\"100%\">";
    sHTML += "<tr>";
    sHTML += "<td align=\"left\" class=\"checkouttotal\" style=\"width: 170px;\">Item Subtotal</td>";
    sHTML += $.format("<td class=\"checkouttotal\" align=\"right\"><span id=\"lbSubTotal\">{0}</span></td>", $(cartResponse).find("mf_orders").find("custom_order_sub_total").text());
    sHTML += "</tr>";
    sHTML += "<tr><td colspan=\"2\" style=\"height: 7px;\"></td></tr><tr><td colspan=\"2\" class=\"checkouttotalline\"></td></tr>";
    sHTML += "<tr><td colspan=\"2\" style=\"height: 7px;\"></td></tr>";
    sHTML += "<tr>";
    sHTML += "<td align=\"left\" class=\"checkouttotal\">Shipping</td><td class=\"checkouttotal\" align=\"right\">";
    sHTML += $.format("<span id=\"lbShipping\">{0}</span></td>", $(cartResponse).find("mf_orders").find("custom_order_shipping").text());
    sHTML += "</tr>";
    sHTML += "<tr><td colspan=\"2\" style=\"height: 7px;\"></td></tr><tr><td colspan=\"2\" class=\"checkouttotalline\"></td></tr>";
    sHTML += "<tr><td colspan=\"2\" style=\"height: 7px;\"></td></tr>";
    sHTML += "<tr><td align=\"left\" class=\"checkouttotal\">Tax</td><td class=\"checkouttotal\" align=\"right\">";
    sHTML += "<span id=\"lbTax\"></span></td></tr>"
    sHTML += "<tr><td colspan=\"2\" style=\"height: 7px;\"></td></tr><tr><td colspan=\"2\" class=\"checkouttotalline\"></td></tr>";
    sHTML += "<tr><td colspan=\"2\" style=\"height: 7px;\"></td></tr>";
    sHTML += "<tr><td align=\"left\" class=\"checkoutmaintotal\">Total</td><td class=\"checkoutmaintotal\" align=\"right\">";
    sHTML += $.format("<span id=\"lbTotal\">{0}</span></td></tr>", $(cartResponse).find("mf_orders").find("custom_order_total").text());
    sHTML += "</table>";
    $('#tdTotal').html(sHTML);
}
function updateCheckoutCartItem(orderItemGUId, itemGuid, idTxtQuantity, currQty) {    
    // Creating Request XML for Update Cart Item
    var txtQty = $('#' + idTxtQuantity)[0];        
    var reqXml = $.format('<reqXml Id=\"13\" order_item_guid=\"{0}\" order_item_quantity=\"{1}\" itemGuid=\"{2}\" currentQty=\"{3}\"></reqXml>', orderItemGUId, txtQty.value, itemGuid, currQty);
    $.ajax({
        url: ajaxServerUrl
        , type: "POST"
        , contentType: "text/xml"
        , processData: false
        , data: reqXml
        , dataType: "xml"
        , beforeSend: function() {
            ShowProgress();
        }
        , success: function(response) {
            var xmlResponse = response.documentElement;
            var dlCart = $("#dlCart");
            var iCartRowCounter = 0;            
            if (xmlResponse != null && xmlResponse != undefined) {                
                if (xmlResponse.getAttribute("result") == "success") {
                    // Clearing the table before binding it with the new data
                    $("#dlCart tr").each(function() {
                        ++iCartRowCounter;
                        if (iCartRowCounter > 1)
                            $(this).remove();
                    });
                    refreshCheckoutCart(dlCart, xmlResponse);
                    ClearDDL("ctl00_Body_MiniCartAddressForm1_CartShippingForm1_cmbShippingMethod");
                    refreshShippingMethods("ctl00_Body_MiniCartAddressForm1_CartShippingForm1_cmbShippingMethod", xmlResponse);
                    updateChceckoutTotal(xmlResponse);
                }
                else if (xmlResponse.getAttribute("result") == "no_stock") {
                    txtQty.value = currQty;
                    alert(xmlResponse.getAttribute("message"));
                }
            }
        }
        , complete: function() {
            HideProgress();
        }
    });
}
function deleteCheckoutCartItem(orderItemGUId) {
    // Creating Request XML for Delete Cart Item
    var reqXml = $.format('<reqXml Id=\"7\" order_item_guid=\"{0}\"></reqXml>', orderItemGUId);
    $.ajax({
        url: ajaxServerUrl
        , type: "POST"
        , contentType: "text/xml"
        , processData: false
        , data: reqXml
        , dataType: "xml"
        , beforeSend: function() {
            ShowProgress();
        }
        , success: function(response) {
            var xmlResponse = response.documentElement;
            var dlCart = $("#dlCart");
            var iCartRowCounter = 0;
            if (xmlResponse != null && xmlResponse != undefined) {
                // Clearing the table before binding it with the new data
                $("#dlCart tr").each(function() {
                    ++iCartRowCounter;
                    if (iCartRowCounter > 1)
                        $(this).remove();
                });
                refreshCheckoutCart(dlCart, xmlResponse);
                ClearDDL("ctl00_Body_MiniCartAddressForm1_CartShippingForm1_cmbShippingMethod");
                refreshShippingMethods("ctl00_Body_MiniCartAddressForm1_CartShippingForm1_cmbShippingMethod", xmlResponse);
                updateChceckoutTotal(xmlResponse);
            }
        }
        , complete: function() {
            HideProgress();
        }
    });
}
//Update checkout page total
function updateChceckoutTotal(xmlResponse) {
    var orderAmounts = $(xmlResponse).find("order_amounts");
    if (orderAmounts.text() != "") {
        $("#lbSubTotal").text(orderAmounts.find("order_sub_total").text());
        $("#lbShipping").text(orderAmounts.find("order_shipping").text());
        $("#lbTax").text(orderAmounts.find("order_tax").text());
        $("#lbTotal").text(orderAmounts.find("order_total").text());
    }
}

//Load Shipping Methods from XML which generated by given country id
function refreshShippingMethods(ddlId, xmlResponse) {
    BindDDLFromXml(
        xmlResponse, "DT_ShippingMethods", ddlId,
        "shipping_method_description_ext", "shipping_method_id", null
    );
    SetDDLSelectedValueFromXML(xmlResponse, "defaultSelected", ddlId);
    SetFreeShippingText(xmlResponse);
}
//Checkout page - End

function ShowProgress() {
    $('#progressDiv').middleCenter();
    $('#progressDiv').css({ "display": "" });
    $(window).scroll(function() {
        $('#progressDiv').middleCenter();
    });
}
function HideProgress() {
    $('#progressDiv').css({ "display": "none" });
    $(window).unbind('scroll');
}

jQuery.fn.middleCenter = function() {
    this.css("position", "absolute");
    this.css("top", ($(window).height() - this.outerHeight()) / 2 + $(window).scrollTop() + "px");
    this.css("left", ($(window).width() - this.outerWidth()) / 2 + $(window).scrollLeft() + "px");
    return this;
}

jQuery.fn.topLeft = function() {
    this.css("position", "absolute");
    this.css("top", "0px");
    this.css("left", "0px");
    return this;
}
jQuery.fn.scrollTopLeft = function() {
    this.css("position", "absolute");
    this.css("top", $(window).scrollTop() + "px");
    this.css("left", "0px");
    return this;
}

jQuery.fn.topRight = function() {
    this.css("position", "absolute");
    this.css("top", "0px");
    this.css("left", ($(window).width() - this.outerWidth()) + "px");
    return this;
}
jQuery.fn.scrollTopRight = function() {
    this.css("position", "absolute");
    this.css("top", $(window).scrollTop() + "px");
    this.css("left", ($(window).width() - this.outerWidth()) + $(window).scrollLeft() + "px");
    return this;
}

jQuery.fn.bottomLeft = function() {
    this.css("position", "absolute");
    this.css("top", ($(window).height() - this.outerHeight()) + "px");
    this.css("left", "0px");
    return this;
}
jQuery.fn.scrollBottomLeft = function() {
    this.css("position", "absolute");
    this.css("top", ($(window).height() - this.outerHeight()) + $(window).scrollTop() + "px");
    this.css("left", "0px");
    return this;
}

jQuery.fn.bottomRight = function() {
    this.css("position", "absolute");
    this.css("top", ($(window).height() - this.outerHeight()) + "px");
    this.css("left", ($(window).width() - this.outerWidth()) + "px");
    return this;
}
jQuery.fn.scrollBottomRight = function() {
    this.css("position", "absolute");
    this.css("top", ($(window).height() - this.outerHeight()) + $(window).scrollTop() + "px");
    this.css("left", ($(window).width() - this.outerWidth()) + $(window).scrollLeft() + "px");
    return this;
}

