$(function() {

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

    $.when(
        $.getScript("//www-dev.facecake.com/nars-test/js/plugins.js"),
        $.getScript("//www-dev.facecake.com/nars-test/js/base64.js"),
        $.getScript("//www-dev.facecake.com/nars-test/js/binaryajax.js"),
        $.getScript("//www-dev.facecake.com/nars-test/js/exif.js"),
        $.getScript("//www-dev.facecake.com/nars-test/js/canvasResize.js"),
        $.getScript("//www-dev.facecake.com/nars-test/js/mediaCheck.min.js"),
        $.Deferred(function(deferred) {
            $(deferred.resolve);
        })
    ).done(function() {

        /* ==============================================
        Setup variables
        =============================================== */
        var iframe = '<iframe src="//localhost:8888/nars/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;" scrolling="no" id="TryCon"></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 = [];

        /* ==============================================
        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 = "http://www.narscosmetics.com/" + productURL;

        shadeName = $("#product-color-select :selected").html();
        shadeName = shadeName.replace(pattern, "");
        shadeName = $.trim(shadeName);
        console.log("shadeName =", 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><div class="swatch" style="background-color:#' + hex + '" data-id="' + id + '" data-href="' + URL + '" data-color="' + hex + '">' + shadeName + '<img src="img/spacer.png"></div></div>');
                swatches.push('<div><a href="' + shadeName + '"><div class="swatch" style="background-color:#' + hex + '" data-id="060' + id + '" data-href="http://www.narscosmetics.com/' + URL + '" data-color="' + hex + '" data-product="' + productName + '"><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);
            }

            iframeLoaded = false;
        });

        /* ==============================================
        Send product data to iframe
        =============================================== */
        function sendData(prodID, prodName, hex, method, src) {
            if (!$('#TryCon').is(':visible')) {
                $('.bx-wrapper').prepend(iframe);
            }

            pass_data = {
                'productID': prodID,
                'prodURL': productURL,
                'name': prodName,
                'color': hex,
                'method': method,
                'source': src,
                'swatches': swatches
            };

            if (!iframeLoaded) {
                fcIframe = document.getElementById("TryCon");

                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() {
            iframeLoaded = false;
            $('iframe#TryCon').remove();
            $('#pdpMain').find(".thumb").removeClass("selected");
            $('li.thumb:eq(0)').addClass("selected");
        }

        function initUI() {
            productName = $("#pdpMain h1.product-name").html();

            if (!$('#thumbnails ul li.facecake').is(':visible')) {
                if (!isMobile) {
                    $('#thumbnails ul').append('<li class="thumb facecake" id="Inga" data-type="demo"> <a href="Inga" class="thumbnail-link" data-slide-index="0"> <img class="productthumbnail" src="//www-dev.facecake.com/nars-test/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" id="Nuria" data-type="demo"> <a href="Nuria" class="thumbnail-link" data-slide-index="0"> <img class="productthumbnail" src="//www-dev.facecake.com/nars-test/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" id="Gerogie" data-type="demo"> <a href="Gerogie" class="thumbnail-link" data-slide-index="0"> <img class="productthumbnail" src="//www-dev.facecake.com/nars-test/img/demos/th/Georgia.jpg" alt="" title="FaceCake Try-On" data-lgimg="{img/demos/th/Gerogie.jpg}"> </a> </li>');
                } else {
                    // if (!$('#tryconBtn').is(':visible')) {
                    //     $('.product-variations').before('<a href="try-on" style="float:right;" id="tryconBtn" data-type="realtime"> <img class="" src="//www-dev.facecake.com/nars-test/img/tryconBtn.png" alt="facecake try-on" title="FaceCake Try-On" data-lgimg="{img/tryconBtn.png}"> </a>');
                    // }

                    // $('#thumbnails ul').append('<li class="thumb facecake" data-type="realtime"> <a href="#" class="thumbnail-link" id="tryconBtn" data-slide-index="0"> <img class="productthumbnail" src="//www-dev.facecake.com/nars-test/img/trycon_tm.jpg" alt="facecake try-on" title="FaceCake Try-On" data-lgimg="{img/trycon_tm.jpg}"> </a> </li>');
                    // $('#pdpMain').append(' <input type="file" id="upload" name="file" accept="image/*" style="display: none;">');
                }
            }

            mediaCheck({
                media: '(max-width: 767px)',
                entry: function() {
                    if ($('#tryconBtn').is(':visible')) {
                        $('#tryconBtn').remove();
                    }

                    if (!isMobile) {
                        $('.product-variations').before('<a href="try-on" style="float:right;padding-bottom:10px;" id="tryconBtn" data-type="realtime"> <img class="" src="//www-dev.facecake.com/nars-test/img/tryconBtn.png" alt="facecake try-on" title="FaceCake Try-On" data-lgimg="{img/tryconBtn.png}"> </a>');

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

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

                            sendData(productId, shadeName, color, type, ID);
                        });

                    } else {
                        $('.product-variations').before('<a href="try-on" style="float:right;padding-bottom:10px;" id="tryconBtn" data-type="realtime"> <img class="" src="//www-dev.facecake.com/nars-test/img/tryconBtn.png" alt="facecake try-on" title="FaceCake Try-On" data-lgimg="{img/tryconBtn.png}"> </a>');

                        $('#pdpMain').append(' <input type="file" id="upload" name="file" accept="image/*" style="display: none;">');

                        $('#tryconBtn').on('click', function(e) {
                            $('input[type=file]').val(null);

                            $('#upload').click();
                            e.preventDefault();

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

                                // if (!$('#TryCon').is(':visible')) {
                                //     $('.bx-wrapper').prepend(iframe);
                                // }
                            }
                        });
                    }
                },
                exit: function() {
                    if ($('#tryconBtn').is(':visible')) {
                        $('#tryconBtn').remove();
                    }
                    $('.recommendations-container').before('<a href="try-on" style="float:right;" id="tryconBtn" data-type="realtime"> <img class="" src="//www-dev.facecake.com/nars-test/img/tryconBtn.png" alt="facecake try-on" title="FaceCake Try-On" data-lgimg="{img/tryconBtn.png}"> </a>');

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

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

                        sendData(productId, shadeName, color, type, ID);
                    });
                }
            });

            //var slider = $('.product-image-slider').bxSlider();
            // slider.reloadSlider();

            // $('head').append('<link rel="stylesheet" href="css/trycon.css">\n');

            //load iframe based on HTML5 getUserMedia support
            // if (!getUserMedia && !isMobile) {
            //     iframe = '<iframe src="//localhost:8888/nars/nars-test/flash-test/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>';
            // } else {
            //     iframe = '<iframe src="//localhost:8888/nars/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;" scrolling="no" id="TryCon"></iframe>';
            // }

            // Click event listeners for added thumbnails
            if (isMobile) {
                // $('#tryconBtn').on('click', function(e) {
                //     $('input[type=file]').val(null);

                //     $('#upload').click();
                //     e.preventDefault();

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

                //         // if (!$('#TryCon').is(':visible')) {
                //         //     $('.bx-wrapper').prepend(iframe);
                //         // }
                //     }
                // });
            } else {
                $('li.thumb').on("click", function(e) {
                    var ID = this.id;
                    var type = $(this).data("type");

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

                            sendData(productId, shadeName, color, type, ID);
                        }
                    }
                });

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

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

                //     console.log(ID, type);

                //     sendData(productId, shadeName, color, type, ID);
                // });
            }

            // 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();
                    }
                }
            });

            // listen for file input/upload
            var myImg = new Image();

            $('input[type=file]').on('change', function(e) {
                var file = e.target.files[0];

                // CANVAS RESIZING
                canvasResize(file, {
                    width: userImgWidth,
                    height: 0,
                    crop: true,
                    quality: 80,
                    callback: function(data, width, height) {
                        myImg = new Image();
                        $(myImg).attr('src', data);

                        myImg.onload = function() {
                            sendData(productId, shadeName, color, "realtime", $(myImg).attr('src'));
                        };
                    }
                });
            });
        }

        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;
            }
        };

        /* ==============================================
        handle different devices and set uploaded image size
        =============================================== */
        var userImgWidth;

        // iPhone 5/5s
        if (matchMedia('only screen and (min-device-width: 320px) and (max-device-width: 568px)').matches) {
            if (!$('li.thumb:eq(2)').hasClass("facecake")) {
                $('li.thumb:eq(2)').remove();
                $('ul.product-image-slider li:eq(2)').remove();
            }
            userImgWidth = 198;
        }

        // iPhone 6
        if (matchMedia('only screen and (min-device-width: 375px) and (max-device-width: 667px)').matches) {
            if (!$('li.thumb:eq(2)').hasClass("facecake")) {
                $('li.thumb:eq(2)').remove();
                $('ul.product-image-slider li:eq(2)').remove();
            }
            userImgWidth = 198;
        }

        // iPhone 6+
        if (matchMedia('only screen and (min-device-width: 414px) and (max-device-width: 736px)').matches) {
            if (!$('li.thumb:eq(2)').hasClass("facecake")) {
                $('li.thumb:eq(2)').remove();
                $('ul.product-image-slider li:eq(2)').remove();
            }
            userImgWidth = 198;
        }

        // iPads
        if (matchMedia('only screen and (min-device-width: 768px) and (max-device-width: 1024px)').matches) {
            userImgWidth = 420;
        }
    });
});
