$(document).ready(function(){
	var hash = window.location.hash;
	if(hash){
		console.log(hash);
		$(hash).lightbox_me({
            onLoad: function ()
            {
                if ($('#box2D-pause').hasClass('paused'))
                {
                    $('#box2D-pause').click();
                }
            },
            onClose: function ()
            {
                $('#box2D-pause').click();
                window.location.hash = "";
            }
        });
	}
	
	$('.light-box .insert-iframe').each(function(){
		var iframe = $(this).html();
		$(this).html('');
	});
	init();
});

function init()
{

    var b2Vec2 = Box2D.Common.Math.b2Vec2,
        b2AABB = Box2D.Collision.b2AABB,
        b2BodyDef = Box2D.Dynamics.b2BodyDef,
        b2Body = Box2D.Dynamics.b2Body,
        b2FixtureDef = Box2D.Dynamics.b2FixtureDef,
        b2Fixture = Box2D.Dynamics.b2Fixture,
        b2World = Box2D.Dynamics.b2World,
        b2MassData = Box2D.Collision.Shapes.b2MassData,
        b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape,
        b2CircleShape = Box2D.Collision.Shapes.b2CircleShape,
        b2DebugDraw = Box2D.Dynamics.b2DebugDraw,
        b2MouseJointDef = Box2D.Dynamics.Joints.b2MouseJointDef;

    var world = new b2World(
    new b2Vec2(0, 0) //gravity
    , true //allow sleep
    );

    var fixDef = new b2FixtureDef;
    fixDef.density = 1.0;
    fixDef.friction = 0.5;
    fixDef.restitution = 0.2;

    var bodyDef = new b2BodyDef;

    var phyWidth = $('#canvas').width() / 30;
    var phyHeight = $('#canvas').height() / 30;

    //create ground
    bodyDef.type = b2Body.b2_staticBody;
    fixDef.shape = new b2PolygonShape;
    fixDef.shape.SetAsBox(phyWidth, 1);
    bodyDef.position.Set(phyWidth / 2, phyHeight + 1);
    world.CreateBody(bodyDef).CreateFixture(fixDef);
    bodyDef.position.Set(phyWidth / 2, -1);
    world.CreateBody(bodyDef).CreateFixture(fixDef);
    fixDef.shape.SetAsBox(1, phyHeight);
    bodyDef.position.Set(-1, phyHeight / 2);
    world.CreateBody(bodyDef).CreateFixture(fixDef);
    bodyDef.position.Set(phyWidth + 1, phyHeight / 2);
    world.CreateBody(bodyDef).CreateFixture(fixDef);

    $('.box2D-dynamic img').mousedown(function (event)
    {
        event.preventDefault();
    });

    $('.box2D-static').each(function ()
    {

        var divarea = new Object();
        divarea.divID = $(this).attr('id');
        divarea.divW = $(this).outerWidth();
        divarea.divH = $(this).outerHeight();
        divarea.divX = $(this).position().left;
        divarea.divY = $(this).position().top;
        divarea.divOrgX = divarea.divX + (divarea.divW / 2);
        divarea.divOrgY = divarea.divY + (divarea.divH / 2);

        fixDef.shape.SetAsBox(divarea.divW / 60, divarea.divH / 60);

        bodyDef.type = b2Body.b2_staticBody;

        bodyDef.position.Set(divarea.divOrgX / 30, divarea.divOrgY / 30);

        bodyDef.userData = divarea;

        world.CreateBody(bodyDef).CreateFixture(fixDef);

    });

    $('.box2D-dynamic').each(function ()
    {

        var divarea = new Object();
        divarea.divID = $(this).attr('id');
        divarea.divW = $(this).outerWidth();
        divarea.divH = $(this).outerHeight();
        divarea.divX = $(this).position().left;
        divarea.divY = $(this).position().top;
        divarea.divOrgX = divarea.divX + (divarea.divW / 2);
        divarea.divOrgY = divarea.divY + (divarea.divH / 2);

        fixDef.shape.SetAsBox(divarea.divW / 60, divarea.divH / 60);

        bodyDef.type = b2Body.b2_dynamicBody;

        bodyDef.position.Set(divarea.divOrgX / 30, divarea.divOrgY / 30);

        bodyDef.userData = divarea;

        if ($(this).hasClass('box2D-fixedRotation'))
        {
            bodyDef.fixedRotation = true;
        }
        else
        {
            bodyDef.fixedRotation = false;
        }

        world.CreateBody(bodyDef).CreateFixture(fixDef);

    });

    //setup debug draw
    var debugDraw = new b2DebugDraw();
    debugDraw.SetSprite(document.getElementById("canvas").getContext("2d"));
    debugDraw.SetDrawScale(30.0);
    debugDraw.SetFillAlpha(0.5);
    debugDraw.SetLineThickness(1.0);
    debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit);
    world.SetDebugDraw(debugDraw);

    box2Dphysics = window.setInterval(update, 10);

    //pause
    $('#box2D-pause').click(function ()
    {

        if ($(this).hasClass('paused'))
        {
            $(this).removeClass('paused');
            window.clearTimeout(box2Dphysics);
        }
        else
        {
            $(this).addClass('paused');
            window.clearTimeout(box2Dphysics);
            box2Dphysics = window.setInterval(update, 10);
        }

    });

    //lightboxes
    $('.lb-box a').each(function ()
    {
        $(this).mouseup(function ()
        {

            $($(this).attr('href')).lightbox_me(
            {
                onLoad: function ()
                {
                    if ($('#box2D-pause').hasClass('paused'))
                    {
                        $('#box2D-pause').click();
                    }
                },
                onClose: function ()
                {
                    $('#box2D-pause').click();
                    window.location.hash = "";
                }
            });

        });
    });

    //mouse
    var mouseX, mouseY, mousePVec, isMouseDown, selectedBody, mouseJoint;
	
	var div = $('#box2d-container').Touchable();
	
	div.bind("touchablemove", function (e) {
    	$(this).children('a').click();
    });
	
    div.bind("touchablemove", function (e, touch)
    {
        world.SetGravity(new b2Vec2(0, 10));
        isMouseDown = true;
        mouseX = ( touch.currentTouch.x - $('#box2d-container').offset().left) / 30; /*- $('#box2d-container').offset().left) / 30;*/
        mouseY = ( touch.currentTouch.y - $('#box2d-container').offset().top) / 30; /*- $('#box2d-container').offset().top) / 30;*/
    });

    div.bind("touchableend", function ()
    {
        world.SetGravity(new b2Vec2(0, 0));
        isMouseDown = false;
        mouseX = undefined;
        mouseY = undefined;
        $(this).children('a').click();
    });

    function getBodyAtMouse()
    {
        mousePVec = new b2Vec2(mouseX, mouseY);
        var aabb = new b2AABB();
        aabb.lowerBound.Set(mouseX - 0.001, mouseY - 0.001);
        aabb.upperBound.Set(mouseX + 0.001, mouseY + 0.001);

        // Query the world for overlapping shapes.
        selectedBody = null;
        world.QueryAABB(getBodyCB, aabb);
        return selectedBody;
    }

    function getBodyCB(fixture)
    {
        if (fixture.GetBody().GetType() != b2Body.b2_staticBody)
        {
            if (fixture.GetShape().TestPoint(fixture.GetBody().GetTransform(), mousePVec))
            {
                selectedBody = fixture.GetBody();
                return false;
            }
        }
        return true;
    }

    //update

    function update()
    {

        if (isMouseDown && (!mouseJoint))
        {
            var body = getBodyAtMouse();
            if (body)
            {
                var md = new b2MouseJointDef();
                md.bodyA = world.GetGroundBody();
                md.bodyB = body;
                md.target.Set(mouseX, mouseY);
                md.collideConnected = true;
                md.maxForce = 300.0 * body.GetMass();
                mouseJoint = world.CreateJoint(md);
                body.SetAwake(true);
            }
        }

        if (mouseJoint)
        {
            if (isMouseDown)
            {
                mouseJoint.SetTarget(new b2Vec2(mouseX, mouseY));
            }
            else
            {
                world.DestroyJoint(mouseJoint);
                mouseJoint = null;
            }
        }

        world.Step(1 / 30, 6, 2);
        //world.DrawDebugData();
        world.ClearForces();

        for (var b = world.GetBodyList(); b; b = b.GetNext())
        {
            if (b.GetUserData() != null && b.GetType() == 2)
            {
                var bodyinfo = b.GetUserData();
                if (b.IsAwake())
                {
                    $("#" + bodyinfo.divID).removeClass('box2d-sleeping');
                    for (var f = b.GetFixtureList(); f; f = f.GetNext())
                    {
                        $("#" + bodyinfo.divID).css(
                        {
                            left: (b.GetPosition().x * 30) - (bodyinfo.divW / 2),
                            top: (b.GetPosition().y * 30) - (bodyinfo.divH / 2),
                            rotate: b.GetAngle() + 'rad'
                        });
                    }
                }
                else
                {
                    $("#" + bodyinfo.divID).addClass('box2d-sleeping');
                }
            }
        }
    };
};

