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

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

// pixiCvs.width = 640;
// pixiCvs.height = 480;

//check device
if (isMobile.any) {
    renderer = PIXI.autoDetectRenderer(525, 525, {
        view: pixiCvs,
        // antialias: true,
        transparent: true,
        preserveDrawingBuffer: true
    });
} else {
    renderer = PIXI.autoDetectRenderer(640, 480, {
        view: pixiCvs,
        // antialias: true,
        transparent: true,
        preserveDrawingBuffer: true
    });

    if (matchMedia('only screen and (max-width: 525px)').matches) {
        renderer.view.style.width = '640px';
        renderer.view.style.height = '480px';
    }

    if (matchMedia('only screen and (max-width: 450px)').matches) {
        renderer.view.style.width = '565px';
        renderer.view.style.height = '424px';
    }

    if (matchMedia('only screen and (max-width: 420px)').matches) {
        renderer.view.style.width = '535px';
        renderer.view.style.height = '401px';
    }

    if (matchMedia('only screen and (max-width: 304px)').matches) {
        renderer.view.style.width = '419px';
        renderer.view.style.height = '314px';
    }

    if (matchMedia('only screen and (max-width: 198px)').matches) {
        renderer.view.style.width = '313px';
        renderer.view.style.height = '235px';
    }
}

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


// $(function() {
// initialize Foundation
// $.when(
//     $.getScript("./js/foundation/foundation.min.js"),
//     $.Deferred(function(deferred) {
//         $(deferred.resolve);
//     })
// ).done(function() {
//     $(document).foundation("reveal", "reflow");
// });

$(document).foundation("reveal", "reflow");

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

if (!isMobile.any) {
    Tipped.create('.icon-bar .item', {
        radius: false,
        position: 'bottomleft'
    });
}


/* ==============================================
    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 isRealTime = false;
var isRealTimeFlash = false;
var isStatic = false;
var debug = false;
var video = document.getElementById("video");
var localStream;
var localStreamTrack;
var currentStream;
var mediaSupported = true;
var context;
var modelName;
var initialColor;
var faceAnim;
var spritesLoaded = false;
var demoHelpLoaded = false;
var realtimeHelpLoaded = false;
var faceTrackerLoaded = false;

// var canvas = document.getElementById("canvas");
// canvas.width = 700;
// canvas.height = 525;

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

// create PIXI texture and sprite
var videoAnim;
var videoTexture = PIXI.Texture.fromVideo(video);
var videoSprite = new PIXI.Sprite(videoTexture);

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

/***** handle different devices *****/
var getImageWidth = function() {
    var userImgWidth = 525;

    // iPhone 5/5s
    if (matchMedia('only screen and (min-device-width: 320px) and (max-device-width: 568px)').matches) {
        userImgWidth = 198;
    }

    // iPhone 6
    if (matchMedia('only screen and (min-device-width: 375px) and (max-device-width: 667px)').matches) {
        userImgWidth = 198;

    }

    // iPhone 6+
    if (matchMedia('only screen and (min-device-width: 414px) and (max-device-width: 736px)').matches) {
        userImgWidth = 198;
    }

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

    return userImgWidth;
};

/* ==============================================
Handle UI interaction
=============================================== */
$('#closeBtn').on("click", function() {
    localStorage.removeItem('color');
    $('#wrapper').fadeOut(1000, function() {
        //stop video and clear lipstick
        try {
            lipstick.clear();
            video.pause();
            videoSprite.visible = false;

            localStreamTrack.stop();
            compatibility.cancelAnimationFrame(faceAnim);
        } catch (error) {
            console.log(error);
        }

        //stop spritesheet animation
        if (spritesLoaded) {
            spriteSheets.stop();
        }

        //send message to parent
        if (window.top !== window.self) {
            window.top.postMessage('close iframe', '*');
        }

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


/* ==============================================
Receive product data from parent
=============================================== */
var fireOnce = once(function() {
    tracker.track("Application Start", "Nars Integrated Try-On started ", productID, appView, userID);
});

window.onmessage = function(e) {
    $('#wrapper').fadeIn(1000);

    e = e || window.event;

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

    if (received_data.message == "data") {
        fireOnce();

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

        if (method == 'realtime') {
            initRealTime(color);
            if (ID !== null && ID != "tryconBtn") {
                var img = new Image();
                $(img).attr('src', ID);

                img.onload = function() {
                    $('#spinnerOverlay').fadeOut("fast", function() {
                        imgCtx.drawImage(img, 0, 0);
                        //animate();
                    });
                };
            }
        } else if (method == 'demo') {
            modelName = ID;

            if ($('#realtimeHelp').is(':visible')) {
                $('#realtimeHelp').fadeOut();
            }

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

            $('#iconBar').fadeOut();
            // $('#facecakeLogo button.secondary, #facecakeLogo.button.secondary').css("background-color", "rgba(26, 26, 26, 0.20)");
            $('#closeBtn button.secondary, #closeBtn.button.secondary').css("background-color", "rgba(0, 0, 0, 0.75)");

            initDemo(ID, color);
        }

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

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

/* ==============================================
load static upload UI
=============================================== */
var initStaticUploadUI = function() {
    appView = "user upload";

    $('#closeBtn button.secondary, #closeBtn.button.secondary').css("background-color", "rgba(0, 0, 0, 0.0)");

    isRealTime = false;
    isStatic = true;

    $('#spinnerOverlay').fadeOut("fast");

    if (isMobile.tablet) {
        $('.upload-ui, .tablet').fadeIn();
    } else {
        $('.upload-ui, .desktop').fadeIn();
    }

    $('#fileSelect').fadeIn();
    $('#helpBtn').fadeOut();
    $('#rotateBtn').fadeOut();

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

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

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

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

    $('#uploadError').fadeOut();
    $('#slick').css("visibility","visible");
    $('.carouselBG').fadeIn();
    $('#closeBtn').fadeIn();
    $('#facecakeLogo').fadeIn();

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

    isRealTime = false;
    isStatic = false;
    isRealTimeFlash = false;

    var IEversion = detectIE();

    if (!webglDetect || IEversion !== false) {
        $('#flashHolder').fadeIn("fast");
        flashModule.load("swf/" + id + ".swf", "flashHolder");

        $('#spinnerOverlay').fadeOut("fast");

        return false
    }

    try {
        lipstick.clear();
        video.pause();
        videoSprite.visible = false;

        localStreamTrack.stop();
        compatibility.cancelAnimationFrame(faceAnim);
    } catch (error) {
        console.log(error);
    }

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

    // $('#rotateBtn, #nowebcamAlert, .upload-ui').fadeOut('fast');
    $('.upload-ui, .desktop, .tablet').fadeOut('fast');

    if ($('#flashHolder').is(':visible')) {
        $('#flashHolder').fadeOut("fast");
        swfobject.removeSWF("flashHolder");
        flashLoaded = false;
    }
};

/* ==============================================
start realtime video try-on
=============================================== */
var initRealTime = function(hex) {
    initialColor = hex;

    $('#fileSelect').fadeOut();
    $('#rotateBtn').fadeIn();
    $('#iconBar').fadeIn();

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

    // if (localStreamTrack !== undefined) {
    //     $.each(cvsArray, function(i, id) {
    //         $("#" + id + "").addClass("mirror");
    //     });

    //     // $('#facecakeLogo button.secondary, #facecakeLogo.button.secondary').css("background-color", "rgba(26, 26, 26, 0.0)");
    //     $('#closeBtn button.secondary, #closeBtn.button.secondary').css("background-color", "rgba(26, 26, 26, 0.0)");

    //     video.src = currentStream;
    //     // video.width = 700;
    //     // video.height = 525;
    //     setTimeout(function() {
    //         video.play();
    //     }, 750);

    //     return false;
    // }

    //show spinner and overlay
    $('#spinnerOverlay').fadeIn("fast");

    navigator.getUserMedia = (navigator.getUserMedia ||
        navigator.webkitGetUserMedia ||
        navigator.mozGetUserMedia ||
        navigator.msGetUserMedia);
    if (navigator.getUserMedia && !isMobile.any) {
        navigator.getUserMedia({
                video: true,
                audio: false
            },
            function(stream) {
                appView = "realtime";

                if ($('#demoHelp').is(':visible')) {
                    $('#demoHelp').fadeOut();
                }

                if (!realtimeHelpLoaded) {
                    $('#realtimeHelp').fadeIn();
                    realtimeHelpLoaded = true;
                }

                if (!faceTrackerLoaded) {
                    // basket.clear();
                    basket.require({
                        url: './js/jsfeat-min.js'
                    }, {
                        url: './js/frontalface.js'
                    }, {
                        url: './js/profiler.js'
                    }, {
                        url: './js/dat.gui.min.js'
                    }, {
                        url: './js/init.js'
                    }).then(function() {
                        basket.require({
                            url: './js/FaceScoutMain.min.js'
                        });

                        faceTrackerLoaded = true;
                    })
                } else {
                    compatibility.requestAnimationFrame(tick);
                }


                localStream = stream;
                localStreamTrack = localStream.getTracks()[0];

                isRealTime = true;

                $.each(cvsArray, function(i, id) {
                    $("#" + id + "").addClass("mirror");
                });

                // $('#iconBar').fadeIn();
                // $('#facecakeLogo button.secondary, #facecakeLogo.button.secondary').css("background-color", "rgba(26, 26, 26, 0.0)");
                $('#closeBtn button.secondary, #closeBtn.button.secondary').css("background-color", "rgba(0, 0, 0, 0.0)");

                var url = window.URL || window.webkitURL;
                currentStream = url ? url.createObjectURL(stream) : stream;
                video.src = currentStream;
                // video.width = 700;
                // video.height = 525;

                setTimeout(function() {
                    video.play();
                }, 750);
            },
            function(error) {
                initStaticUploadUI();

                return;
            }
        );
    } else if (isMobile.tablet) {
        initStaticUploadUI();
    } else {
        if (!flashModule.detect) {
            $('#spinnerOverlay').fadeOut("fast");
        } else {
            //hide spinner and handle UI based on device capabilities
            appView = "realtime";
            isRealTimeFlash = true;
            $('#spinnerOverlay').fadeOut("fast");
            $('#flashHolder').fadeIn("fast");
            flashModule.load("swf/CloseUp.swf", "flashHolder");
            $('#closeBtn button.secondary, #closeBtn.button.secondary').css("background-color", "rgba(0, 0, 0, 0.0)");
        }
        return;
    }
};

// initRealTime("ff9900");

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

    // console.log("tick");
};

// Wait for the video to start to play
video.addEventListener('play', function() {
    //hide spinner and handle UI based on device capabilities
    $('#spinnerOverlay').fadeOut("fast");

    videoSprite.width = video.width;
    videoSprite.height = video.height;

    // videoSprite.x = (video.width - 525) / 2;
    // // videoSprite.y = -(video.height - 525) / 2;
    // videoSprite.y = 0;

    videoSprite.visible = true;

    stage.addChild(videoSprite);

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

    tracker.track("Apply Asset To Image", productID, productID, appView, userID);

    animate();
}, false);

function clearImage() {
    imgCtx.setTransform(1, 0, 0, 1, 0, 0);
    imgCtx.translate(0, 0);
    imgCtx.rotate(0, 0);
    imgCtx.clearRect(0, 0, 1000, 1000);
}

/* 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
    $('#spinnerOverlay').fadeIn("fast");

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

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

                var shareCvs = document.getElementById("shareCvs");
                var shareCtx = shareCvs.getContext("2d");
                shareCtx.clearRect(0, 0, 525, 525);

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

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

                    imgShareURL = data.imgPath;

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

                // $('#shareImage').attr("src", data.imgPath);

            }
        });
    };

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

function downloadCanvas(link, filename) {
    link.href = imgData;
    link.download = filename;
}

/***** UI/buttons and such *****/

var initCarousel = function(arr) {
    if (!isSlick) {
        //swatch carousel
        $('#slick').slick({
            slidesToShow: 7,
            slidesToScroll: 7,
            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: 525,
                settings: {
                    slidesToShow: 7,
                    slidesToScroll: 7,
                    infinite: true,
                    dots: true
                }
            }, {
                breakpoint: 451,
                settings: {
                    slidesToShow: 6,
                    slidesToScroll: 6
                }
            }, {
                breakpoint: 421,
                settings: {
                    slidesToShow: 5,
                    slidesToScroll: 5
                }
            }, {
                breakpoint: 320,
                settings: {
                    slidesToShow: 4,
                    slidesToScroll: 4
                }
            }, {
                breakpoint: 304,
                settings: {
                    slidesToShow: 3,
                    slidesToScroll: 3
                }
            }]
        });

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

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


$(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");

    localStorage.setItem("color", hex);

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

    if (isRealTime) {
        lipstick.apply(hex);
        tracker.track("Apply Asset To Image", productID, productID, appView, userID);
    } else if (flashLoaded) {
        document.getElementById("flashHolder").apply(hex);
        tracker.track("Apply Asset To Image", productID, productID, appView, userID);
    } else 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();
});

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

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

$('#snapshotBtn').on("click", function() {
    if (isRealTime || isStatic) {
        exportAndSaveCanvas();
    } else if (flashLoaded) {
        document.getElementById("flashHolder").share();
        $('#iconBar').fadeOut();
        // $('#slick').fadeOut();
        $('#slick').css("visibility","hidden");
        $('.carouselBG').fadeOut();
        $('#closeBtn').fadeOut();
        $('#facecakeLogo').fadeOut();
    }
});

//flip camera
$('#rotateBtn').on("click", function() {
    if (flashLoaded) {
        document.getElementById("flashHolder").flip();
    } else {
        if ($('#holder').hasClass("mirror")) {
            $.each(cvsArray, function(i, id) {
                $("#" + id + "").removeClass("mirror");
            });
        } else {
            $.each(cvsArray, function(i, id) {
                $("#" + id + "").addClass("mirror");
            });
        }
    }

});

$('#clearBtn').on("click", function() {
    if (isRealTime) {
        lipstick.clear();
    } else if (flashLoaded) {
        document.getElementById("flashHolder").clear();
    } else if (isStatic) {
        clearStaticLips();
    }
});

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

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

// $('.social-links a.close').on("click", function() {
//     $('#shareModal').foundation('reveal', 'close');
// });

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

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

$('.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');
});

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

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

$('input[type=file]').on('change', function(e) {
    var myImg = new Image();

    $('#fileForm').submit();

    // $('#spinnerOverlay').fadeIn();

    // 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) {
    $('#uploadError').fadeOut();

    $('.upload-ui, .desktop, .tablet').fadeOut();
    $('#spinnerOverlay').fadeIn();

    e.preventDefault();

    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) {
            stage.removeChild(staticFaceImg);
            stage.removeChild(staticLipsImg);

            var face = URL + data.face;
            var lips = URL + data.mouth;

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

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

            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
=============================================== */

// 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) {
            console.log("success");
            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');
                }, 2000);

                tracker.track("Share Email", toEmailval, productID, appView, userID);
            });
        },
        error: function(xhr, type, data) {
            console.log("fail");
            $('.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');
                }, 2000);
            });
        }
    });
});

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

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


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

$(window).resize(function() {
    flashModule.resize();

    /* ==============================================
    resize PIXI renderer
    =============================================== */
    if (!isMobile.any) {
        if (matchMedia('only screen and (max-width: 525px)').matches) {
            renderer.view.style.width = '640px';
            renderer.view.style.height = '480px';
        }

        if (matchMedia('only screen and (max-width: 450px)').matches) {
            renderer.view.style.width = '565px';
            renderer.view.style.height = '424px';
        }

        if (matchMedia('only screen and (max-width: 420px)').matches) {
            renderer.view.style.width = '535px';
            renderer.view.style.height = '401px';
        }

        if (matchMedia('only screen and (max-width: 304px)').matches) {
            renderer.view.style.width = '419px';
            renderer.view.style.height = '314px';
        }

        if (matchMedia('only screen and (max-width: 198px)').matches) {
            renderer.view.style.width = '313px';
            renderer.view.style.height = '235px';
        }
    }
});

/* ==============================================
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 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;

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


$(document).on("click", ".fc-track", function() {
    tracker.track($(this).data("action"), $(this).data("desc"), productID, appView, userID);
});

/* ==============================================
functions for flash
=============================================== */
function emailShare(imgShareURL) {
    imgShareURL = imgShareURL;
    $('#emailModal').foundation('reveal', 'open');
}

function noFlashCameraDetected() {
    $('#flashHolder').fadeOut("fast");
    swfobject.removeSWF("flashHolder");
    flashLoaded = false;

    initStaticUploadUI();
}

function flashShareClosed() {
    $('#iconBar').fadeIn();
    $('#slick').css("visibility","visible");
    $('.carouselBG').fadeIn();
    $('#closeBtn').fadeIn();
    $('#facecakeLogo').fadeIn();
}

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