var isAddRoom = false;
var isWithinIFrame = false;
var isProductsetInitialized = false;
var ROOMTYPE_KITCHEN = 1;

$(document).ready(function () {
    productset_initialize();
    fillProductSetSelector(true);
    $('#tryItNowLink').click(function () { init_tryItNowLink() });
});

function productset_initialize() {
    var decodedURI = unescape(document.location.href);
    isAddRoom = (decodedURI.indexOf('addroom=true') != -1);
    isWithinIFrame = (decodedURI.indexOf('iframe=true') != -1);
    
    $("#selectProductSet").bind('reloadProductset', function(e, startSelectedValue, startSelectedText) {
        fillProductSetSelector(false, startSelectedValue, startSelectedText);
    });

    $("#selectProductSet").change(function () {
        productSetChange($(this));
    });
}

// This function is executed when Productset's selected value is changed.
// Duplicate calls are postponed by comparing a selected value and cookie, which should be different. 
// Parameter force == true to force execute all code even if a selected value and cookie are equal.
function productSetChange(productSetControl, force) {
    force = force == null ? false : force;

    var selectedOption = productSetControl.find("option:selected");
    if (selectedOption.attr("id") == "create3DShoppingListOption") {
        selectedOption[0].removeAttribute("selected");
        productSetControl.find("option")[0].setAttribute("selected", "selected");
        createNewRoom();
        return;
    }

    var selectedValue = productSetControl.val();
    if (selectedValue == $.cookie("selectedProductSet") && isProductsetInitialized && !force)
        return;
    
    if (selectedValue != $.cookie("selectedProductSet")) {
        $.cookie("showAllCategories", null, { expires: 30, path: "/" });
    }

    var type = selectedOption.data("type");
    if (!type)
        type = null;
    $.cookie("selectedRoomType", type, { expires: 30, path: "/" });

    if (selectedValue != '0') {
        var selectedText = selectedOption.text();
        var callback = 'fillProductSetSelector(false, 0)';
        initEditRemoveRoomDesign(selectedValue, selectedText, callback);
        isStandaloneProductSetViewReady = false;
        InvokeExternalInterface(false, "StandaloneProductSetView", "setRoomIdeaId", selectedValue);
        $('.addToList').each(function () {
            $('.addToProductSetPlace').html('');
        });
    } else if (selectedValue == '0') {
        // reset flash application
        showDependedControls($("#selectProductSet"), selectedValue, type);
    }   

    if (isProductsetInitialized)
        $.cookie("selectedProductSet", selectedValue, { expires: 30, path: "/" });
    updateCategoriesMenu();
    isProductsetInitialized = true;

    setTimeout('onProductSetReady();', 10);
}


function onProductSetReady() {
    // wait while currentProductSet will be loaded
    if (waitUntilProductsetIsReady(onProductSetReady)) return;

    var type = $.cookie("selectedRoomType");
    var productSetControl = $("#selectProductSet");
    var selectedValue = productSetControl.val();

    showDependedControls(productSetControl, selectedValue, type);
}

function showDependedControls(productSetControl, selectedValue, type) {
    if (selectedValue != '0') {
        if (productSetControl.is(":visible")) {
            $("#ad_banner").show();
            $("#ad_banner2").hide();
        }

        $.ajax({
            type: "POST",
            url: "/WebServices/Room.asmx/ShowOnly3DButton",
            contentType: "application/json; charset=utf-8",
            data: "{}",
            dataType: "json",
            success: function (json) {
                var show3DButton = json.d;
                if (show3DButton)
                    $(".show3DProductsBtn").show();
                else
                    $(".show3DProductsBtn").hide();
            }
        });

        $("#btn_buy_room,#div_clientflashContainer").show();
        if (isMyRoomRolloverOpened())
            $("#productset_independed_group").hide();               
    }
    else {
        if (productSetControl.is(":visible")) {
            $("#ad_banner").hide();
            $("#ad_banner2").show();
        }
        $(".show3DProductsBtn,#btn_buy_room,#div_clientflashContainer").hide();
        $("#productset_independed_group").show();
        hideEditRemoveRoomDesign();
    }
    filter3DProducts();
}

function filter3DProducts() {
    var showOnly3D = $(".CheckBoxShow3D").children();
    if (showOnly3D.length == 0) // when productset.js is used within a page without CheckBoxShow3D control. TODO: remove this function from this file.
        return;

    var selectedValue = $("#selectProductSet").val();
    var previousState = $.cookie("filterOnly3DProductsPrevious");
    
    //reset to default value (checked)
    if (selectedValue == '0' && !showOnly3D.is(':checked')) {
        //simulate click for call postback within updatepanel     
        $.data(showOnly3D.get(0), 'force_update', true);
        showOnly3D.click();
        return;
    }

    //compare previous and current filter state and do postack if needed
    $.ajax({
        type: "POST",
        url: "/WebServices/Room.asmx/FilterOnly3DProducts",
        contentType: "application/json; charset=utf-8",
        data: "{}",
        dataType: "json",
        success: function (json) {
            if (previousState == null || previousState.toLowerCase() != json.d.toString().toLowerCase()) {
                postBack();
            }
        }
    });
}


function updateCategoriesMenu() {
    $.ajax({
        type: "POST",
        url: "/WebServices/ProductCategory.asmx/GetCategoriesMenuHTML",
        contentType: "application/json; charset=utf-8",
        data: "{}",
        dataType: "json",
        success: function (json) {
            $(".dropdownmenu-container").html(json.d);
        }
    });
}

function productset_showCreationPopup(placeholder, callback)
{
    $('#SubmitProductSet').data( "callback", callback );
    $(placeholder).load("/Shop/createSet.htm", null, function(responseText, textStatus, XMLHttpRequest) {
        $(this).modal();
        // fill room selector async
        $.ajax({
            type: "POST",
            url: "/WebServices/Room.asmx/RoomList",
            contentType: "application/json; charset=utf-8",
            data: "{}",
            dataType: "json",
            success: function(json) {
                $("#roomSelector").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;
                });

                $("#roomSelector").html(html);
            }
        });

        $("a[name=NaturalSurroundings]").click(function() {
            $("#input_Surroundings").val($(this).text());
            return false;
        });

        $("a[name=DesignGoals]").click(function() {
            $("#input_DesignGoals").val($(this).text());
            return false;
        });

        $('#SubmitProductSet').click(function() {
            var name = $('#input_productSetName').val();
            var naturalSurroundings = $('#input_Surroundings').val();
            var designGoals = $('#input_DesignGoals').val();
            var tags = $('#input_Tags').val();
            var templateId = $("#mdiSlider input")[$("#mdiSlider").data("selected")].value;
            var roomTypeId = $('#roomSelector').val();
            if (roomTypeId == null)
                roomTypeId = ROOMTYPE_KITCHEN;

            var data = JSON.stringify({ "name": name, "naturalSurroundings": naturalSurroundings, "tags": tags, "designGoals": designGoals, "roomTypeId": roomTypeId, "templateId": templateId });

            $.ajax({
                type: "POST",
                url: "/WebServices/Room.asmx/CreateRoomIdea",
                contentType: "application/json; charset=utf-8",
                data: data,
                dataType: "json",
                success: function(json) {
                    if (callback != null)
                        callback(json.d);
                    fillProductSetSelector();
                    if ($(".inputProductSet")) {
                        $(".inputProductSet").val(json.d);
                        $.cookie("selectedProductSet", json.d, { expires: 30, path: "/" });
                    }
                }
            });

            $.modal.close();
            return false; // suppress default handler
        });
    });
}

function fillProductSetSelector(disableFlashNotification, startSelectedValue, startSelectedText) {
    var selectedValue = $.cookie( "selectedProductSet");
    if ( startSelectedValue != null )
        selectedValue = startSelectedValue;
    if ( selectedValue == null || selectedValue.toString() == '0') 
    { 
        selectedValue = '';
    };
    
    var html = "<option value=\"0\">Select My Room</option>";

    if (!isApproved) {
        var needProductSetUpdate = false;
        var roomType = new Object();       
        if (tempdesigncontent != null && tempdesigncontent.getTempDesignList != null) {
            $("#selectProductSet").removeAttr("disabled");

            var designList = tempdesigncontent.getTempDesignList();
            if (designList.length > 0) {
                var design = designList[0];
                roomType[design[0]] = design[2];
                //alert("Temp Design: [id=" + design[0] + ", name=" + design[1] + "]  from " + designList);
                needProductSetUpdate = ($("#selectProductSet option[value='" + design[0] + "']").length == 0);
                var selectedHtml = '';
                if (design[0] == selectedValue)
                    selectedHtml = "selected='true'";
                html += "<option id=\"tempRoomIdeaOption\" value=\"" + design[0] + "\" " + selectedHtml + ">" + design[1] + "</option>";
                setShoppingListCount(1);
            }
            else {
                needProductSetUpdate = ($("#selectProductSet option[value='" + $.cookie("selectedProductSet") + "']").length > 0);
            }
        }
        $("#selectProductSet").html(html);
        jQuery.each($("#selectProductSet option"), function () {
            var type = roomType[this.value];
            if (type)
                $(this).data("type", type);
        });

        if (disableFlashNotification != true && needProductSetUpdate) {
            setTimeout('productSetChange($("#selectProductSet"));', 10);
        }
    }
    else {
        if (tempdesigncontent != null && tempdesigncontent.getTempDesignList != null) {
            var designList = tempdesigncontent.getTempDesignList();
            if (designList.length > 0) {
                // move tempDesign to Server
                var tempDesignId = designList[0][0];
                tempdesigncontent.uploadDesign(tempDesignId, 'onDesignUploaded');
                return;
            }            
        }

        $.ajax({
            type: "POST",
            url: "/WebServices/Room.asmx/GetMyRoomIdeas",
            contentType: "application/json; charset=utf-8",
            data: "{}",
            dataType: "json",
            success: function (json) {
                $("#selectProductSet").removeAttr("disabled");

                //var html = "<option value=\"0\">Select My Room</option><option id=\"create3DShoppingListOption\" value=\"0\">Create My Room</option>";
                html += "<option id=\"create3DShoppingListOption\" value=\"0\">Create My Room</option>";
                var roomType = new Object();
                jQuery.each(json.d, function () {
                    var selectedHtml = '';
                    if (selectedValue.toString() == this.Id.toString())
                        selectedHtml = ' selected=\"true\"';
                    html += "<option value=\"" + this.Id.toString() + "\" " + selectedHtml + " >" + this.Name + "</option>";
                    roomType[this.Id.toString()] = this.Type;
                    return true;
                });
                if (selectedValue.length != 0)
                    $('#div_clientflashContainer').show();

                $("#selectProductSet").html(html);
                jQuery.each($("#selectProductSet option"), function () {
                    var type = roomType[this.value];
                    if (type) 
                        $(this).data("type", type);                    
                });


                if (disableFlashNotification != true) {
                    setTimeout('productSetChange($("#selectProductSet"));', 10);
                }
            }
        });
    }
}

/* handler called from TempDesign flash */
function onDesignUploaded(roomId) {
    changeShoppingListCount(1);
    setTimeout('fillProductSetSelector(false, ' + roomId + ')', 10);
}

function initEditRemoveRoomDesign(selectedValue, selectedText, callback) {
    var EditRemoveRoomDesignControl = $('#shopnav_EditRemoveRoomDesignContainer > .EditRemoveRoomDesignBase');
    $(EditRemoveRoomDesignControl).find('.EditRemoveRoomId').text(selectedValue);
    $(EditRemoveRoomDesignControl).find('.EditRemoveRoomName').text(selectedText);
    $(EditRemoveRoomDesignControl).find('.EditRemoveCallback').text(callback);
    $('#shopnav_EditRemoveRoomDesignContainer').show();
}

function hideEditRemoveRoomDesign() {
    $('#shopnav_EditRemoveRoomDesignContainer').hide();
}

/*
id=6, 
appearances=[7,8,9,10,11,12,13,14],
refinementOptions=['capacity-lessthan1.2cu.ft.', 'type-overtherange']
*/
function searchNewProduct(id, appearances, refinementOptions) {
    document.location.href = getSearchProductURL(id, appearances, refinementOptions);
}

function textSearchNewProduct(categoryId, query) {
    document.location.href = getSearchProductsUrl(categoryId, query);
}

/* Default handler called from StandaloneProductSetView flash */
function onUpdateProductSetItem() {
    updateShoppingListContent(false);
}


/* Default handler called from StandaloneProductSetView flash */
function onLoadRoomIdea() {
    isStandaloneProductSetViewReady = true;
}


function init_tryItNowLink() {
    var currentProductSet = $("#selectProductSet").get(0);
    if (!isApproved && currentProductSet != null && currentProductSet.options.length > 1) {
        // Not registered user can't create more than 1 room
        if (!isMyRoomRolloverOpened()) {
            var selectedValue = $.cookie("selectedProductSet");
            if (selectedValue == '0') {
                currentProductSet.selectedIndex = 1;
                $.cookie("selectedProductSet", currentProductSet.options[1].value, { expires: 30, path: "/" });
            }
            MyRoomRolloverDown();
        }
        //return;
    }
    createNewRoom();
}




