/// <reference path="../worker/objreader.js" />
var canvas = document.getElementById("renderCanvas");

var noise, time = 0;

var camera, _null = "null value";
var engine = new BABYLON.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true });
var scene = createScene();

engine.runRenderLoop(function () {
    if (scene) {
        scene.render();
    }
});

// Resize
window.addEventListener("resize", function () {
    engine.resize();
});


function addEventHandler(obj, evt, handler) {
    if (obj.addEventListener) {
        // W3C method
        obj.addEventListener(evt, handler, false);
    } else if (obj.attachEvent) {
        // IE method.
        obj.attachEvent('on' + evt, handler);
    } else {
        // Old school method.
        obj['on' + evt] = handler;
    }
}

if (window.FileReader) {

    Function.prototype.bindToEventHandler = function bindToEventHandler() {
        var handler = this;
        var boundParameters = Array.prototype.slice.call(arguments);
        //create closure
        return function (e) {
            e = e || window.event; // get window.event if e argument missing (in IE)
            boundParameters.unshift(e);
            handler.apply(this, boundParameters);
        }
    };




} else {
    //not support filereader
}

var objectIndex = 0;

function AppendDropEvent(drop, funn) {

    var data = null;


    function cancel(e) {
        if (e.preventDefault) { e.preventDefault(); }
        return false;
    }

    addEventHandler(drop, 'drop', function (e) {
        e = e || window.event; // get window.event if e argument missing (in IE)
        if (e.preventDefault) { e.preventDefault(); } // stops the browser from redirecting off to the image.

        var dt = e.dataTransfer;
        var files = dt.files;
        for (var i = 0; i < files.length; i++) {
            var file = files[i];
            var reader = new FileReader();



            addEventHandler(reader, 'loadend', function (e, file) {
                var bin = this.result;
                var newFile = file.name + '  ' + kb(file.size);

                if (file.name.toString().toLocaleLowerCase()
                    .replace(/  /g, ' ')
                    .replace(/  /g, ' ')
                    .replace(/  /g, ' ').indexOf('.obj') != -1) {

                    data = (bin);

                    var myWorker = new Worker('/worker/objreader.js');
                    myWorker.postMessage({ data: data });
                    var wd = new wind({
                        start: 0,
                        step: 10,
                        fun: function (d) {
                            first('.ab', null, drop).style.width = d + '%';
                        }
                    });
                    myWorker.onmessage = function (e) {
                        if (e.data.toString().indexOf('prg') == 0) {
                            wd.go(100 * min(1., e.data.toString().replace('prg', '').valueOf()));

                            if (min(1., e.data.toString().replace('prg', '').valueOf()) == 1) {
                                myWorker.terminate();
                                first('.ab', null, drop).style.width =  '0%';
                            }
                        }
                        else { 
                            var mesh = new BABYLONX.Geometry(e.data.geo).toMesh(scene);
                            mesh.material = defMat; 
                               if (funn)  
                                funn({
                                    type: 'geo',
                                    mesh: mesh, 
                                    geometry: e.data.geo,
                                    parentName: file.name,
                                    childName: e.data.obj.g,
                                    info: 'v' + e.data.obj.v.length + ': t' + e.data.obj.vt.length + ': f' + e.data.obj.f.length
                                });
                             
                        }
                    }
                }
                else if (file.name.toString().toLocaleLowerCase().indexOf('.jpg') != -1 ||
                    file.name.toString().toLocaleLowerCase().indexOf('.png') != -1 ||
                    file.name.toString().toLocaleLowerCase().indexOf('.jpeg') != -1) {

                    var img = document.createElement("img");
                    img.file = file;
                    img.className = 'w-02 m-0005 rad-02 op3 c-htrans op-h5';
                    img.src = bin;
                    img.title = newFile;
                    img.addEventListener('click', function () {
                        currTxr = this.src; reMatCurr()
                    });
                    img.addEventListener('load', function () {
                        currTxr = this.src; reMatCurr();
                    });

                    funn({
                        type: 'img',
                        mesh: img,
                        src: bin,
                    });

                }
            }.bindToEventHandler(file));
            if (file.name.toString().toLocaleLowerCase().indexOf('.obj') != -1)
                reader.readAsText(file);
            else reader.readAsDataURL(file);
        }
        return false;
    });
    addEventHandler(drop, 'dragover', cancel);
    addEventHandler(drop, 'dragenter', cancel);

}
