var isAddRoom = false;
var isWithinIFrame = false;

$(document).ready(function() {
    var decodedURI = unescape(document.location.href);
    isAddRoom = (decodedURI.indexOf('addroom=true') != -1);
    isWithinIFrame = (decodedURI.indexOf('iframe=true') != -1);
    
    fillProductSetSelector();

    $("#selectProductSet")
        .bind('reloadProductset', function(e, startSelectedValue, startSelectedText) {
            fillProductSetSelector(false, startSelectedValue, startSelectedText);
        });

    $("#selectProductSet").change(function() {
        var selectedValue = $(this).val();
        if (selectedValue != '0') {
            $('#div_clientflashContainer').show();
            var selectedText = $(this).find("option:selected").text();
            var callback = 'fillProductSetSelector()';
            initEditRemoveRoomDesign(selectedValue, selectedText, callback);
            InvokeExternalInterface(false, "StandaloneProductSetView", "setRoomIdeaId", selectedValue);
            $('.addToList').each(function() {
                $('.addToProductSetPlace').html('');
            });
        }
        else {
            hideEditRemoveRoomDesign();
            if ($(this).find("option:selected").attr("id") == "create3DShoppingListOption") {
                $(this).find("option:selected")[0].removeAttribute("selected");
                $(this).find("option")[0].setAttribute("selected", "selected");

                var isApproved = false;
                isUserApproved(function(value) {
                    isApproved = value;
                }, false);
                if (!isApproved) {
                    userLogin(isWithinIFrame ? 'fromiframe=mdiFrame' : null);
                    return false;
                }

                $('.createList').click();
            }
            else {
                $('#div_clientflashContainer').hide();
            }
        }

        $.cookie("selectedProductSet", selectedValue, { expires: 30, path: "/" });
    });


});

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 = 1;

            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) {
        if (tempdesigncontent != null && tempdesigncontent.getTempDesignList != null) {
            $("#selectProductSet").removeAttr("disabled");

            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);  
            }
        }
        $("#selectProductSet").html(html);
        $("#selectProductSet").change();
    }
    else {
        if (tempdesigncontent != null && tempdesigncontent.getTempDesignList != null) {
            var designList = tempdesigncontent.getTempDesignList();
            if (designList.length > 0) {
                // move tempDesign to Server
                tempdesigncontent.uploadDesign(designList[0][0]);
                $.cookie("selectedProductSet", designList[0][0], { expires: 1, path: "/" });
                changeShoppingListCount(1);
                setTimeout('fillProductSetSelector()', 200);
            }            
        }
        
        $.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>";

                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>";
                    return true;
                });
                if (selectedValue.length != 0)
                    $('#div_clientflashContainer').show();

                $("#selectProductSet").html(html);

                if (disableFlashNotification != true)
                    setTimeout('$("#selectProductSet").change();', 1000);
            }
        });
    }
}

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);
}