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;
var OTHER_OTHER_CATEGORY_ID = 220;

$(document).ready(function () {
    productlist_initialize();
});  // $(document).ready(function()

function productlist_initialize() {
        $('#pageContainer').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();
        }
        // add button in new ProductGridView
        $('.prodAddRoom').click(function () {
            ////debugger;
            var selectedProductSetIndex = $.cookie("selectedProductSet");
            if (selectedProductSetIndex != 0 && selectedProductSetIndex != null) {
                onAddRoom(this);
            }
            else {
                // Create a room
                var li = $(this).parent().parent().parent().parent().parent();
                var targetId = li.find('.targetId').text();
                var backurl = escape(getPageUrlWithoutParams(['action']) + '?action=' + PAGE_ACTION_ADD_PRODUCT + '&id=' + targetId);
                createNewRoom(null, backurl);
            }

            return false;
        });


        $('.commentsToggle').each(function () {
            loadProductCommentCount(this);
        });


        $('.commentsToggle').click(function () {
            var isRegistered = false;
            isUserRegistered(function (value) {
                isRegistered = value;
            }, false);
            if (!isRegistered) {
                var message = 'to post your comment about this Product';
                doLoginOverlay(message, postProductComment, [this]);
                return false;
            }
            postProductComment(this);
            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", "flashcontent_preview3D", "440", "239", "10.0.0.0", null, 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 productlist_initialize()


function postProductComment(control) {
    var productId = $(control).find('div.targetId').text();
    var hide = $(control).hasClass('medArrowOn');
    $('.commentsToggle').removeClass('medArrowOn');
    if (hide)
        $('#commentsBox').slideUp(400, function () {
            $('.commentsPlace').html('');
        });
    else
        $('.commentsPlace').html('');
    if (!hide) {
        $(control).addClass('medArrowOn');
        $(control).parents('.itemContainer').find('.commentsPlace').load('/Shop/commentsBox.htm', null, function () {
            updateProductComments(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) {
                        updateProductComments(productId);
                        loadProductCommentCount($('.medArrowOn')[0]);
                    }
                });
                $('#commentTextBox').val('');
                return false;
            });

            $('.closeCommentsToggle').click(function () {
                slideHideComments();
                return false;
            });
        });
    }

} // postProductComment()


function updateProductComments(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);
        }
    });
}


function loadProductCommentCount(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");
        }
    });
}


function slideHideComments() {
    $('#commentsBox').slideUp(400, function () {
        $(this).parents('.commentsPlace').html('');
        $('.commentsToggle').removeClass('medArrowOn');
    });
}


function onAddRoom(commandLink) {

    if (    (!isApproved && tempdesigncontent == undefined)
         || (isMyRoomRolloverExists() && isMyRoomRolloverOpened() && !isStandaloneProductSetViewReady)
         || (isMyRoomRolloverExists() && !isMyRoomRolloverOpened())
       ) 
    {
        setTimeout("onAddRoom(document.getElementById('" + commandLink.id + "'));", 100);
        if (isMyRoomRolloverExists() && !isMyRoomRolloverOpened()) {
            setTimeout('MyRoomRolloverDown();', 10);
        }
        return;
    }

    if ($(commandLink).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 li = $(commandLink).parent().parent().parent().parent().parent();

    var addToListButton = $(commandLink);
    var decodedURI = unescape(document.location.href);
    var isRetailerProductList = false;

    var productId = TrimString(li.find('.productId').text());
    if (productId == '') {
        isRetailerProductList = true;
        productId = TrimString(li.find('.offerId').text());
    }

    var has3DRepresentation = (TrimString(li.find('.hasRepresentation3D').text()) == 'true');
    var retailerId = TrimString(li.find('.retailerId').text());
    var categoryId = TrimString(li.find('.categoryId').text());
    if (categoryId == '') categoryId = '0';

    var targetUrl = TrimString(li.find('.targetUrl').text());
    var targetImageUrl = TrimString(li.find('.targetImageUrl').text());

    $('.addToProductSetPlace').html('');
    $('.finishingTypeContainer').html('');

    $.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 = li.find('.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 });
                finishingTypeContainer.mouseover();

            } else {
                if (items.length == 1) {
                    FinishingTypeId = items[0].Id;
                    FinishingType = items[0].Title;
                } else {
                    FinishingTypeId = 0;
                    FinishingType = "";
                }
                addProductToProductSet(li, isRetailerProductList, productId, categoryId, targetUrl, targetImageUrl, retailerId, has3DRepresentation);
            }
        },
        error: function (data) {
            alert('error:' + data.responseText);
        }
    });
}

function selectFinishingType(finishingTypeList, isRetailerProductList, addToListButtonId) {
    var option = $('#finishingTypeListId').find('option[selected=true]');
    FinishingType = option.text();
    FinishingTypeId = option.val();
    var addToListButton = $('#' + addToListButtonId);

    var li = addToListButton.parent().parent().parent().parent().parent();
    var currentProductSet = $("#selectProductSet").get(0);
    var decodedURI = unescape(document.location.href);
    var isRetailerProductList = false;

    var productId = TrimString(li.find('.productId').text());
    if (productId == '') {
        isRetailerProductList = true;
        productId = TrimString(li.find('.offerId').text());
    }

    var has3DRepresentation = (TrimString(li.find('.hasRepresentation3D').text()) == 'true');
    var retailerId = TrimString(li.find('.retailerId').text());
    var categoryId = TrimString(li.find('.categoryId').text());
    if (categoryId == '') categoryId = '0';

    var targetUrl = TrimString(li.find('.targetUrl').text());
    var targetImageUrl = TrimString(li.find('.targetImageUrl').text());

    /*
    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(li, isRetailerProductList, productId, categoryId, targetUrl, targetImageUrl, retailerId, has3DRepresentation);
}

// internal functions

function prepareAdToProductSet(productSetPlace, productId, categoryId, productPosition, isProductInRoom, items, productTitle) {
    productTitle = (categoryId == OTHER_OTHER_CATEGORY_ID ? productTitle : productCategory.Title);
    if (isProductInRoom && items.length == 1) {
        $('#div_ErrorMessageProductInProductSet').show();
        $('#Tr_TopAlternateSelector').hide();
        $("#tr_ProductSetControlButtons").hide();
        
        $("#div_newItemName").html(productTitle + " 1");///////////////////////////
        return;
    }

    TopChoiceItemsCount = 0;
    AlternativeItemsCount = 0;
    TopChoiceItemsHtml = '';
    AlternativeItemsHtml = '';

    //debugger;

    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(productTitle + " " + (TopChoiceItemsCount + 1));
    $('#div_ErrorMessageProductInProductSet').hide();
    
    setAddProductSelection(productPosition);
    updateProductSetItems();
    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;
    });

    //debugger;
    var showDialog = false;
    var showMsgBox = false;
    if (TopChoiceItemsCount == 0) {
        // Select New Item radiobutton
        $('#addToProductSet_radioBoxList #newItem').attr("checked", "true");
        showMsgBox = true;
    }

    if (TopChoiceItemsCount == 1 && (items[0].TopChoice == 0 || FinishingTypeId != 0)) {
        // Select first TopChoice in ProductSetItem
        $('#addToProductSet_radioBoxList #topChoice').attr("checked", "true");
        showMsgBox = true;
    }

    //if (TopChoiceItemsCount == 1 && categoryId != OTHER_OTHER_CATEGORY_ID && (items[0].TopChoice != 0 || FinishingTypeId == 0)) {
    if (TopChoiceItemsCount == 1 && categoryId != OTHER_OTHER_CATEGORY_ID && items[0].TopChoice != 0) {
        // Open a Dialog for setup first TopChoice in ProductSetItem with an ability to interrupt by HOLD On link
        $('#addToProductSet_radioBoxList #topChoice').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();
        showDialog = true;
    }

    if (categoryId == OTHER_OTHER_CATEGORY_ID) {
        if (items[0].TopChoice == 0) {
            $('#addToProductSet_radioBoxList #topChoice').attr("checked", "true");
            showMsgBox = true;
        }
        else {
            $('#addToProductSet_radioBoxList #newItem').attr("checked", "true");
            showMsgBox = false;
            showDialog = false;
        }
    }

    if (showDialog) {
        //$("#tr_ProductSetControlButtons").show();
        $("#tr_dialogBoxAddProductContainer")
            .slideDown(500)
            .delay(3000, function () {
                addToProductSet_Create_click(productId);
            })
            .slideUp(500)
            .delay(0, function () {
                $('.expandedContainer').hide();
                $('.addToProductSetPlace').html('');
            });
        return;
    }

    if (showMsgBox) {
        $("#tr_msgBoxAddProductContainer")
            .slideDown(800, function () {
                addToProductSet_Create_click(productId);
            })
            .slideUp(800, function () {
                $('.expandedContainer').hide();
                $('.addToProductSetPlace').html('');
            });
        return;
    }

    $("#tr_ProductSetControlButtons,#Tr_TopAlternateSelector").show();
}

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) {
    //debugger;
    if (selection == 0) {
        $('.browseGrid').html(TopChoiceItemsHtml);
        $('.browseGrid').data('index', 0);
        //$('#addToProductSet_radioBoxList input[type=radio]:first').attr("checked", "true");
        $('#topChoice').attr("checked", "true");
        $('#td_items_for_topchoice').html($('.itemBrowseBox').html());
        var firstitem = $('.browseGrid input[type=radio]:first');
        firstitem.attr("checked", "true");
        $('#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());
        var firstitem = $('.browseGrid input[type=radio]:first');
        firstitem.attr("checked", "true");
    } 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 addProductToProductSet(itemContainer, isRetailerProductList, productId, categoryId, targetUrl, targetImageUrl, retailerId, has3DRepresentation) {
    productSetPlace = itemContainer.find('.addToProductSetPlace');
    if (isRetailerProductList) {
        $.ajax({
            type: "POST",
            url: "/WebServices/Product.asmx/GetProductByAffiliateProduct",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ "affProductId": productId, "affProviderId": retailerId }),
            dataType: "json",
            success: function (json) {
                //debugger;
                productId = json.d.Id;
                categoryId = json.d.CategoryId;
                has3DRepresentation = (json.d.Representation3D != null) && (json.d.Representation3D.length > 0);
                if (isAdmin) {
                    if (has3DRepresentation && !confirm("The product has already 3D representation. Do you want to edit it?")) {
                        addToProductSet(productSetPlace, productId, categoryId, 0, json.d.OriginalTitle);
                        return;
                    }
                    window.location.href = "/Shop/AddManufacturerProduct.aspx?url=" + encodeURIComponent(window.location.href) + "&pid=" + productId + "&add_to_room=1";
                } else {
                    addToProductSet(productSetPlace, productId, categoryId, 0, json.d.OriginalTitle );
                }
            }
        });        
    }
    else {
        if (isAdmin) {
            if (has3DRepresentation && !confirm("The product has already 3D representation. Do you want to edit it?")) {
                var productName = itemContainer.find('.prodName').get(0).outerText;
                addToProductSet(productSetPlace, productId, categoryId, 0, productName);
                return;
            }
            window.location.href = "/Shop/AddManufacturerProduct.aspx?url=" + encodeURIComponent(window.location.href) + "&pid=" + productId + "&add_to_room=1";
        } else {
            var productName = itemContainer.find('.prodName').outerText;
            addToProductSet(productSetPlace, productId, categoryId, 0, productName);
        }
    }
}

/* 
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, productTitle) {

    if (productTitle == '' || productTitle == undefined) {
        //debugger;
    }

    productSetPlace.load('/Shop/addToProductSet.htm', function () {

        //$(addToListButton.parents('.listViewNarrow,.listView').get(0)).find('.addToProductSetPlace').load('/Shop/addToProductSet.htm', null, function() {

        //alert("/Shop/addToProductSet.htm loaded");


        $("#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) {
                    //debugger;
                    if (!json.d)
                        return;

                    var appearanceId = json.d.AppearanceId;

                    //debugger;
                    $('#StandaloneProductSetView').externalInterface({
                        method: 'getRoomIdea',
                        args: [selectedValue, categoryId, productId, productTitle, FinishingTypeId, appearanceId],
                        success: function (data) {
                            //debugger;
                            //alert('success! flash returned: ' + data);
                            if (data == null || data.ProductSetItems.length == 0)
                                return;
                            prepareAdToProductSet(productSetPlace, productId, categoryId, productPosition, data.IsProductInRoom, data.ProductSetItems, productTitle);
                        },
                        error: function (error) {
                            //alert('there was an error: ' + error);
                        }
                    });
                }
            });
            //}
            //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) {
            //            //debugger;
            //            if (!json.d)
            //                return;
            //            var items = json.d.ProductSetItems;

            //            prepareAdToProductSet(productSetPlace, productId, categoryId, productPosition, json.d.IsProductInRoom, items, productTitle);
            //        }
            //    });
            //}
        }); // $("#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);
                        var selectedHtml = '';
                        if (design[0] == $.cookie("selectedProductSet"))
                            selectedHtml = "selected='true'";
                        html += "<option id=\"tempRoomIdeaOption\" value=\"" + design[0] + "\" " + selectedHtml + " >" + 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(productTitle);
                        $("#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(productId);
            $('.expandedContainer').html('');
            $('.addToProductSetPlace').html('');
            return false;
        });

        $('#addToProductSet_Create').click(function () {
            addToProductSet_Create_click(productId);
            $('.expandedContainer').html('');
            $('.addToProductSetPlace').html('');
        }); // $('#addToProductSet_Create').click(function() {

    });                     // $($(this).parents('.listViewNarrow,.listView').get(0)).find('.addToProductSetPlace').load('/Shop/addToProductSet.htm', null, function() { 
}

function addToProductSet_Create_click(productId) {
    //debugger;
    $('#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);

        if (isPopupMode && self.parent.tb_remove)
            self.parent.tb_remove();
    }
    else {
        //debugger; // not valid
    }    
}

function showTopAlternateSelector(productPosition) {
    $('#tr_dialogBoxAddProductContainer').clearQueue().stop().hide();
    $('#Tr_TopAlternateSelector,#tr_ProductSetControlButtons').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, '');
}

function doProductListAction(action) {
    var id = unescape($.query.get('id'));
    // wait while currentProductSet will be loaded
    if (waitUntilProductsetIsReady("doProductListAction('" + action + "')")) return;

    if (isActionActive()) {
        $.cookie("isActionActive", false, { expires: 1, path: "/" });

        if (action == PAGE_ACTION_ADD_PRODUCT) {
            var id = unescape($.query.get('id'));
            $('.targetId').each(function () {
                if ($(this).text() == id) {
                    var href_id = $(this).parent().find('.prodAddRoom').attr('id');
                    setTimeout("$('#" + href_id + "').click();", 10);
                }
            });
        }
        else if (action == PAGE_ACTION_ADD_ROOM) {
            createNewRoom();
        }
        else if (action == PAGE_ACTION_DESIGN_ROOM) {
            openDesignRoomPopup();
        }
    }
}

function isActionActive() {
    var result = $.cookie("isActionActive");
    return (result == undefined || result == null) ? false : result == "true";
}

