/* jshint browser: true */
/*global $:false */

var stage = new PIXI.Container();
var staticFaceImg = new PIXI.Sprite();
var staticLipsImg = new PIXI.Sprite();

$(function() {
    // initialize Foundation
    $(document).foundation("reveal", "reflow");

    if (isMobile.apple.device) {
        $('.social-links .download').hide();
    }

    $('#wrapper').fadeIn(1000);

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

    $("#emailBtn").animatedModal({
        modalTarget: 'emailModal',
        color: '#ffffff',
        overflow: 'hidden'
    });

    function closeShareModal() {
        $('#shareModal').fadeOut();
        $('#shareModal').removeClass("shareModal-on");
        $('#shareModal').addClass("shareModal-off");
        $('#shareModal').addClass("zoomOut");
        $('#shareModal').css("z-index", "-9999");
    }

    function closeEmailModal() {
        $('#emailModal').fadeOut();
        $('#emailModal').removeClass("emailModal-on");
        $('#emailModal').addClass("emailModal-off");
        $('#emailModal').addClass("zoomOut");
        $('#emailModal').css("z-index", "-9999");
    }
    /* ==============================================
        declare variables
    =============================================== */
    // Tracking variables
    var userID = -1;
    var appView = "Main";
    var productID = -1;
    var productURL = -1;
    var productName = -1;

    // share variables
    var imgName;
    var imgShareURL;
    var oAuthToken;
    var imgData;

    // Canvas/drawing variables
    var debug = false;
    var context;
    var modelName;
    var initialColor;
    var spritesLoaded = false;
    var demoHelpLoaded = false;
    var realtimeHelpLoaded = false;
    var isStatic = false;

    var w = 0;
    var h = 0;
    var imageData;
    var isSlick = false;

    // Setup PIXI
    var pixiCvs = document.getElementById('holder');

    var renderer = PIXI.autoDetectRenderer(525, 470, {
        view: pixiCvs,
        antialias: true,
        transparent: true,
        preserveDrawingBuffer: true
    });

    // draw frames to canvas
    var animate = function() {
        requestAnimationFrame(animate);
        renderer.render(stage);
    };

    //creat array of canvases
    var cvsArray = [];
    $('canvas, #holder').each(function() {
        cvsArray.push(this.id);
    });

    var shareCvs = document.getElementById("shareCvs");
    var shareCtx = shareCvs.getContext("2d");

    /* ==============================================
    Receive product data from parent
    =============================================== */
    window.onmessage = function(e) {
        e = e || window.event;

        tracker.track("Application Start", "Nars Integrated Try-On started ", productID, appView, userID);

        var received_data = JSON.parse(e.data);
        var action = received_data.trackAction;
        var desc = received_data.trackDesc;

        if (received_data.message == "data") {
            var ID = received_data.ID;
            var swatchArr = received_data.swatches;
            var method = received_data.method;
            var color = received_data.color;
            productID = received_data.productID;
            productURL = received_data.prodURL;
            productName = received_data.name;

            tracker.track(action, desc, productID, appView, userID);
            // if (!localStorage.getItem("color")) {
            //     spriteSheets.shade(color);
            // }
            modelName = "Inga";

            spriteSheets.shade(color);

            // if (!demoHelpLoaded) {
            //     $('#demoHelp').fadeIn();
            //     demoHelpLoaded = true;
            // }

            initDemo(modelName, color);

            if (swatchArr !== null) {
                initCarousel(swatchArr);
            }
        }

        if (received_data.message == "cart") {
            tracker.track(action, desc, productID, appView, userID);
        }
    };

    /* ==============================================
    start demo try-on
    =============================================== */

    var initDemo = function(id, hex) {
        appView = "demo";

        if (spritesLoaded) {
            $('.spinnerOverlay').fadeIn("fast");

            spriteSheets.load(id, hex);
        } else {
            spriteSheets.shade(hex);
        }

        if ($('#holder').hasClass("mirror")) {
            $.each(cvsArray, function(i, id) {
                $("#" + id + "").removeClass("mirror");
            });
        }
    };

    /* ==============================================
    Handle UI interaction
    =============================================== */
    var initCarousel = function(arr) {
        if (!isSlick) {
            //swatch carousel
            $('#slick').slick({
                slidesToShow: 5,
                slidesToScroll: 5,
                infinite: false,
                arrows: true,
                prevArrow: '<a href="slick-prev" class="slick-prev"><img src="./slick/img/prev.png"></a>',
                nextArrow: '<a href="slick-next" class="slick-next"><img src="./slick/img/next.png"></a>',
                responsive: [{
                    breakpoint: 601,
                    settings: {
                        slidesToShow: 7,
                        slidesToScroll: 7
                    }
                }, {
                    breakpoint: 415,
                    settings: {
                        slidesToShow: 5,
                        slidesToScroll: 5
                    }
                }, {
                    breakpoint: 377,
                    settings: {
                        slidesToShow: 4,
                        slidesToScroll: 4
                    }
                }, {
                    breakpoint: 320,
                    settings: {
                        slidesToShow: 3,
                        slidesToScroll: 3
                    }
                }]
            });

            $('#slick').slick('slickAdd', arr.join(""));
        }
    };

    $('#slick').on('init', function(event, slick) {
        isSlick = true;
    });

    // handle swatch click
    $(document).on("click", "#slick a .swatch", function(e) {
        e.preventDefault();

        var hex = $(this).data("color");
        productID = $(this).data("id");
        productURL = $(this).data("href");
        productName = $(this).data("product");

        $('.help-overlay').fadeOut();

        localStorage.setItem("color", hex);

        if (spritesLoaded) {
            spriteSheets.apply(modelName, hex);
        } else {
            spriteSheets.shade(hex);
        }

        if (isStatic) {
            applyStaticLips(hex);
            tracker.track("Apply Asset To Image", productID, productID, appView, userID);
        }
    });

    // slick arrow click
    $(document).on("click", "a.slick-prev, a.slick-next", function(e) {
        e.preventDefault();
    });

    $('#modelThumbs a.th').on("click", function(e) {
        e.preventDefault();

        $('.help-overlay').fadeOut();

        var ID = this.id;

        if (ID != "fileSelect") {
            modelName = ID;
            // initDemo(ID, color);
            spriteSheets.load(modelName, null);
        }
    });

    $('#demoHelp .continue, #realtimeHelp .continue').on("click", function(e) {
        e.preventDefault();

        $(this).parent().parent().fadeOut();
    });

    $('#snapshotBtn').on("click", function() {
        $('#shareModal').fadeIn("medium");
        exportAndSaveCanvas();
    });

    $('#clearBtn').on("click", function() {
        clearStaticLips();
    });

    $('#helpBtn').on("click", function() {
        $('#realtimeHelp').fadeIn();
    });

    $('.close-btn button.share').on("click", function() {
        // $('#shareModal').foundation('reveal', 'close');
        closeShareModal();
    });

    $('#closeBtn').on("click", function() {
        if (spritesLoaded) {
            spriteSheets.stop();
        }
        if (window.top !== window.self) {
            window.top.postMessage('close iframe', '*');
        }

        tracker.track("Application End", "User closed application iframe", productID, appView, userID);
    });

    $('.social-links a.facebook').on("click", function() {
        fbPost(imgShareURL);
    });

    $('.social-links a.email').on("click", function() {
        // $('#emailModal').foundation('reveal', 'open');
        closeShareModal();
        $('#emailModal').fadeIn("medium");
    });

    $('.social-links a.download').on("click", function() {
        downloadCanvas(this, "FaceCake_NARS_Try-On_" + imgName + ".png");
    });

    $('#submitBtn').on("click", function() {

    });

    $('#cancelBtn').on("click", function() {
        // $('#emailModal').foundation('reveal', 'close');
        closeEmailModal();
    });

    function applyStaticLips(hex) {
        staticLipsImg.tint = "0x" + hex;
        staticLipsImg.alpha = 1;
    }

    function clearStaticLips() {
        staticLipsImg.tint = 0xFFFFFF;
        staticLipsImg.alpha = 0;
    }

    /* ==============================================
    Image upload and process
    =============================================== */

    /* date string for saved pic */
    var getCD = function() {
        var d = new Date();
        var curr_date = d.getDate();
        if (curr_date <= 9) {
            curr_date = '0' + curr_date;
        }

        var curr_month = d.getMonth();
        if (curr_month <= 9) {
            curr_month = '0' + curr_month;
        }
        curr_month++;
        var curr_year = d.getFullYear();
        var curr_hour = d.getHours();
        if (curr_hour <= 9) {
            curr_hour = '0' + curr_hour;
        }
        var curr_min = d.getMinutes();
        if (curr_min <= 9) {
            curr_min = '0' + curr_min;
        }
        var curr_sec = d.getSeconds();
        if (curr_sec <= 9) {
            curr_sec = '0' + curr_sec;
        }

        var cd = curr_month + "-" + curr_date + "-" + curr_year + "-" + curr_hour + "-" + curr_min + "-" + curr_sec;

        return cd;
    };

    /* export and save canvas */
    var exportAndSaveCanvas = function() {
        //show spinner and overlay
        $('.share-modal-content .spinnerOverlay').fadeIn("fast");

        // Get the canvas screenshot as PNG
        imgData = renderer.view.toDataURL('image/png');

        shareCtx.clearRect(0, 0, 525, 525);

        var postImage = function(img) {
            var url = 'upload/export.php';

            imgName = getCD();
            $.ajax({
                type: "POST",
                url: url,
                dataType: 'json',
                data: {
                    base64data: img,
                    filename: imgName
                },
                success: function(data) {
                    // hide spinner and overlay
                    var shareImg = new Image();
                    $(shareImg).attr('src', data.imgPath);

                    shareImg.onload = function() {
                        // $('.spinnerOverlay').fadeOut("fast", function() {
                        //     shareCtx.drawImage(shareImg, 0, 0);
                        // });

                        shareCtx.drawImage(shareImg, 0, 0);
                        $('.share-modal-content .spinnerOverlay').fadeOut("fast");
                        // $('#shareCvs').fadeIn();

                        // $('#shareModal').foundation("reveal", "open");

                        // shareModal.open();

                        imgShareURL = data.imgPath;

                        tracker.track("Save Photo To Server", data.img, productID, appView, userID);
                    };

                    //hide spinner and overlay
                    // $('.spinnerOverlay').fadeOut("fast");
                    // $('#shareImage').attr("src", data.imgPath);
                    // $('#shareModal').foundation("reveal", "open");

                    // console.log(data.img);
                    // imgShareURL = data.imgPath;
                    // console.log(imgShareURL);

                    // tracker.track("Save Photo To Server", data.img, productID, appView, userID);

                }
            });
        };

        //flip snapshot if need be
        var flip = function(data) {
            var img = new Image();
            img.onload = function() {
                var c = document.createElement('canvas');
                c.width = this.width;
                c.height = this.height;
                var ctx = c.getContext("2d");
                ctx.scale(-1, 1);
                ctx.drawImage(this, -this.width, 0);
                this.onload = undefined;
                // var newImageData = c.toDataURL();

                imgData = c.toDataURL();

                postImage(imgData);
                // postImage(newImageData);
            };
            img.src = data;
        };

        if ($('#holder').hasClass("mirror")) {
            flip(imgData);
        } else {
            postImage(imgData);
        }
    };

    $('input[type=file]').on('change', function(e) {
        $('.spinnerOverlay').fadeIn();
        $('#fileForm').submit();

        // var myImg = new Image();

        // file = e.target.files[0];

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

        //         // clearImage();

        //         myImg.onload = function() {
        //             // $('.spinnerOverlay, .upload-ui').fadeOut("fast", function() {
        //             //     // imgCtx.drawImage(myImg, 0, 0);
        //             //     //animate();
        //             // });
        //         };
        //     }
        // });
    });

    $('#fileForm').on("submit", function(e) {
        e.preventDefault();

        if (spritesLoaded) {
            spriteSheets.stop();
        }

        isStatic = true;

        $('#realtimeHelp').fadeOut();
        $('#demoHelp').fadeOut();
        $('#uploadError').fadeOut();

        var fileSelect = document.getElementById('upload');

        var files = fileSelect.files;
        var formData = new FormData(this);

        var file = files[0];
        var newFileName = file.name.replace(/(\.[\w\d_-]+)$/i, '_'+ getCD() +'$1');
        formData.append('file', file, newFileName);

        var URL = $(this).attr("action");

        $.ajax({
            type: "POST",
            url: URL,
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            dataType: "json",
            success: function(data, textStatus, xhr) {
                // $('#iconBar').fadeIn();
                $('.icon-bar .item').fadeIn();
                // $('#closeBtn button.secondary, #closeBtn.button.secondary').css("background-color", "rgba(0, 0, 0, 0.0)");

                stage.removeChild(staticFaceImg);
                stage.removeChild(staticLipsImg);

                var face = URL + data.results[1].face;
                var lips = URL + data.results[2].mouth;

                staticFaceImg = PIXI.Sprite.fromImage(face);
                staticLipsImg = PIXI.Sprite.fromImage(lips);

                if (localStorage.getItem("color")) {
                    applyStaticLips(localStorage.getItem("color"));
                } else {
                    applyStaticLips(initialColor);
                }

                staticFaceImg.visible = true;
                staticLipsImg.visible = true;

                stage.addChild(staticFaceImg);
                stage.addChild(staticLipsImg);

                appView = "user upload";
                // animate();

                $('.spinnerOverlay').fadeOut();
            },
            error: function(data) {
                $('.spinnerOverlay').fadeOut();
                $('#uploadError').fadeIn();
            }
        });
    });

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

        if (upload) {
            upload.click();
        }
        e.preventDefault();
    });

    /* ==============================================
    Share functions
    =============================================== */
    //download
    function downloadCanvas(link, filename) {
        link.href = imgData;
        link.download = filename;
    }
    // email
    $('#shareForm').on("submit", function(e) {
        e.preventDefault();

        var toNameval = $('#toName').val();
        var toEmailval = $('#toEmail').val();
        var fromNameval = $('#fromName').val();
        var fromEmailval = $('#fromEmail').val();

        tracker.track("Email From Name", fromNameval, productID, appView, userID);
        tracker.track("Email To Name", toNameval, productID, appView, userID);
        tracker.track("Email From Addr", fromEmailval, productID, appView, userID);

        $('.spinner').show();

        $.ajax({
            type: 'POST',
            url: 'sendMail.php',
            data: {
                toName: toNameval,
                toEmail: toEmailval,
                fromName: fromNameval,
                fromEmail: fromEmailval,
                shareImg: imgShareURL,
                prodDesc: productName,
                prodURL: productURL,
            },
            success: function(data) {
                localStorage.setItem("user email", fromEmailval);

                $('.spinner').hide();

                $('#response').html("<div data-alert class='alert-box success radius'>SUCCESS: Your message was sent!<a href='#' class='close'>&times;</a></div>").promise().done(function() {
                    setTimeout(function() {
                        // $('#emailModal').foundation('reveal', 'close');
                        closeEmailModal();
                    }, 2000);

                    tracker.track("Share Email", toEmailval, productID, appView, userID);
                });
            },
            error: function(xhr, type, data) {
                $('.spinner').hide();

                $('#response').html("<div data-alert class='alert-box alert radius'>ERROR: There was a problem sending your message.  Please try again.<a href='#' class='close'>&times;</a></div>").promise().done(function() {
                    setTimeout(function() {
                        // $('#emailModal').foundation('reveal', 'close');
                        closeEmailModal();
                    }, 2000);
                });
            }
        });
    });

    // Facebook
    function fbPost(imgURL) {
        var redirectURI = "https://www.facebook.com/connect/login_success.html";
        console.log(productURL);

        var postTitle = 'NARS Audacious Lipstick Try-On';
        var prodDesc = "I just tried on this NARS look. Click to try for yourself.";

        var leftPosition, topPosition;
        //Allow for borders.
        var width = 500;
        var height = 300;

        leftPosition = (window.screen.width / 2) - ((width / 2) + 10);
        //Allow for title and status bars.
        topPosition = (window.screen.height / 2) - ((height / 2) + 150);
        var windowFeatures = "status=no,height=" + height + ",width=" + width + ",resizable=no,left=" + leftPosition + ",top=" + topPosition + ",screenX=" + leftPosition + ",screenY=" + topPosition + ",toolbar=no,menubar=no,scrollbars=no,location=no,directories=no";

        window.open('https://www.facebook.com/dialog/feed?app_id=301956396641648&link=' + productURL + '&picture=' + imgURL + '&name=' + postTitle + '&description=' + prodDesc + '&redirect_uri=' + redirectURI + '&display=popup', 'facebook-share-dialog', windowFeatures);

        tracker.track("Share Facebook", "Share Facebook", productID, appView, userID);
    }

    /* ==============================================
    spritesheets module
    =============================================== */
    var spriteSheets = (function() {

        var videoAnim;
        var faceMovie;
        var lipsMovie;
        var hightlightsMovie;
        var currentMovie = 0;
        var currentShadeHex; // = 0xFFFFFF;
        var currFrame;

        // asset arrays
        var faceAssetsToLoad = [];
        var lipsAssetsToLoad = [];
        var highlightsAssetsToLoad = [];

        // var animate = function() {
        //     requestAnimationFrame(animate);
        //     renderer.render(stage);
        // };

        var assetData = {
            /*Inga*/
            1: {
                "sprites": 3,
                "frames": 210
            },
            /*Nuria*/
            2: {
                "sprites": 3,
                "frames": 228
            },
            /*Georgie*/
            3: {
                "sprites": 3,
                "frames": 240
            }
        };

        var movieClips = {
            /*Inga*/
            1: {
                face: null,
                lips: null,
                highlights: null
            },
            /*Nuria*/
            2: {
                face: null,
                lips: null,
                highlights: null
            },
            /*Georgie*/
            3: {
                face: null,
                lips: null,
                highlights: null
            }
        };

        function loadModels() {
            //show spinner and overlay
            $('.spinnerOverlay').fadeIn("fast");

            for (var i = 1; i < 4; ++i) {
                var num = assetData[i].sprites;
                for (var j = 0; j < num; ++j) {
                    if (i == 1) {
                        PIXI.loader.add('./spritesheets/Inga/276/face/Inga_Face_' + j + '.json');
                        PIXI.loader.add('./spritesheets/Inga/276/lips/Inga_Lips_' + j + '.json');
                        PIXI.loader.add('./spritesheets/Inga/276/highlights/Inga_Highlights_' + j + '.json');
                    }

                    if (i == 2) {
                        PIXI.loader.add('./spritesheets/Nuria/276/face/Nuria_Face_' + j + '.json');
                        PIXI.loader.add('./spritesheets/Nuria/276/lips/Nuria_Lips_' + j + '.json');
                        PIXI.loader.add('./spritesheets/Nuria/276/highlights/Nuria_Highlights_' + j + '.json');
                    }

                    if (i == 3) {
                        PIXI.loader.add('./spritesheets/Georgie/276/face/Georgie_Face_' + j + '.json');
                        PIXI.loader.add('./spritesheets/Georgie/276/lips/Georgie_Lips_' + j + '.json');
                        PIXI.loader.add('./spritesheets/Georgie/276/highlights/Georgie_Highlights_' + j + '.json');
                    }
                }
            }
        }

        function prepareFrames() {
            for (var i = 1; i < 4; ++i) {
                var num = assetData[i].frames;
                var faceArray = [];
                var lipsArray = [];
                var highlightsArray = [];

                for (var j = 0; j < num; ++j) {
                    var val = j < 10 ? '0' + j : j;

                    if (val > 99) {
                        if (i == 1) {
                            faceArray.push(PIXI.Texture.fromFrame('Inga_Face_' + val));
                            lipsArray.push(PIXI.Texture.fromFrame('Inga_Lips_' + val));
                            highlightsArray.push(PIXI.Texture.fromFrame('Inga_Highlights_' + val));
                        }

                        if (i == 2) {
                            faceArray.push(PIXI.Texture.fromFrame('Nuria_Face_' + val));
                            lipsArray.push(PIXI.Texture.fromFrame('Nuria_Lips_' + val));
                            highlightsArray.push(PIXI.Texture.fromFrame('Nuria_Highlights_' + val));
                        }

                        if (i == 3) {
                            faceArray.push(PIXI.Texture.fromFrame('Georgie_Face_' + val));
                            lipsArray.push(PIXI.Texture.fromFrame('Georgie_Lips_' + val));
                            highlightsArray.push(PIXI.Texture.fromFrame('Georgie_Highlights_' + val));
                        }
                    } else {
                        if (i == 1) {
                            faceArray.push(PIXI.Texture.fromFrame('Inga_Face_0' + val));
                            lipsArray.push(PIXI.Texture.fromFrame('Inga_Lips_0' + val));
                            highlightsArray.push(PIXI.Texture.fromFrame('Inga_Highlights_0' + val));
                        }

                        if (i == 2) {
                            faceArray.push(PIXI.Texture.fromFrame('Nuria_Face_0' + val));
                            lipsArray.push(PIXI.Texture.fromFrame('Nuria_Lips_0' + val));
                            highlightsArray.push(PIXI.Texture.fromFrame('Nuria_Highlights_0' + val));
                        }

                        if (i == 3) {
                            faceArray.push(PIXI.Texture.fromFrame('Georgie_Face_0' + val));
                            lipsArray.push(PIXI.Texture.fromFrame('Georgie_Lips_0' + val));
                            highlightsArray.push(PIXI.Texture.fromFrame('Georgie_Highlights_0' + val));
                        }
                    }
                }

                // create and add face movie-clip
                faceMovie = new PIXI.extras.MovieClip(faceArray);
                faceMovie.visible = false;
                faceMovie.position.x = -1;
                faceMovie.position.y = -1;
                faceMovie.scale.x = 1.95;
                faceMovie.scale.y = 1.95;

                faceMovie.anchor.set(0);
                faceMovie.animationSpeed = 0.417;

                stage.addChild(faceMovie);

                faceMovie.stop();

                movieClips[i].face = faceMovie;

                // // create and add lips movie-clip
                lipsMovie = new PIXI.extras.MovieClip(lipsArray);
                lipsMovie.visible = false;
                lipsMovie.position.x = -1;
                lipsMovie.position.y = -1;
                lipsMovie.scale.x = 1.95;
                lipsMovie.scale.y = 1.95;

                lipsMovie.anchor.set(0);
                lipsMovie.animationSpeed = 0.417;

                if (currentShadeHex == 0xFFFFFF) {
                    lipsMovie.alpha = 0.0;
                } else {
                    lipsMovie.alpha = 0.9;
                }

                if (localStorage.getItem("color")) {
                    lipsMovie.tint = "0x" + localStorage.getItem("color");
                } else {
                    lipsMovie.tint = "0x" + currentShadeHex;
                }

                stage.addChild(lipsMovie);

                lipsMovie.stop();

                movieClips[i].lips = lipsMovie;

                // create and add hightlights movie-clip
                hightlightsMovie = new PIXI.extras.MovieClip(highlightsArray);
                hightlightsMovie.visible = false;
                hightlightsMovie.position.x = -1;
                hightlightsMovie.position.y = -1;
                hightlightsMovie.scale.x = 1.95;
                hightlightsMovie.scale.y = 1.95;

                hightlightsMovie.anchor.set(0);
                hightlightsMovie.animationSpeed = 0.417;

                stage.addChild(hightlightsMovie);

                hightlightsMovie.stop();

                movieClips[i].highlights = hightlightsMovie;

                if (i == 3) {
                    spritesLoaded = true;

                    if (modelName !== undefined || modelName !== null) {
                        init(modelName, null);
                    }
                }
            }
        }

        loadModels();

        PIXI.loader.load(function() {
            prepareFrames();
            animate();
        });

        function init(model, hex) {
            var ID;

            $('.icon-bar .item').fadeOut();

            staticFaceImg.visible = false;
            staticLipsImg.visible = false;

            isStatic = false;

            $('#uploadError').fadeOut();

            if (currentMovie > 0) {
                stopMovie(currentMovie);
            }

            switch (model) {
                case "Inga":
                    ID = 1;
                    break;
                case "Nuria":
                    ID = 2;
                    break;
                case "Georgie":
                    ID = 3;
                    break;
            }

            var clips = movieClips[ID];

            if (!clips) {
                console.log("clips not loaded");

                // this will mean it hasn't loaded yet, or you have a weird button.
                // you may decide instead to only enable the buttons after the loading completes.
                return;
            }

            stage.x = 0;
            stage.y = 0;

            clips.face.visible = true;
            clips.lips.visible = true;
            clips.highlights.visible = true;

            if (currFrame > 0 && currFrame < 210) {
                clips.face.gotoAndPlay(currFrame);
                clips.lips.gotoAndPlay(currFrame);
                clips.highlights.gotoAndPlay(currFrame);
            } else {
                clips.face.gotoAndPlay(clips.face.totalFrames / 4);
                clips.lips.gotoAndPlay(clips.lips.totalFrames / 4);
                clips.highlights.gotoAndPlay(clips.highlights.totalFrames / 4);
            }

            if (localStorage.getItem("color")) {
                applyMakeup(model, localStorage.getItem("color"));
            } else {
                applyMakeup(model, currentShadeHex);
            }

            clips.highlights.alpha = 0.15;

            currentMovie = ID;

            //show spinner and overlay
            $('.spinnerOverlay').fadeOut("fast");
        }

        function applyMakeup(model, shade) {

            var ID;

            switch (model) {
                case "Inga":
                    ID = 1;
                    break;

                case "Nuria":
                    ID = 2;
                    break;

                case "Georgie":
                    ID = 3;
                    break;

                default:
                    ID = model;
            }

            var clip = movieClips[ID];

            if (clip) {
                clip.lips.alpha = 0.9;
                currentShadeHex = "0x" + shade;
                clip.lips.tint = currentShadeHex;

                localStorage.setItem("color", shade);

                if (clip.lips.visible) {
                    tracker.track("Apply Asset To Image", productID, productID, appView, userID);
                }
            }
        }

        function clearMakeup() {
            if (lipsMovie !== undefined) {
                lipsMovie.alpha = 0.0;
                currentShadeHex = 0xFFFFFF;
                lipsMovie.tint = 0xFFFFFF;
            }
        }

        function updateShade(hex) {
            localStorage.setItem("color", hex);

            currentShadeHex = hex;
        }

        function stopMovie(id) {
            var clip = movieClips[id];

            currFrame = clip.face.currentFrame;

            clip.face.visible = false;
            clip.lips.visible = false;
            clip.highlights.visible = false;

            clip.face.stop();
            clip.lips.stop();
            clip.highlights.stop();
        }

        function stopAll() {
            for (var i = 1; i < 4; ++i) {
                movieClips[i].face.visible = false;
                movieClips[i].lips.visible = false;
                movieClips[i].highlights.visible = false;

                movieClips[i].face.gotoAndStop(movieClips[i].face.totalFrames / 4);
                movieClips[i].lips.gotoAndStop(movieClips[i].lips.totalFrames / 4);
                movieClips[i].highlights.gotoAndStop(movieClips[i].highlights.totalFrames / 4);
            }
        }

        // Public API
        return {
            load: init,
            apply: applyMakeup,
            clear: clearMakeup,
            stop: stopAll,
            shade: updateShade
        };
    })();

    /***** handle different devices *****/
    function getImageSize() {
        var userImgSize = {
            width: 525,
            height: 470
        }

        // iPhone 5/5s
        if (matchMedia('only screen and (min-device-width: 320px) and (max-device-width: 568px)').matches) {
            userImgSize = {
                width: 301,
                height: 269
            }
        }

        // iPhone 6
        if (matchMedia('only screen and (min-device-width: 375px) and (max-device-width: 667px)').matches) {
            userImgSize = {
                width: 356,
                height: 319
            }

        }

        // iPhone 6+
        if (matchMedia('only screen and (min-device-width: 414px) and (max-device-width: 736px)').matches) {
            userImgSize = {
                width: 394,
                height: 353
            }
        }

        // iPads
        if (matchMedia('only screen and (min-device-width: 768px) and (max-device-width: 1024px)').matches) {
            // trackHeight = 320;
            // canvas.height = 640;
            userImgSize = {
                width: 450,
                height: 403
            }
        }

        return userImgSize;
    };

    /* ==============================================
      Set boolean "iframeLoaded = true" in parent
      =============================================== */
    if (window.top !== window.self) {
        window.top.postMessage('iframe loaded', '*');

        // tracker.track("Application Start", "Nars Integrated Try-On started ", productID, appView, userID);
    }

    /* ==============================================
      Force orientation to portrait
      =============================================== */
    // function reorient(e) {
    //     var portrait = (window.orientation % 180 == 0);
    //     $("body > div").css("-webkit-transform", !portrait ? "rotate(-90deg)" : "");
    // }
    // window.onorientationchange = reorient;
    // window.setTimeout(reorient, 0);

    /* ==============================================
    Adding tracking to click events
    =============================================== */
    $(document).on("click", ".fc-track", function() {
        tracker.track($(this).data("action"), $(this).data("desc"), productID, appView, userID);
    });

    tracker.track("Application Load", "Application Loaded", productID, appView, userID);
});
