$(document).ready(function(){
    var initialWidth = 320
    var max_width = $('body').width() * .75
    var auto_in_px = ($('body').width() - $("#pageBox").width()) * .5
    $("#slide-admin, #slide-edit").click(function(){
        auto_in_px = ($('body').width() - $("#pageBox").width()) * .5
        if($('body iframe').length==0){
            var handle = '<div id="handle"></div>'
            var close = '<span id="close">←</span>'
            $('body').prepend('<iframe id="admin" src="/ajax/admin/_left/" seamless></iframe>'+handle + close)
            var dragging = function(){
                var drag_pos = $('#handle').offset().left

                  if (drag_pos < 300 && 100 < drag_pos) {
                    drag_pos = 300;
                  }

                  if (drag_pos > max_width) {
                    drag_pos = max_width;
                  }
                  if (drag_pos < 100){
                        $('#admin').css({width: 0})
                        $('#pageBox').css({ "margin-left": 'auto'})
                        return false
                    }

                $('#admin').css({width: (drag_pos + 2) + "px"})
                $("#pageBox").css({'margin-left': drag_pos + "px"})
                $("#admin").contents().find("#edit").css({width: $("#admin").innerWidth()-110 })
                $("#close").css({left:(drag_pos) + "px"})
            }

            var dragged = function(){
                var sb_width = $("#admin").width()
                $("#handle, #close").css({left: (sb_width + 2) + "px"})
            }

            $('#handle').draggable({
                    iframeFix: true,
                    axis: 'x',
                    drag: dragging,
                    stop: dragged}
                    )
        }

        if($(this).is("#slide-edit")){
            $("#admin").addClass("editing")
        }
        $('#admin').animate({
            width: initialWidth + "px"
        }, 500, function(){
            $('#handle').css({left: (initialWidth-2)+ "px"})
            $("#close").css({left:($("handle").css('left') - 2) + "px"})
        })
        if(auto_in_px < initialWidth){
            
        $("#pageBox").animate({
            'margin-left': initialWidth + "px"
        }, 500)}
        return false
    })
})

