var preview3DProductId;
var userId;
var shiftStep = 1;
var TopChoiceItemsCount;
var AlternativeItemsCount;
var TopChoiceItemsHtml;
var AlternativeItemsHtml;
var FinishingTypeId = 0;
var FinishingType;
var mouseX = 0;
var mouseY = 0;
var isPopupMode = false;
var isPending = false;
var productCategory = null;
var productSetPlace;

$(document).ready(function() {
    $().mousemove(function(e) {
        mouseX = e.pageX;
        mouseY = e.pageY;
    });

    try { $('.imgthumb,.imgthumb_myproducts').minmax(); } catch (e) { }

    var decodedURI = unescape(document.location.href);
    if (decodedURI.indexOf('ar=1') != -1) {
        createNewRoom();
    }

    $('.addToList').click(function() {
        if ($(this).attr("disabled") == 'true') {
            // additional checking of room's status
            var roomIsReady = false;
            try { roomIsReady = getFlashObject("StandaloneProductSetView").isReady(); } catch (e) { }
            if (roomIsReady)
                disableAddToList(false);
            else
                return false;
        }

        var currentProductSet = $("#selectProductSet").get(0);
        var addToListButton = $(this);
        var decodedURI = unescape(document.location.href);
        var isRetailerProductList = (decodedURI.indexOf('within-PartnerProducts') != -1);
        var productId, categoryId;
        var targetUrl, targetImageUrl;
        var has3DRepresentation = false;

        if (isRetailerProductList) {
            productId = TrimString(addToListButton.find('.targetId').text());
            has3DRepresentation = (TrimString(addToListButton.find('.hasRepresentation3D').text()) != 'False');
            retailerId = TrimString(addToListButton.find('.retailerId').text());
            categoryId = TrimString(addToListButton.find('.mdiCategoryId').text());
            targetUrl = TrimString(addToListButton.find('.targetUrl').text());
            targetImageUrl = TrimString(addToListButton.find('.targetImageUrl').text());
        } else {
            productId = TrimString(addToListButton.parents('#itemContainer').find('.productId').text());
            has3DRepresentation = (TrimString(addToListButton.find('.hasRepresentation3D').text()) != 'False');
            retailerId = 'undefined';
            categoryId = TrimString(addToListButton.find('.categoryId').text());
            targetUrl = TrimString(addToListButton.find('.targetUrl').text());
            targetImageUrl = TrimString(addToListButton.find('.targetImageUrl').text());
        }
        $('.addToProductSetPlace').html('');
        $('.finishingTypeContainer').html('');

        var elementPosition = $(this).position();

        if ((currentProductSet != null && currentProductSet.options[currentProductSet.selectedIndex].value != '0') ||
             (currentProductSet == null && jQuery && jQuery.cookie && $.cookie("selectedProductSet") != '0')) {

            $.ajax({
                type: "POST",
                url: "/WebServices/Category.asmx/GetFinishingTypeList",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify({ "categoryId": categoryId }),
                dataType: "json",
                success: function(json) {
                    var items = json.d;
                    var finishingTypeContainer = isRetailerProductList ? addToListButton.next('.finishingTypeContainer') : addToListButton.parents('#itemContainer').find('.finishingTypeContainer');
                    if (items.length > 1) {
                        finishingTypeContainer.html(initFinishingTypeList(items, isRetailerProductList, addToListButton.get(0).id));
                        finishingTypeContainer.show();
                        finishingTypeContainer.mouseleave(function() {
                            $('.finishingTypeContainer').html('');
                            $('.finishingTypeContainer').hide();
                        });
                        finishingTypeContainer.click(function() {
                            $('.finishingTypeContainer').html('');
                            $('.finishingTypeContainer').hide();
                        });
                        finishingTypeContainer.css({ top: mouseY - 2, left: mouseX - 2 })

                    } else {
                        if (items.length == 1) {
                            FinishingTypeId = items[0].Id;
                            FinishingType = items[0].Title;
                        } else {
                            FinishingTypeId = 0;
                            FinishingType = "";
                        }
                        addProductToProductSet(addToListButton, isRetailerProductList, productId, categoryId, targetUrl, targetImageUrl, retailerId, has3DRepresentation);
                    }
                }
            });
        } else { // if ((currentProductSet != null && currentProductSet.options[currentProductSet.selectedIndex].value != '0') ||
            var url = $('#myListsBox a:first').get(0).getAttribute('href');
            if (url.indexOf('&pid=') > 0)
                url = url.substring(0, url.indexOf('&pid='));
            url += "&pid=" + productId;
            $('#myListsBox a:first').get(0).setAttribute('href', url);
            $("#myListsBox a:first").click();
        }

        return false;
    }); // $('.addToList').click(function()


    function loadCommentCount(link) {
        var productId = $(link).find('div.targetId').text();
        $.ajax({
            type: "POST",
            url: "/WebServices/Comments.asmx/GetProductCommentsCount",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ "productId": productId }),
            dataType: "json",
            success: function(json) {
                $(link).find('div.commentCount').html(json.d.toString() + " Comments");
            }
        });
    }

    $('.commentsToggle').each(function() {
        loadCommentCount(this);
    });

    function slideHideComments() {
        $('#commentsBox').slideUp(400, function() {
            $(this).parents('.commentsPlace').html('');
            $('.commentsToggle').removeClass('medArrowOn');
        });
    }

    function updateComments(productId) {
        $('#commentListPlaceholder').html('');
        $.ajax({
            type: "POST",
            url: "/WebServices/Comments.asmx/GetProductComments",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ "productId": productId }),
            dataType: "json",
            success: function(json) {
                var html = '';
                jQuery.each(json.d, function() {
                    html += '<div class=\"commentBox\"><ul class=\"lrBox\"><li class=\"lt\"><a href=\"#\">' + this.UserName + '</a> said...</li>'; ;
                    html += '<li class=\"rt\">' + this.Date + '</li></ul>' + this.Text + '</div>';
                });
                $('#commentListPlaceholder').html(html);
            }
        });
    }

    $('.commentsToggle').click(function() {
        var isRegistered = false;
        isUserRegistered(function(value) {
            isRegistered = value;
        }, false);
        if (!isRegistered) {
            userLogin();
            return false;
        }

        var productId = $(this).find('div.targetId').text();
        var hide = $(this).hasClass('medArrowOn');
        $('.commentsToggle').removeClass('medArrowOn');
        if (hide)
            $('#commentsBox').slideUp(400, function() {
                $('.commentsPlace').html('');
            });
        else
            $('.commentsPlace').html('');
        if (!hide) {
            $(this).addClass('medArrowOn');
            $(this).parents('#itemContainer').find('.commentsPlace').load('/Shop/commentsBox.htm', null, function() {
                updateComments(productId);

                $('#commentsBox').slideToggle(400, function() {
                    $.scrollTo("#commentsBox", 1000, {});
                });

                $('#commentBox_submit').click(function() {
                    var text = $('#commentTextBox').val();
                    if (text.length == 0)
                        return false;
                    $.ajax({
                        type: "POST",
                        url: "/WebServices/Comments.asmx/AddProductComment",
                        contentType: "application/json; charset=utf-8",
                        data: JSON.stringify({ "productId": productId, "text": text }),
                        dataType: "json",
                        success: function(json) {
                            updateComments(productId);
                            loadCommentCount($('.medArrowOn')[0]);
                        }
                    });
                    $('#commentTextBox').val('');
                    return false;
                });

                $('.closeCommentsToggle').click(function() {
                    slideHideComments();
                    return false;
                });
            });
        }
        return false;
    });

    userId = $('#itemContainer').find('.userId').text();

    $('.mainLinks').each(function() {
        showProductQAStatus($(this).parents('#itemContainer'));
    });

    $('.Accept').click(function() {
        var productId = $(this).parents('#itemContainer').find('.productId').text();

        $.ajax({
            type: "POST",
            url: "/WebServices/Product.asmx/SetQAedDate",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ "userId": userId, "productId": productId }),
            dataType: "json",
            success: function(json) {
                var QAedInfo = json.d;
                $('.Accept').each(function() {
                    var itemContainer = $(this).parents('#itemContainer');
                    if (productId == itemContainer.find('.productId').text()) {
                        itemContainer.find('.productIsActive').html(QAedInfo.Active);
                        updateModifiedBy(itemContainer, itemContainer.find('#QAedBy'), QAedInfo.QAedAccountName, QAedInfo.QAedDate, "Accepted", "")
                        showProductQAStatus(itemContainer);
                        itemContainer.find('#DeniedCommentContainer').hide();
                    }
                });
            }
        });
        return false;
    });

    $('.Deny').click(function() {
        var productId = $(this).parents('#itemContainer').find('.productId').text();

        $.ajax({
            type: "POST",
            url: "/WebServices/Product.asmx/SetDeniedDate",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ "userId": userId, "productId": productId }),
            dataType: "json",
            success: function(json) {
                var QAedInfo = json.d;
                $('.Deny').each(function() {
                    var itemContainer = $(this).parents('#itemContainer');
                    if (productId == itemContainer.find('.productId').text()) {
                        itemContainer.find('.productIsActive').html(QAedInfo.Active);
                        updateModifiedBy(itemContainer, itemContainer.find('#DeniedBy'), QAedInfo.DeniedAccountName, QAedInfo.DeniedDate, "Denied", QAedInfo.DeniedComment)
                        showProductQAStatus(itemContainer);
                        showDeniedComment(itemContainer);
                    }
                });
            }
        });
        return false;
    });

    $('.DeniedComment_submit').click(function() {
        var productId = $(this).parents('#itemContainer').find('.productId').text();
        var itemContainer = $(this).parents('#itemContainer');
        var comment = itemContainer.find('#DeniedCommentTextarea').text();

        $.ajax({
            type: "POST",
            url: "/WebServices/Product.asmx/SetDeniedComment",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ "productId": productId, "comment": comment }),
            dataType: "json",
            success: function(json) {
                var QAedInfo = json.d;
                $('.Deny').each(function() {
                    var itemContainer = $(this).parents('#itemContainer');
                    if (productId == itemContainer.find('.productId').text()) {
                        updateModifiedBy(itemContainer, itemContainer.find('#DeniedBy'), QAedInfo.DeniedAccountName, QAedInfo.DeniedDate, "Denied", QAedInfo.DeniedComment)
                    }
                });
                itemContainer.find('#DeniedCommentContainer').hide();
            }
        });

        return false;
    });

    $('#QAedFilter').click(function() {
        var url = window.location.href;
        if (url.indexOf('qf') == -1)
            url = $('#filterTabs a:first').attr('href')
        var url = replaceQueryParameter(url, 'qf', this.checked ? "True" : "False");
        if (window.location.href != url)
            window.location.href = url;
        return false;
    });

    $('.preview3D').click(function() {
        preview3DProductId = $(this).find('.targetId').text();
        var currentPreviewButton = $(this).get(0);

        if (currentPreviewButton.getAttribute("disabled")) {
            hidePreview3D();
            return false;
        }
        else {
            hidePreview3D();
            currentPreviewButton.setAttribute("disabled", "disabled");
        }

        $(this).parents('#itemContainer').find('.preview3DPlace').load('/Shop/preview3DBox.htm', null, function() {
            $('#preview3DBox').slideDown(100, function() {
                var flashvars = { productId: preview3DProductId }; // {};
                var params = { allowScriptAccess: "sameDomain", wmode: "transparent" };
                var attributes = {};
                attributes.id = "flashcontent_preview3D";
                swfobject.embedSWF("/Flash/AppearancePreview3D.swf?<%= _assemblyid %>", "flashcontent_preview3D", "440", "239", "10.0.12", "../Flash/expressInstall.swf", flashvars, params, attributes);
                //swfobject.addDomLoadEvent(onSwfobjectLoad);
            });

            $('#edit_bookmark').click(function() {
                $('.preview3DPlace').html('');
                window.location.href = "/Shop/AddManufacturerProduct.aspx?url=" + encodeURIComponent(window.location.href) + "&pid=" + preview3DProductId;
            });

            $('#delete_bookmark').hide();
            $.ajax({
                type: "POST",
                url: "/WebServices/Product.asmx/IsUsed",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify({ "productId": preview3DProductId }),
                dataType: "json",
                success: function(json) {
                    var isUsed = (json.d == true);
                    if (isUsed) {
                        $('#delete_bookmark').hide();
                    }
                    else {
                        $('#delete_bookmark').show();
                    }
                }
            });


            $('#delete_bookmark').click(function() {
                $.ajax({
                    type: "POST",
                    url: "/WebServices/Product.asmx/DeleteProduct",
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify({ "productId": preview3DProductId }),
                    dataType: "json",
                    success: function(json) { reloadPageWithUniquePId(preview3DProductId) }
                });
                return false;
            });

            $('.closePreview3DToggle').click(function() {
                hidePreview3D();
                return false;
            });

        });

        return false;
    });


});



function prepareAdToProductSet(productSetPlace, productId, categoryId, productPosition, isProductInRoom, items) {
    if (isProductInRoom && items.length == 1) {
        $('#div_ErrorMessageProductInProductSet').show();
        $('#Tr_TopAlternateSelector').hide();
        $("#tr_ProductSetControlButtons").hide();
        $("#div_newItemName").html(productCategory.Title + " 1");
        return;
    }

    TopChoiceItemsCount = 0;
    AlternativeItemsCount = 0;
    TopChoiceItemsHtml = '';
    AlternativeItemsHtml = '';

    for (index = 0; index < items.length; index++) {
        var item = items[index];
        var shortItemName = item.Name;
        if (shortItemName.indexOf("Kitchen") != -1)
            shortItemName = shortItemName.substring(shortItemName.indexOf(" "), shortItemName.length);

        var style = '';
        if (index > 3)
            style = 'display: none;';

        var checked = '';
        if (TopChoiceItemsCount == 0)
            checked = 'checked'

        var image = '';
        if (item.TopChoice > 0) {
            image = '<img src=\'' + item.TopChoiceThumbnailURL + '\' width=\'70\' height=\'70\' alt=\'' + item.Name + '\' title=\'' + item.Name + '\'/>';
            AlternativeItemsHtml += '<li style=\'' + style + '\'>' + shortItemName + '<br />' + image + '<br /><input type=\'radio\' ' + checked + ' name=\'itemList\' value=\'' + item.Id + '\' /></li>'
            AlternativeItemsCount++;
        } else {
            image = '<img src=\'/Images/noImage.gif\' width=\'70\' height=\'70\' alt=\'' + item.Name + '\' title=\'' + item.Name + '\'/>';
        }
        TopChoiceItemsHtml += '<li style=\'' + style + '\'>' + shortItemName + '<br />' + image + '<br /><input type=\'radio\' ' + checked + ' name=\'itemList\' value=\'' + item.Id + '\' /></li>'
        TopChoiceItemsCount++;
    }

    $("#div_newItemName").html(productCategory.Title + " " + (TopChoiceItemsCount + 1));
    $('#div_ErrorMessageProductInProductSet').hide();
    $("#tr_ProductSetControlButtons").show();

    setAddProductSelection(productPosition);
    updateProductSetItems();

    if (TopChoiceItemsCount == 0) {
        // Setup first TopChoice in ProductSetItem
        $('#Tr_AddNewItemContainer input[type=radio]').attr("checked", "true");
        $('#addToProductSet_Create').click();
        return;
    }

    if (TopChoiceItemsCount == 1 && (items[0].TopChoice == 0 || FinishingTypeId != 0)) {
        // Setup first TopChoice in ProductSetItem
        $('#addToProductSet_radioBoxList input[type=radio]:first').attr("checked", "true");
        $('#addToProductSet_Create').click();
        return;
    }

    if (AlternativeItemsCount > 0)
        $('#alternateChoice').show();
    else
        $('#alternateChoice').hide();

    $('.itemBrowseBox input').click(function() {
        var itemId = parseInt($('.browseGrid input:checked').val());
        var index;
        for (index = 0; index < items.length; index++) {
            var item = items[index];
            if (item.Id != itemId) continue;
            if (item.TopChoice > 0) $('#alternateChoice').show();
            else $('#alternateChoice').hide();
        }
        return true;
    });

    if (TopChoiceItemsCount == 1 && (items[0].TopChoice != 0 || FinishingTypeId == 0)) {
        // Open a Dialog for setup first TopChoice in ProductSetItem with an ability to interrupt by HOLD On link
        $('#addToProductSet_radioBoxList input[type=radio]:first').attr("checked", "true");
        $('#img_dialogBoxAddProductContainer').attr('src', items[0].TopChoiceThumbnailURL);
        $('#img_dialogBoxAddProductContainer').attr('alt', items[0].Name);
        $('#img_dialogBoxAddProductContainer').attr('title', items[0].Name);
        $('#tr_dialogBoxAddProductContainer').hide();
        $("#tr_ProductSetControlButtons").hide();
        //if (!isPopupMode)
        //  $.scrollTo(productSetPlace.get(0), 1000, {});
        $('#tr_dialogBoxAddProductContainer').slideToggle(7000, function() {
            if ($('#Tr_TopAlternateSelector').css('display') == 'none') {
                $('#addToProductSet_Create').click();
            }
            $("#tr_ProductSetControlButtons").show();
            $('#tr_dialogBoxAddProductContainer').hide();
        });
        return;
    }

    $('#Tr_TopAlternateSelector').show();
}


/* 
    productPosition == 0 for default TopChoice position 
    productPosition == 1 for default Alternative position 
    productPosition == 2 for default New Item position 
*/
function addToProductSet(productSetPlace, productId, categoryId, productPosition) {
    productSetPlace.load('/Shop/addToProductSet.htm', null, function() {
        //$(addToListButton.parents('.listViewNarrow,.listView').get(0)).find('.addToProductSetPlace').load('/Shop/addToProductSet.htm', null, function() {

        $("#shoppingLists").change(function() {
            var selectedValue = $(this).val();
            if (jQuery && jQuery.cookie) {
                $.cookie("selectedProductSet", selectedValue, { expires: 30, path: "/" });
            }

            if (!isApproved) {
                $.ajax({
                    type: "POST",
                    url: "/WebServices/Product.asmx/GetProduct",
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify({ "productId": parseInt(productId) }),
                    dataType: "json",
                    success: function(json) {
                        if (!json.d)
                            return;

                        var appearanceId = json.d.AppearanceId;
                        var data = getFlashObject('StandaloneProductSetView').getRoomIdea(selectedValue, categoryId, productId, FinishingTypeId, appearanceId);
                        if (data == null || data.ProductSetItems.length == 0)
                            return;
                        prepareAdToProductSet(productSetPlace, productId, categoryId, productPosition, data.IsProductInRoom, data.ProductSetItems);
                    }
                });
            }
            else {
                $.ajax({
                    type: "POST",
                    url: "/WebServices/Room.asmx/GetRoomIdea",
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify({ "id": parseInt(selectedValue), "categoryId": parseInt(categoryId), "productId": parseInt(productId), "finishingTypeId": FinishingTypeId }),
                    dataType: "json",
                    success: function(json) {
                        if (!json.d)
                            return;
                        var items = json.d.ProductSetItems;

                        prepareAdToProductSet(productSetPlace, productId, categoryId, productPosition, json.d.IsProductInRoom, items);
                    }
                });
            }
        }); // $("#shoppingLists").change(function() {

        $.ajax({
            type: "POST",
            url: "/WebServices/Room.asmx/GetMyRoomIdeas",
            contentType: "application/json; charset=utf-8",
            data: "{}",
            dataType: "json",
            success: function(json) {
                var selectedProductSet = '';
                if (jQuery && jQuery.cookie) {
                    selectedProductSet = $.cookie("selectedProductSet");
                }
                $("#shoppingLists").removeAttr("disabled");
                var html = "<option value=\"0\">Select a Room Idea</option>";
        
                if (!isApproved) {
                    var designList = tempdesigncontent.getTempDesignList();
                    if (designList.length > 0) {
                        var design = designList[0];
                        //alert("Temp Design: [id=" + design[0] + ", name=" + design[1] + "]  from " + designList);
                        html += "<option id=\"tempRoomIdeaOption\" value=\"" + design[0] + "\" selected=\"true\">" + design[1] + "</option>";
                        setShoppingListCount(1);
                    }
                }
                else {
                    jQuery.each(json.d, function() {
                        var selectedHtml = '';
                        if (selectedProductSet == this.Id.toString())
                            selectedHtml = ' selected=\"true\" ';
                        html += "<option value=\"" + this.Id.toString() + "\" " + selectedHtml + "  >" + this.Name + "</option>";
                        return true;
                    });
                }
                $("#shoppingLists").html(html);

                $.ajax({
                    type: "POST",
                    url: "/WebServices/ProductCategory.asmx/GetCategoryById",
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify({ "id": parseInt(categoryId) }),
                    dataType: "json",
                    success: function(json) {
                        if (json.d == null)
                            return;
                        productCategory = json.d;

                        //$("#div_categoryName").html(productCategory.Title);
                        $("#shoppingLists").change();
                    }
                });
            }
        });

        $.ajax({
            type: "POST",
            url: "/WebServices/Room.asmx/RoomList",
            contentType: "application/json; charset=utf-8",
            data: "{}",
            dataType: "json",
            success: function(json) {
                $("#AddToProductSet_roomType").removeAttr("disabled");

                var html = "<option value=\"0\">Select a Room</option>";

                jQuery.each(json.d, function() {
                    html += "<option value=\"" + this.Id.toString() + "\" >" + this.Name + "</option>";
                    return true;
                });

                $("#AddToProductSet_roomType").html(html);
            }
        });

        $('#newListToggle').click(function() {
            $("#div_newItemName").html(productCategory.Title + " 1");
            //$('#Tr_ItemsContainer').hide();
            $('#Tr_TopAlternateSelector').hide();
            $('#Tr_AddNewItemContainer input[type=radio]').attr("checked", "true");
            //$('#newChoiceTypeLink').hide();
            $('#existingListBox').hide();
            $('#div_ErrorMessageProductInProductSet').hide();
            //$('#newChoiceType').show();
            //$('#Tr_AddNewItemContainer').show();
            $('#newListBox').show();
            $('#AddToProductSet_roomTypeContainer').show();
            $('#tr_ProductSetControlButtons').show();

            $('#newShoppingList').data('shown', true);
            return false;
        });

        $('#newChoiceTypeToggle').click(function() {
            $('#Tr_AddNewItemContainer input[type=radio]').attr("checked", "true");
            //$('#newChoiceTypeLink').hide();
            //$('#newChoiceType').show();
            return false;
        });


        $('#addToProductSet_cancel').click(function() {
            $('.addToProductSetPlace').html('');
            disableAddToList(false);
            if (isPopupMode && self.parent.tb_remove)
                self.parent.tb_remove();
            return false;
        });

        $('#suggestAddNewItem_cancel').click(function() {
            $('.addToProductSetPlace').html('');
            disableAddToList(false);
            return false;
        });

        $('#suggestAddNewItem_ok').click(function() {
            $('#Tr_AddNewItemContainer input[type=radio]').attr("checked", "true");
            //$('#newChoiceType').show();
            //$('#newChoiceTypeLink').hide();
            //$('#Tr_AddNewItemContainer').show();
            $('#tr_ProductSetControlButtons').show();
            $('#div_ErrorMessageProductInProductSet').hide();
            $('#addToProductSet_Create').click();
            return false;
        });

        $('#addToProductSet_Create').click(function() {
            $('#addToProductSet_ListError, #addToProductSet_ListError2, #addToProductSet_RoomError, #addToProductSet_ChoiceError').hide();
            var selectedList = parseFloat($('#shoppingLists').val());
            var newList = "";
            var valid = true;

            //if ($('#newShoppingList').data('shown')==true)
            if ($('#newListBox').is(':visible')) {
                newList = $('#newShoppingList').val();
                $('#AddToProductSet_roomType').val($('#AddToProductSet_roomType_Popup').val());
            }
            if (newList != "")
                selectedList = 0;

            if (newList == "" && selectedList < 1) {
                $('#addToProductSet_ListError, #addToProductSet_ListError2').css('display', 'inline');
                valid = false;
            }

            var selectedRoom = parseFloat($('#AddToProductSet_roomType').val());
            if (selectedRoom < 1 && newList != '') {
                $('#addToProductSet_RoomError').css('display', 'inline');
                valid = false;
            }
            var choice = $('input[type=radio][name="choiceType"]:checked');
            var selectedChoice = "";
            var newItemName = "";
            var itemId = 0;
            if (choice.length != 0) {
                selectedChoice = choice.val();
                if (FinishingTypeId > 0) {
                    selectedChoice = 'finishing';
                    newItemName = null;
                } else if (selectedChoice == "newItem") {
                    newItemName = $("#div_newItemName").html();
                } else {
                    itemId = parseInt($('.browseGrid input:checked').val());
                }
            }
            else {
                $('#addToProductSet_ChoiceError').css('display', 'inline');
                valid = false;
            }

            if (valid) {
                $.cookie("selectedProductSet", selectedList, { expires: 30, path: "/" });
                if (!isPopupMode && (getFlashObject('StandaloneProductSetView') == null)) { // when Product has been added via Admin page (AddManufacturerProduct.aspx)
                    $.ajax({
                        type: "POST",
                        url: "/WebServices/Room.asmx/AddProductToRoomIdea",
                        contentType: "application/json; charset=utf-8",
                        data: JSON.stringify({ "roomIdeaId": selectedList, "productId": productId, "newRoomIdeaName": newList, "roomId": selectedRoom, "choice": selectedChoice, "newItemName": newItemName, "itemId": itemId }),
                        dataType: "json",
                        success: function(json) {
                            try {
                                $.cookie("selectedProductSet", json.d, { expires: 30, path: "/" });
                                fillProductSetSelector(true, false, json.d);
                                //InvokeExternalInterface( "StandaloneProductSetView", "setRoomIdeaId", json.d );
                                hidePreview3D(); // to refresh "Make Inactive" or "Delete" links on next show of Preview3D
                            }
                            catch (e) { }
                        }
                    });
                }
                else {
                    InvokeExternalInterface(isPopupMode, "StandaloneProductSetView", "addProductToRoomIdea", // pass parameters: "roomIdeaId", "productId", "choice", "newItemName", "itemId"
                    selectedList + "," + productId + "," + selectedChoice + "," + (newItemName ? newItemName : "-") + "," + itemId + "," + FinishingTypeId + "," + (FinishingType ? FinishingType : "-") + "," + "onProductSetItemUpdated");
                    hidePreview3D(); // to refresh "Make Inactive" or "Delete" links on next show of Preview3D
                }
                
                // Disable addToList links until flash invokes callback function onProductSetItemUpdated(...) or Cancel by user
                disableAddToList(true);

                $('.expandedContainer').html('');

                if ($('#tr_dialogBoxAddProductContainer').css('display') != 'none') {
                    $('#tr_dialogBoxAddProductContainer').slideToggle(1000, function() {
                        $('.addToProductSetPlace').html('');
                    });
                } else {
                    $('#tr_msgBoxAddProductContainer').hide();
                    $('#tr_msgBoxAddProductContainer').slideToggle(2000, function() {
                        $('#tr_msgBoxAddProductContainer').slideToggle(1000, function() {
                            $('.addToProductSetPlace').html('');
                        });
                    });
                }

                if (isPopupMode && self.parent.tb_remove)
                    self.parent.tb_remove();
            }

            return false;
        }); // $('#addToProductSet_Create').click(function() {

    });               // $($(this).parents('.listViewNarrow,.listView').get(0)).find('.addToProductSetPlace').load('/Shop/addToProductSet.htm', null, function() { 
}

function updateProductSetItems() {
    var index = $('.browseGrid').data('index');
    var count = $('.browseGrid>li').length;
    $('.browseGrid>li').hide();
    var startIndex = index * shiftStep - 1;
    if (startIndex < 0) {
        $('.browseGrid>li').slice(0, 3).show();
    } else {
        $('.browseGrid>li:gt(' + startIndex.toString() + ')').slice(0, 3).show();
    }
    $('.itemBrowseBar').css('display', (count < 3) ? 'none' : 'inline');

    if ($('#topChoice').length > 0 && $('#topChoice').get(0).checked)
        $('#topChoice').click();
    else if ($('#alternateChoice').length > 0 && $('#alternateChoice').get(0).checked)
        $('#alternateChoice').click();
}

function onItemBrowseBarLt() {
    var indx = $('.browseGrid').data('index') - 1;
    if (indx > -1) {
        $('.browseGrid').data('index', indx);
        updateProductSetItems();
    }
    return false;
}

function onItemBrowseBarRt() {
    var indx = $('.browseGrid').data('index') + 1;
    var itemsCount = ($('#topChoice').get(0).checked) ? TopChoiceItemsCount : AlternativeItemsCount;
    if (indx * shiftStep < itemsCount) {
        $('.browseGrid').data('index', indx);
        updateProductSetItems();
    }
    return false;
}


function CalendarOnChange(value) {
    if ($('#QAedFilter').attr('checked') == 'false')
        return false;
    var url = window.location.href;
    if (url.indexOf('qf') == -1)
        url = $('#filterTabs a:first').attr('href')
    var url = replaceQueryParameter(url, 'qd', (value != null ? value.replace(/\D/g, '') : null));
    if (window.location.href != url)
        window.location.href = url;
    return false;
};

function switchBookmarkStatus(mode) {
    var url = window.location.href;
    if (url.indexOf('bs') == -1)
        url = $('#filterTabs a:first').attr('href')
    var url = replaceQueryParameter(url, 'bs', mode);
    if (window.location.href != url)
        window.location.href = url;
    return false;
};

function switchBrandFilter(BrandId) {
    var url = window.location.href;
    if (url.indexOf('bf') == -1)
        url = $('#filterTabs a:first').get(0).getAttribute('href')
    var url = replaceQueryParameter(url, 'bf', BrandId);
    if (window.location.href != url)
        window.location.href = url;
    return false;
};


// Get a logical parameter from address string as part of a query parameter
function getParameterValue(url, name) {
    var decodedURI = decodeURIComponent(url);
    var slashIndex = decodedURI.lastIndexOf('/');
    var arr = decodedURI.substr(slashIndex + 1).split('-');
    var value = '';
    for (var i = 0, n = arr.length; i < n; i++) {
        if (arr[i] == name || (i == 0 && (arr[i].lastIndexOf(name) == arr[i].length - name.length))) {
            value = arr[i + 1];
            break;
        }
    }
    return value;
}

// Use this approach to avoid usage of a cache
function replaceQueryParameter(url, name, value) {
    var decodedURI = decodeURIComponent(url);
    var slashIndex = decodedURI.lastIndexOf('/')
    var baseUrl = decodedURI.substring(0, slashIndex + 1);

    var arr = decodedURI.substr(slashIndex + 1).split('-');
    for (var i = 0, n = arr.length; i < n; i++) {
        if (arr[i] == name) {
            arr[i + 1] = encodeURIComponent(value);
        } else {
            arr[i + 1] = encodeURIComponent(arr[i + 1]);
        }
        i++;
    }
    url = baseUrl + arr.join("-");
    return url;
}

// Use this approach to avoid usage of a cache
function reloadPageWithUniquePId(productId) {
    var url = window.location.href;
    var index = url.indexOf("pid=");
    url = (index == -1) ? url : url.substring(0, index - 1);
    url += "&pid=" + productId;
    window.location.href = url;
}

function setProductMDIPicked(productId, MDIPickedCheckBox) {
    $.ajax({
        type: "POST",
        url: "/WebServices/Product.asmx/SetMDIPicked",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ "productId": productId, "MDIPicked": MDIPickedCheckBox.checked }),
        dataType: "json",
        success: function(json) {}
    });
}

function hidePreview3D() {
    $('.preview3DPlace').html('');
    $('.preview3D').each(function() {
        this.removeAttribute("disabled");
    });
}

function onSwfobjectLoad() {
    onLoadHandler();
}

function getFlashObject(movieName) {
    var isIE = navigator.appName.indexOf("Microsoft") != -1;
    var flash = (isIE) ? window[movieName] : document[movieName];
    if (flash == null)
        flash = $('#' + movieName)[0];
    return flash;
}

function onLoadHandler() {
    try {
        window.clearInterval(interval3Drepresentation);
        getFlashObject("flashcontent_preview3D").setProductId(preview3DProductId);
        document.body.style.cursor = 'default';
    } catch (e) {
        document.body.style.cursor = 'wait';
        interval3Drepresentation = setInterval("onLoadHandler()", 100);
    }
}

function currentTimeToString() {
    var d = new Date();
    var curr_hour = twoDigit(d.getHours());
    var curr_min = twoDigit(d.getMinutes());
    var curr_sec = twoDigit(d.getSeconds());

    var curr_date = twoDigit(d.getDate());
    var curr_month = twoDigit(d.getMonth() + 1);
    var curr_year = twoDigit(d.getFullYear());

    var time = curr_month + "/" + curr_date + "/" + curr_year;  //+ " " + curr_hour + ":" + curr_min + ":" + curr_sec;
    return time;
}

function twoDigit(value) {
    return (value < 10) ? "0" + value : value;
}

function setAddProductSelection(selection) {
    if (selection == 0) {
        $('.browseGrid').html(TopChoiceItemsHtml);
        $('.browseGrid').data('index', 0);
        $('#addToProductSet_radioBoxList input[type=radio]:first').attr("checked", "true");
        $('#td_items_for_topchoice').html($('.itemBrowseBox').html());
        $('#td_items_for_alternative').html("");
    } else if (selection == 1) {
        $('.browseGrid').html(AlternativeItemsHtml);
        $('.browseGrid').data('index', 0);
        $('#td_items_for_topchoice').html("");
        $('#alternateChoice').attr("checked", "true");
        $('#td_items_for_alternative').html($('.itemBrowseBox').html());
    } else {
        $('#td_items_for_topchoice').html("");
        $('#td_items_for_alternative').html("");
        $('#newItem').attr("checked", "true");
    }
}

function showProductQAStatus(itemContainer) {
    var productIsActive = itemContainer.find('.productIsActive').text() == 'True';
    if (productIsActive) {
        itemContainer.find('.Accept').css('display', 'none');
        itemContainer.find('.Deny').css('display', '');
        itemContainer.find('#QAedInfo').css('display', '');
        itemContainer.find('#DeniedInfo').css('display', 'none');
    }
    else {
        itemContainer.find('.Accept').css('display', '');
        itemContainer.find('.Deny').css('display', 'none');
        itemContainer.find('#QAedInfo').css('display', 'none');
        itemContainer.find('#DeniedInfo').css('display', '');
    }
    itemContainer.find('#EditedInfo').css('display', itemContainer.find('#AccountId').text() != '0' ? '' : 'none');
    itemContainer.find('#BookmarkedInfo').css('display', itemContainer.find('#BMedAccountId').text() != '0' ? '' : 'none');
}


function showDeniedComment(itemContainer) {
    itemContainer.find('#DeniedCommentContainer').show();
    itemContainer.find('#DeniedCommentTextarea').text('');
}

function updateModifiedBy(itemContainer, item, accountName, date, modifyType, deniedComment)
{
    var info = accountName != ""
        ? "<span class='txtGray'><b>" + modifyType + " by </b></span>" + accountName
            + "<span class='txtGray'><b> on </b></span>" + date
            + (deniedComment != "" ? " with comment: " + deniedComment : "")
        : "";
    item.html(info);
}

function initFinishingTypeList(items, isRetailerProductList, addToListButtonId) {
    var html = '<select id="finishingTypeListId" size="' + items.length + '"  onclick="selectFinishingType(\'finishingTypeListId\', ' + (isRetailerProductList ? 'true' : 'false') + ',\'' + addToListButtonId + '\' )" >';

    for (var i = 0; i < items.length; i++) {
        var selected = (i == 0 ? 'selected="selected"' : '');
        html += '<option value="' + items[i].Id + '" ' + selected + '>' + items[i].Title + '</option>';
    }
    html += '</select>';
    //alert(html);

    return html;
}

function selectFinishingType(finishingTypeList, isRetailerProductList, addToListButtonId) {
    var option = $('#finishingTypeListId').find('option[selected=true]');
    FinishingType = option.text();
    FinishingTypeId = option.val();  
    var addToListButton = $('#' + addToListButtonId ); 
    var productId, categoryId;
    var targetUrl, targetImageUrl;
    var has3DRepresentation = false;
    
    if (isRetailerProductList) {
        productId = TrimString(addToListButton.find('.targetId').text());
        has3DRepresentation = (TrimString(addToListButton.find('.hasRepresentation3D').text()) != 'False');
        retailerId = TrimString(addToListButton.find('.retailerId').text());
        categoryId = TrimString(addToListButton.find('.mdiCategoryId').text());
        targetUrl = TrimString(addToListButton.find('.targetUrl').text());
        targetImageUrl = TrimString(addToListButton.find('.targetImageUrl').text());
    } else {
        productId = TrimString(addToListButton.parents('#itemContainer').find('.productId').text());
        has3DRepresentation = (TrimString(addToListButton.find('.hasRepresentation3D').text()) != 'False');
        retailerId = 'undefined';
        categoryId = TrimString(addToListButton.find('.categoryId').text());
        targetUrl = TrimString(addToListButton.find('.targetUrl').text());
        targetImageUrl = TrimString(addToListButton.find('.targetImageUrl').text());
    }

    addProductToProductSet(addToListButton, isRetailerProductList, productId, categoryId, targetUrl, targetImageUrl, retailerId, has3DRepresentation);
}

function addProductToProductSet(addToListButton, isRetailerProductList, productId, categoryId, targetUrl, targetImageUrl, retailerId, has3DRepresentation) {
    if (isRetailerProductList) {
        // start Wizard's introduction
        if (!isApproved) { userLogin(); return false; }

        var pageurl = "/bookmarkOverlay/intro?productid={0}&categoryId={1}&url={2}&imageurl={3}&retailerid={4}&placeValuesBeforeTB_=savedValues&TB_iframe=true&height=540&width=650&modal=true";
        tb_show('', pageurl.replace('{0}', productId).replace('{1}', categoryId).replace('{2}', targetUrl).replace('{3}', targetImageUrl).replace('{4}', retailerId));
    }
    else {
        productSetPlace = $(addToListButton.parents('.listViewNarrow,.listView').get(0)).find('.addToProductSetPlace');
        if (!isApproved) {
            //alert('!isApproved');
            if (!has3DRepresentation) {
                var pageurl = "/shop/BookmarkItem.html?productId={0}&categoryId={1}&placeValuesBeforeTB_=savedValues&TB_iframe=true&height=540&width=700&modal=true";
                tb_show('', pageurl.replace('{0}', productId).replace('{1}', categoryId));
            }
            else {
                addToProductSet(productSetPlace, productId, categoryId, 0);
            }
        } else if (isAdmin) {
            window.location.href = "/Shop/AddManufacturerProduct.aspx?url=" + encodeURIComponent(window.location.href) + "&pid=" + productId + "&add_to_room=1";
            //alert('isAdmin');
        } else {
            //alert('is Normal user');
            if (!has3DRepresentation) {
                // jump to step2 (3D representation)
                var pageurl = "/bookmarkOverlay/step1?productid={0}&categoryId={1}&url={2}&imageurl={3}&retailerid={4}&firstStep=2&placeValuesBeforeTB_=savedValues&TB_iframe=true&height=540&width=974&modal=true";
                tb_show('', pageurl.replace('{0}', productId).replace('{1}', categoryId).replace('{2}', targetUrl).replace('{3}', targetImageUrl).replace('{4}', retailerId));
            }
            else {
                addToProductSet(productSetPlace, productId, categoryId, 0);
            }
        }
    }
}


function showTopAlternateSelector(productPosition) {
    $('#tr_dialogBoxAddProductContainer').hide();
    $('#Tr_TopAlternateSelector').show();
    setAddProductSelection(productPosition);
    updateProductSetItems();
    
    return false;
}

function onProductSetItemUpdated(id) {
    disableAddToList(false);
}

function disableAddToList(flag) {
    var list = (isPopupMode) ? self.parent.$('.addToList') : $('.addToList');
    if (flag == true) {
        list.attr("disabled", true);
    } else {
        list.each(function() {
            if ($(this).hasClass("isBookmarkedAffiliate")) {
                $(this).hide();
            } else {
                $(this).attr("disabled", false);
            }
        });
    }
}

function onChangeRoomIdea(roomIdeaId) {
    //alert("onChangeRoomIdea: " + roomIdeaId)
    isPending = false;
}

function TrimString(sInString) {
    sInString = sInString + ''; // to convert integer to string
    sInString = sInString.replace(/ /g, ' ');
    return sInString.replace(/(^\s+)|(\s+$)/g, '');
}