$(function() {

    /* ==============================================
    Load scripts
    =============================================== */

    $.when(
        $.getScript("//media.facecake.com/dev/NARS-test/js/animatedModal.min.js"),
        $.getScript("//media.facecake.com/dev/NARS-test/js/plugins.js"),
        $.Deferred(function(deferred) {
            $(deferred.resolve);
        })
    ).done(function() {
        /* ==============================================
        Setup variables
        =============================================== */
        var iframe;
        var fcIframe;
        var pass_data;
        var productId;
        var productName;
        var productURL;
        var shadeName;
        var color;
        var pattern = /\n/ig;
        var iframeLoaded = false;
        var swatches = [];
        var userID = -1;
        var appView = "Main";
        var isRealTime = false;
        var gaImg = new Image(1, 1);

        /* ==============================================
        Grab initial color after page load
        =============================================== */
        productId = "060" + $('#product-color-select').val();
        productName = $('#pdpMain h1.product-name').html();

        productURL = $('#product-color-select :selected').attr("data-href");
        productURL = productURL + $('#product-color-select').val();

        shadeName = $("#product-color-select :selected").html();
        shadeName = shadeName.replace(pattern, "");
        shadeName = $.trim(shadeName);

        color = $('#product-color-select :selected').attr("data-color");
        // console.log("color =", color);

        if (color === undefined) {
            color = $('#product-color-select :selected').attr("data-colors");
            // console.log("colors =", color);
        }

        /* ==============================================
        get swatch colors and send to iframe
        =============================================== */
        var getSwatches = function() {
            var swatch, ID, URL, hex;

            $('#product-color-select option').each(function() {
                swatch = $(this);
                id = swatch.attr("value");
                URL = swatch.data("href");
                hex = swatch.data("color");
                shadeName = swatch.html();
                shadeName = $.trim(shadeName);

                swatches.push('<div><a href="#"><div class="swatch fc-track" style="background-color:#' + hex + '" data-id="060' + id + '" data-href="' + URL + '" data-color="' + hex + '" data-product="' + productName + '" data-action="Select Color" data-desc="' + hex + ', lipstick"><p class="shade-name">' + shadeName + '</p></div></a></div>');
            });
        };

        getSwatches();

        /* ==============================================
        Listen for color dropdown select menu changes
        =============================================== */
        $(document).on("change", "#product-color-select", function(e) {
            productId = "060" + $(this).val();
            shadeName = e.target.options[e.target.selectedIndex].text;
            color = $("#product-color-select :selected").attr("data-color");

            console.log("product id = ", productId);
            console.log("shadeName = ", shadeName);

            if (color !== undefined) {
                console.log("color =", color);
            } else {
                color = $('#product-color-select :selected').attr("data-colors");
                console.log("colors =", color);
            }

            if ($('#TryCon').is(':visible')) {
                sendData(productId, shadeName, color, null, null, null, null, null);
            }

            iframeLoaded = false;
        });

        /* ==============================================
        Send product data to iframe
        =============================================== */
        function sendData(prodID, prodName, hex, method, id, action, desc) {
            $('#TryCon').fadeIn();

            // if (!isMobile.phone) {
            //     if (!$('#TryCon').is(':visible')) {
            //         iframe = '<iframe src="//media.facecake.com/dev/NARS/iframe.html" style="width:100%;max-width:525px;height:525px;border:none;overflow: hidden;position:absolute;left: 0;top: 0;z-index: 1;" scrolling="no" id="TryCon"></iframe>';

            //         $('.bx-wrapper').prepend(iframe);
            //     }
            // }

            pass_data = {
                'message': "data",
                'productID': prodID,
                'prodURL': productURL,
                'name': prodName,
                'color': hex,
                'method': method,
                'ID': id,
                'trackAction': action,
                'trackDesc': desc,
                'swatches': swatches
            };

            if (!iframeLoaded) {
                fcIframe.onload = function() {
                    fcIframe.contentWindow.postMessage(JSON.stringify(pass_data), "*");
                };
            } else {
                // fcIframe = document.getElementById("TryCon");
                fcIframe.contentWindow.postMessage(JSON.stringify(pass_data), "*");
            }
        }

        /* ==============================================
        Setup UI
        =============================================== */
        function closeIframe() {
            if (isMobile.phone || isMobile.seven_inch) {
                $('#animatedModal').removeClass("animatedModal-on");
                $('#animatedModal').addClass("animatedModal-off");
                $('#animatedModal').addClass("zoomOut");
                $('#animatedModal').css("z-index", "-9999");

                // $("body").css("overflow","scroll");
            } else {
                // iframeLoaded = false;
                isRealTime = false;
                // $('iframe#TryCon').remove();
                $('#TryCon').fadeOut();
                $('#pdpMain').find(".thumb").removeClass("selected");
                $('li.thumb:eq(0)').addClass("selected");

                $('div.product-tag').show();
            }
        }

        function initUI() {
            if (!$('#thumbnails ul li.facecake').is(':visible')) {
                if (!isMobile.any || isMobile.tablet && !isMobile.seven_inch) {
                    if (!$('#TryCon').is(':visible')) {
                        iframe = '<iframe src="//media.facecake.com/dev/NARS-test/iframe.html" style="width:100%;max-width:525px;height:525px;border:none;overflow: hidden;position:absolute;left: 0;top: 0;z-index: 1;visability:hidden;" scrolling="no" id="TryCon"></iframe>';

                        $('.bx-wrapper').prepend(iframe);

                        fcIframe = document.getElementById("TryCon");
                    }

                    $('#thumbnails ul').append('<li class="thumb facecake fc-track" id="Inga" data-type="demo" data-action="Select Model" data-desc="Model Inga Clicked"> <a href="Inga" class="thumbnail-link" data-slide-index="0"> <img class="productthumbnail" src="//media.facecake.com/dev/NARS/img/demos/th/Inga.jpg" alt="" title="FaceCake Try-On" data-lgimg="{img/demos/th/Inga.jpg}"> </a> </li>');

                    $('#thumbnails ul').append('<li class="thumb facecake fc-track" id="Nuria" data-type="demo" data-action="Select Model" data-desc="Model Nuria Clicked"> <a href="Nuria" class="thumbnail-link" data-slide-index="0"> <img class="productthumbnail" src="//media.facecake.com/dev/NARS/img/demos/th/Nuria.jpg" alt="" title="FaceCake Try-On" data-lgimg="{img/demos/th/Nuria.jpg}"> </a> </li>');

                    $('#thumbnails ul').append('<li class="thumb facecake fc-track" id="Georgie" data-type="demo" data-action="Select Model" data-desc="Model Georgie Clicked"> <a href="Georgie" class="thumbnail-link" data-slide-index="0"> <img class="productthumbnail" src="//media.facecake.com/dev/NARS/img/demos/th/Georgie.jpg" alt="" title="FaceCake Try-On" data-lgimg="{img/demos/th/Georgie.jpg}"> </a> </li>');

                    // $('#thumbnails ul').append('<li class="thumb facecake fc-track" id="tryconBtn" data-type="realtime" data-action="Click" data-desc="Try-On Clicked"> <a href="#" class="thumbnail-link" data-slide-index="0"> <img class="productthumbnail" src="//media.facecake.com/dev/NARS/img/trycon_tm.jpg" alt="" title="FaceCake Try-On" data-lgimg="{img/trycon_tm.jpg}"> </a> </li>');

                    if (!$('#tryconBtn').is(':visible')) {
                        $('.recommendations-container').before('<a href="try-on" style="float:right;" id="tryconBtn" data-type="realtime" class="fc-track" data-type="realtime" data-action="Select Realtime" data-desc="Try-On Clicked"> <img class="" src="//media.facecake.com/prod/NARS/img/trycon_button.png" alt="facecake try-on" title="FaceCake Try-On" data-lgimg="{img/trycon_button.png}"> </a>');
                    }

                    $('.facecake').on("click", function(e) {
                        e.preventDefault();

                        var ID = this.id;
                        var type = $(this).data("type");

                        if ($(this).hasClass("facecake")) {
                            if (!$('#TryCon').is(':visible') || !$(this).closest("li").hasClass("selected")) {
                                isRealTime = false;

                                $('#pdpMain').find("div.product-thumbnails li.selected").removeClass("selected");
                                $(this).closest("li").addClass("selected");

                                $('div.product-tag').hide();

                                sendData(productId, shadeName, color, type, ID, $(this).data("action"), $(this).data("desc"));
                            }
                        }
                    });

                    $('#tryconBtn').on('click', function(e) {
                        e.preventDefault();

                        var ID = this.id;
                        var type = $(this).data("type");

                        if (!isRealTime) {
                            isRealTime = true;

                            $('#pdpMain').find("div.product-thumbnails li.selected").removeClass("selected");
                            $(this).closest("li").addClass("selected");

                            $('div.product-tag').hide();

                            sendData(productId, shadeName, color, type, ID, $(this).data("action"), $(this).data("desc"));

                            gaImg.src = "//media.facecake.com/dev/NARS-test/iframe.html?utm_source=facecake&utm_medium=audacious&utm_campaign=" + shadeName + "";
                        }

                        // if (!$('#TryCon').is(':visible') || !$(this).closest("li").hasClass("selected")) {
                        //     $('#pdpMain').find("div.product-thumbnails li.selected").removeClass("selected");
                        //     $(this).closest("li").addClass("selected");
                        // }
                    });

                } else {
                    iframe = '<iframe src="//media.facecake.com/dev/NARS-test/iframe-mobile.html" style="width:100%;max-width:601px;height:100%;border:none;overflow: hidden;position:absolute;left: 0;top: 0;z-index: 1;" scrolling="no" id="TryCon"></iframe>';

                    $('head').append('<link rel="stylesheet" href="//media.facecake.com/dev/NARS/css/animate.min.css">');

                    var customModal = $('<div id="animatedModal"><div class="modal-content">' + iframe + '</div></div>');

                    $('body').append(customModal);

                    fcIframe = document.getElementById("TryCon");

                    $('#thumbnails ul').append('<li class="thumb facecake fc-track" data-action="TryCon App Overlay" data-desc="TryCon Clicked"> <a href="#animatedModal" class="thumbnail-link" id="tryconBtn" data-slide-index="0" data-type="realtime" > <img class="productthumbnail" src="//media.facecake.com/dev/NARS/img/trycon_146x146.jpg" alt="" title="FaceCake Try-On" data-lgimg="{img/trycon_146x146.jpg}"> </a> </li>');
                    // $('#pdpMain').append(' <input type="file" id="upload" name="file" accept="image/*" style="display: none;">');

                    $('#tryconBtn').on('click', function(e) {
                        var ID = this.id;
                        var type = $(this).data("type");

                        $('#pdpMain').find("div.product-thumbnails li.selected").removeClass("selected");
                        $(this).closest("li").addClass("selected");

                        sendData(productId, shadeName, color, type, ID, $(this).closest("li").data("action"), $(this).closest("li").data("desc"));

                        gaImg.src = "//media.facecake.com/dev/NARS-test/iframe.html?utm_source=facecake&utm_medium=audacious&utm_campaign=" + shadeName + "";

                        // $("body").css("overflow","hidden");

                        // if (!$('#TryCon').is(':visible') || !$(this).closest("li").hasClass("selected")) {
                        //     $('#pdpMain').find("div.product-thumbnails li.selected").removeClass("selected");
                        //     $(this).closest("li").addClass("selected");
                        // }
                    });

                    $("#tryconBtn").animatedModal({
                        modalTarget: 'animatedModal',
                        color: '#000000',
                        overflow: 'hidden'
                    });

                }
            }

            // Click event listeners for original thumbs - removes FaceCake iframe
            $('li.thumb').on("click", function() {

                if (!$(this).hasClass("facecake")) {
                    $('#pdpMain').find(".thumb").removeClass("selected");
                    $(this).closest("li").addClass("selected");

                    if ($('#TryCon').is(':visible')) {
                        closeIframe();
                    }
                }
            });

            $('button#add-to-cart').on("click", function() {
                var cart_data = {
                    'message': "cart",
                    'trackAction': "Add To Cart",
                    'trackDesc': "User clicked add to bag"
                };
                if ($('#TryCon').is(':visible')) {
                    fcIframe.contentWindow.postMessage(JSON.stringify(cart_data), "*");
                }
            });
        }

        initUI();

        // Listen DOM changes
        $('.page-title').bind("DOMSubtreeModified", initUI);


        /* ==============================================
        Listen for close firing from iframe
        =============================================== */
        window.onmessage = function(e) {
            e = e || window.event;

            if (e.data == 'close iframe') {
                closeIframe();
            } else if (e.data == 'iframe loaded') {
                iframeLoaded = true;
            }
        };
    });
});
