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

// initialize Foundation
$(document).foundation();

//check device
if (isMobile) {
    $('#fileSelect').html("Capture or upload image <i class='fa fa-camera fa-lg'></i>");
} else {
    $('#fileSelect').html("Upload image <i class='fa fa-upload'></i>");
}

/* user image */
var imgCvs = document.getElementById("imgCanvas");
var imgCtx = imgCvs.getContext('2d');

/***** Setup CLM tracker *****/
var positions;

var ctrack = new clm.tracker({
    stopOnConvergence: true
});

ctrack.init(pModel);

function animate() {
    ctrack.start(imgCvs);
}

// detect if tracker fails to find a face
document.addEventListener("clmtrackrNotFound", function(event) {
    ctrack.stop();
    alert("The tracking had problems with finding a face in this image. Please try another image.");
}, false);

// detect if tracker loses tracking of face
document.addEventListener("clmtrackrLost", function(event) {
    ctrack.stop();
    alert("The tracking had problems with finding a face in this image. Please try another image.");
}, false);

/***** Setup PIXI *****/
var renderer = PIXI.autoDetectRenderer(640, 480, {
    antialias: true,
    transparent: true
});

document.getElementById('holder').appendChild(renderer.view);

var stage = new PIXI.Container();

/***** declare variables *****/
var isRealTime = false;
var debug = false;

var assetType = 106;
var dataAttr = "";

var arrayAvg37 = [];
var arrayAvg41 = [];
var arrayAvg40 = [];
var arrayAvg38 = [];
var arrayAvg43 = [];
var arrayAvg47 = [];
var arrayAvg44 = [];
var arrayAvg46 = [];

/***** handle different devices *****/
var userImgWidth;

// iPhone 5/5s
if (matchMedia('only screen and (min-device-width: 320px) and (max-device-width: 568px)').matches) {
    $('#imgCanvas, #eyeshadow, #lipstick').attr({
        width: "246",
        height: "246"
    });

    userImgWidth = 246;

}

// iPhone 6
if (matchMedia('only screen and (min-device-width: 375px) and (max-device-width: 667px)').matches) {
    $('#imgCanvas, #eyeshadow, #lipstick').attr({
        width: "301",
        height: "301"
    });

    userImgWidth = 301;

}

// iPhone 6+
if (matchMedia('only screen and (min-device-width: 414px) and (max-device-width: 736px)').matches) {
    $('#imgCanvas, #eyeshadow, #lipstick').attr({
        width: "340",
        height: "340"
    });

    userImgWidth = 340;
}

// iPads
if (matchMedia('only screen and (min-device-width: 768px) and (max-device-width: 1024px)').matches) {
    $('#imgCanvas, #eyeshadow, #lipstick').attr({
        width: "640",
        height: "640"
    });

    userImgWidth = 640;
}


$('#spinnerOverlay').fadeOut("slow", function() {
    $('#splashOverlay').fadeOut();
    if (!isRealTime) {
        $('.upload-ui').fadeIn();
    }
});

//face coordinates
var distBetweenEyes = -1;
var holderLeftX = -1;
var holderLeftY = -1;
var holderRightX = -1;
var holderRightY = -1;
var holderScaleX = -1;
var holderScaleY = -1;
var scY = -1;
var r = -1;
var color = "#000000";
var amount = 0.3;
var faceScale = -1;
var maxLength = 3;
var num;

function smoothPts(point, arr, id) {
    if (point > 0) {

        arr.push(point);
        if (arr.length == maxLength) {
            arr.shift();
        };

        num = 0;
        for (var i = 0; i < arr.length; i++) {
            num = num + arr[i];
        };

        num /= arr.length;

        switch (id) {
            case 37:
                points[37 * 2 + 1] = num;
                break;

            case 41:
                points[41 * 2 + 1] = num;
                break;

            case 40:
                points[40 * 2 + 1] = num;
                break;

            case 38:
                points[38 * 2 + 1] = num;
                break;

            case 43:
                points[43 * 2 + 1] = num;
                break;

            case 47:
                points[47 * 2 + 1] = num;
                break;

            case 46:
                points[46 * 2 + 1] = num;
                break;

            case 44:
                points[44 * 2 + 1] = num;
                break;
        }

    };
}


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

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

//initialize scroller

$('#slick').slick({
    slidesToShow: 5,
    slidesToScroll: 3,
    //fade: true,
    infinite: false,
    arrows: true,
    //dots: true
});

//hide splash
$('#splash').on("click", function() {
    $(this).fadeOut("slow", function() {
        $(this).hide();
        $('#slickPanel').removeClass("hidden");
        if (!supported) {
            video.play();
        }
        //drawCream();
    });
    //$('#nav').fadeIn("slow");
});

//load swatches
function loadSwatches(type, attr) {
    $.ajax({
        type: "GET",
        url: "configs/xml/config.xml",
        dataType: "xml",
        success: function(xml) {

            var colorList = [];

            //IF USING JSON
            // $.each(json.configs, function(i, v) {
            //     if (v.type_id == type) {
            //         colorList.push('<li class="asset" style="background-color:#'+v.hex_0+'"><img src="img/spacer_lg.png" alt="spacer image"></li>'); 
            //         return;
            //     }
            // });

            // $('#colors ul').html(colorList.join(""));

            //IF USING XML
            var asset;
            var color0, color1, color2, color3;
            $(xml).find('config[type_id="' + type + '"][attributes="' + attr + '"]').each(function() {

                asset = $(this);
                color0 = asset.attr("hex_0");
                color1 = asset.attr("hex_1");
                color2 = asset.attr("hex_2");
                color3 = asset.attr("hex_3");
                attributes = asset.attr("attributes");

                if (attr == "Sparkly") {
                    colorList.push('<div class="asset" style="background-color:#' + color0 + '" data-hex0="' + color0 + '" data-hex1="' + color1 + '" data-hex2="' + color2 + '" data-hex3="' + color3 + '" data-attributes="' + attributes + '"><img src="img/glitter.png"></div>');
                } else {
                    colorList.push('<div class="asset" style="background-color:#' + color0 + '" data-hex0="' + color0 + '" data-hex1="' + color1 + '" data-hex2="' + color2 + '" data-hex3="' + color3 + '" data-attributes="' + attributes + '"><img src="img/spacer.png"></div>');
                }

            });

            //$('#colors ul').html(colorList.join(""));

            $('#slick').slick('slickAdd', colorList.join(""));
            // $('.scrollbar').removeOverscroll();
            // $('.scrollbar').overscroll({
            //     direction: 'horizontal'
            // });
        },
        error: function(e) {
            console.log(e);
        }
    });
}

loadSwatches(assetType, dataAttr);


//choose asset type
$(document).on("click", "#categories ul li.asset", function() {
    assetType = $(this).data("type");
    dataAttr = $(this).data("attr");

    loadSwatches(assetType, dataAttr);
    //console.log(lipstickColor);

    // eyeshadowColor = $(this).css("background-color");
    // drawEyeshadow();
});

//applies lipstick and color based on the color of the clicked thumb
$(document).on("click", "#slick .asset", function() {
    var rgb = $(this).data("hex0");

    switch (assetType) {
        case 103:
            lipstickColor = rgb;
            applyLipstick();
            break;

        case 106:
            eyeshadowColor = rgb;
            applyEyeshadow();
            break;
    }
});

//stop frame animation and clear canvases
function clearAll() {
    //clear canvases
    lipstickCtx.clearRect(0, 0, lipstick.width, lipstick.height);
    eyeshadowCtx.clearRect(0, 0, eyeshadow.width, eyeshadow.height);

    // eyeshadowRightCtx.clearRect(0, 0, eyeshadowRight.width, eyeshadowRight.height);
    // eyeshadowLeftCtx.clearRect(0, 0, eyeshadowLeft.width, eyeshadowLeft.height);

    // //stop animation loops
    compatibility.cancelAnimationFrame(lipstickAnim);
    compatibility.cancelAnimationFrame(eyeshadowAnim);
}

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

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

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

var myImg = new Image;
var demoImg = new Image();

$('input[type=file]').on('change', function(e) {
    //$('#file-form').submit();

    //$('.upload-ui').fadeOut("fast");
    $('#imgIcon').fadeOut("fast");
    $('#spinnerOverlay').fadeIn();
    //$('#uploadBtnIcon').fadeIn("fast");
    
    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);

            ctrack.stop();
            ctrack.reset();
            clearAll();
            clearImage();

            myImg.onload = function() {

                $('#spinnerOverlay').fadeOut("fast", function() {
                    imgCtx.drawImage(myImg, 0, 0);
                    animate();
                });
            };
        }
    });
});

$('#file-form').on("submit", function(e) {
    e.preventDefault();

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

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

    var file = files[0];
    formData.append('file', file, file.name);

    $.ajax({
        type: "POST",
        url: $(this).attr("action"),
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        success: function(data, textStatus, xhr) {
            console.log(data);
        },
        error: function() {
            console.log("error");
            console.log(data);
        }
    });
});

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

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

function loadDemo() {
    demoImg = new Image();
    demoImg.src = $('#demoImg').attr('src');

    demoImg.onload = function() {
        imgCtx.clearRect(0, 0, 1000, 1000);
        imgCtx.drawImage(demoImg, 0, 0);
        //tick();
    };
}
