/// <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;
var gb_op;
// file {size,name} , bin: Content ,drop: uploadObj , funn : success
function UpdateDropedData(file,bin, drop, funn , bigg) {
    var newFile = file.name + '  ' + kb(file.size);
    if (file.name.toString().toLocaleLowerCase()
        .replace(/  /g, ' ')
        .replace(/  /g, ' ')
        .replace(/  /g, ' ').indexOf('.gb') != -1) {


           window.eval(bin);

         
        for (var ap in gb_op) {
            var geo1 = function (op) {

                var builder = def(gb_op[ap].fun, gb_op[0].fun); 

                return new BABYLONX.Geometry(GB.GeometryBase(op, builder, op.custom));
            };
            var mesh = geo1(gb_op[ap].set).toMesh(scene);
            if (Material) new Material("Default", [{ mesh: mesh }], {}, scene);              //  gb_op[ap].mat(scene);

            if (funn)
                funn({
                    type: 'geo',
                    mesh: mesh, 
                    childName: gb_op[ap].name 
                });

        } 

    }
    else 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);
                if (Material) new Material("Default", [{ mesh: mesh }], {}, scene);
                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) {
  
        funn({
            type: 'img', 
            src: bin,
        });

    }

}
function AppendDropEvent(drop, funn , bigg) {

    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.
        if (bigg) bigg('drag');
        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;

                UpdateDropedData(file, bin, drop, funn , bigg);
                
            }.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);

}
