
var sampleCode = " \
/* \n\
 * Welcome to Processing.alt ! \n\
 * \n\
 * Press the Green Run button to see this Processing Sketch \n\
 * Press the Floppy Save button to save your code.  \n\
 * Press the Blue Share button to publish your code to Gallery. \n\
 * Login using your Gmail account. The door button in top left corner. \n\
 * Press the Folder button to look at Gallery of sketches and your saved files. \n\
*/ \n\
 \n\
 \n\
size(500, 500); \n \
smooth(); \n \
background(0); \n \
strokeWeight(10); \n \
 \n \
for(int i = 0; i < width; i++) { \n \
  float r = random(255); \n \
  float x = random(0, width); \n \
  stroke(r, 100); \n \
  line(i, 0, x, height); \n \
} \n \
";

function now() {
    var d = new Date();
    return Date.UTC(d.getUTCFullYear(),
        d.getUTCMonth(),d.getUTCDate(),
        d.getUTCHours(),d.getUTCMinutes(),
        d.getUTCSeconds()) / 1000;
}

function getSource(id) {
    return session.editor.mirror.getCode();
}

function showShareSettings() {
    $('#sharebox').css('top',(($(document).height()-200)/2)+'px');
    $('#sharebox').css('left',(($(document).width()-300)/2)+'px');
    $('#share').attr('checked', session.share);
    $('#share').change(
        function() { 
            if($(this).is(':checked')) {
                $('#permabox').show(function() { $('#uniqurl').select(); });
            } else {
                $('#permabox').hide();
            }
        });
    if(session.editor.filename != undefined) {
        if(session.share) {
            $('#uniqurl').val('http://p.altcanvas.com/'+session.editor.uid);
            $('#permabox').show(function() { $('#uniqurl').select(); });
        } else {
            $('#permabox').hide();
        }
    } else {
        $('#permabox').hide();
        $('#uniqurl').val('Please save the sketch');
    }
    $('#shareoptions').fadeIn();
    session.isShareOptions = true;
}

function hideShareSettings() {
    session.share = $('#share').is(':checked')
    $("#shareoptions").fadeOut();
    session.isShareOptions = false;
}

function saveCode() {
    if(session.editor.filename == undefined) {
        var filename = prompt("   Save code   ", null);
        var uid = undefined;
    } else {
        var filename = session.editor.filename;
        var uid = session.editor.uid;
    }
    if(filename == null) return;
    var source = getSource();

    $.post('/_ajax/sketch', { op : 'save', 
                    scope : 'user',
                    name : filename,
                    uid : uid,
                    code : source,
                    share : session.share },
                    function(data) {
                        resp = $.parseJSON(data);
                        if(resp.result == 'NOT_LOGGED_IN') {
                            alert('You need to login');
                            return;
                        }
                        if(resp.result != 'SUCCESS') {
                            alert(data);
                            return;
                        }
                        session.editor.filename = filename;
                        session.editor.uid = resp.uid;
                        undirtyEditor(filename);
                    });
}

function runCode() {
    if(!session.isPlaying) {

        if(session.isFullscreen) {

            $('#fsplayer').append('<canvas id="display"></canvas>');
            $('#display').css('position','absolute');
            var bbox = {};
            bbox.x = 0
            bbox.y = 0;
            bbox.w = $(document).width();
            bbox.h = $(document).height();
            session.isPlaying = true;
            $('#fsplayer').fadeIn(function() {
                try {
                    Processing($("#display")[0], getSource(), bbox); 
                } catch(err) {
                    alert('Error: '+err.name+'\n'+err.message);
                    $(this).css('background-image',
                        'url("/_images/run_40x40.png")');
                    $("#display").remove();
                    session.isPlaying = false;
                }
            });

        } else {

            $(this).css('background-image','url("/_images/back_40x40.png")');

            $('body').append('<canvas id="display"></canvas>');
            $('#display').css('position','absolute');
            var bbox = {};
            bbox.x = editorLeft + editorWidth;
            bbox.y = 0;
            bbox.w = $(document).width() - bbox.x;
            bbox.h = $(document).height() - bbox.y;
            session.isPlaying = true;
            try {
                Processing($("#display")[0], getSource(), bbox); 
            } catch(err) {
                alert('Error: '+err.name+'\n'+err.message);
                $(this).css('background-image','url("/_images/run_40x40.png")');
                $("#display").remove();
                session.isPlaying = false;
            }
        }
    } else {
        $(this).css('background-image','url("/_images/run_40x40.png")');

        $("#display").remove();

        session.isPlaying = false;
    }
}

function closeEditor() {
    var id = parseInt($(this).attr('id').replace('close',''));
    $('#editor'+id).remove();
}

function undirtyEditor(filename) {
    var title = (filename === undefined) ? 'Untitled' : filename;
    $('#editor #title').text(title);
    session.editor.isDirty = false;
}

function dirtyEditor() {
    var cur = $('#editor #title').text();
    if(cur.substring(cur.length-1) != '*') {
        $('#editor #title').text(cur+'*');
    }
    session.editor.isDirty = true;
}

function loadCode(content, filename, uid, share, isMine) {
    session.editor.mirror.setCode(content);
    session.share = share;
    if(isMine) {
        session.editor.filename = filename;
        session.editor.uid = uid;
    } else {
        session.editor.filename = undefined;
        session.editor.uid = undefined;
    }
    undirtyEditor(filename);
}

function exitSketchList() {
    $("#sketches").fadeOut();
    session.isSketchList = false;
}

var session = {};
session.editor = {};
session.editors = {};
session.isPlaying = false;
session.isFullscreen = false;
session.isShareOptions = false;
session.isSketchList = false;
session.isSettings = false;
session.share = false;
var focusEd = -1;
var edCount = 0;
var W = 0;
var H = 0;
var editorWidth = 0;
var editorLeft = 150;

$(document).ready(function() {
    W = $(document).width();
    H = $(document).height();
    editorWidth = (2*$(document).width()/5);

    $("#sketches").css('height', H);

    var lbWidth = Math.min(Math.round(0.30*W), 400);

    var emptyWidth = W - (2 * lbWidth);

    $('.listbox').css('width', lbWidth+'px');
    $('.listbox').css('height', Math.round(H-100)+'px' );

    $('#sketchbook').css('top', '50px');
    $('#sketchbook').css('left', (emptyWidth/4)+'px');
    $('#gallery').css('top', '50px');
    $('#gallery').css('left', (W/2 + emptyWidth/4)+'px');


    $('#login').click(function() {
        if(session.editor.isDirty) {
            var proceed = confirm(
                'Unsaved code in editor. Save it before logging in.'+
                ' Proceed anyway?');
            if(!proceed) return;
        }
        window.location = LOGIN_URL;
    });

    $('#logout').click(function() {
        if(session.editor.isDirty) {
            var proceed = confirm(
                'Unsaved code in editor. Save it before logging out.'+
                ' Proceed anyway?');
            if(!proceed) return;
        }
        window.location = LOGIN_URL;
    });

    $("#new").click(function() {
        if(session.editor.isDirty) {
            var proceed = confirm('Unsaved code in editor.'+
                        ' Proceed anyway?');
            if(!proceed) return;
        }
        loadCode('',undefined, undefined, false, true);
    });
    $("#config").click(function() {
        $('#settings #message').css('top',(($(document).height()-200)/2)+'px');
        $('#settings #message').css('left',(($(document).width()-300)/2)+'px');
        $("#settings").fadeIn();
        session.isSettings = true;
    });

    $("#open").click(function() {
        $("#sketches").fadeIn();
        session.isSketchList = true;

        $.post('/_ajax/sketch', { op : 'list', scope : 'public' },
                function(data) {
                    var response = $.parseJSON(data);
                    if(response.result != 'SUCCESS') return;

                    var list = response.list;
                    $('#gallery').empty();
                    $('#gallery').append('<p>Gallery</p>');

                    $('#gallery').append('<div id="scroller"></div>');
                    $('#gallery #scroller').append('<div id="items"></div>');
                    for(var i=0; i < list.length; i++) {
                        $("#gallery #scroller #items").append(
                            '<ul class="name" id="'+list[i].uid+'">'+
                            list[i].name+'</ul>'+
                            '<ul class="author">'+
                            list[i].authorname.split('@')[0]+'</ul>');
                    }
                    $('#gallery #scroller').css('width',
                        $('#gallery').css('width'));
                    $('#gallery #scroller').css('height',
                        $('#gallery').css('height'));
                    $('#gallery .name').css('width',
                        $('#gallery').css('width'));
                    $('#gallery .author').css('width',
                        $('#gallery').css('width'));

                    $("#gallery #scroller").scrollable({
                        vertical:true, size: 1 }).mousewheel();

                    $("#gallery ul").click(function() {
                        $.post('/_ajax/sketch',
                            { op:'open', scope:'public', 
                            uid : $(this).attr('id') },
                            function(data) {
                                var response = $.parseJSON(data);
                                if(response.result == 'NOT_FOUND') {
                                    alert(data); 
                                    return;
                                }
                                if(session.editor.isDirty) {
                                    var overwrite = 
                                        confirm('Unsaved code in editor.'+
                                                ' Proceed anyway?');
                                    if(!overwrite) return;
                                }
                                if(response.code == undefined) {
                                } else {
                                    loadCode(response.code, 
                                        response.name, response.uid, false, false);
                                }
                                exitSketchList();
                            });
                    });
                });

        $.post('/_ajax/sketch', { op : 'list', scope : 'user' },
                function(data) {
                    var response = $.parseJSON(data);
                    if(response.result != 'SUCCESS') return;

                    var list = response.list;

                    $('#sketchbook').empty();
                    $('#sketchbook').append('<p>My Sketchbook</p>');
                    $('#sketchbook').append('<div id="scroller"></div>');
                    $('#sketchbook #scroller')
                        .append('<div id="items"></div>');
                    for(var i=0; i < list.length; i++) {
                        $("#sketchbook #scroller #items").append(
                            '<ul class="mysketchname" id="'+list[i].uid+'">'+
                            list[i].name+
                            '<ul class="sketchdelete" id="'+list[i].uid+
                            '"></ul></ul>');
                    }
                    $('#sketchbook #scroller').css('width',
                        $('#sketchbook').css('width'));
                    $('#sketchbook #scroller').css('height',
                        $('#sketchbook').css('height'));
                    $('#sketchbook .mysketchname').css('width',
                        $('#sketchbook').css('width'));

                    $("#sketchbook #scroller").scrollable({
                        vertical:true, size: 1 }).mousewheel();

                    $("#sketchbook .mysketchname").click(function() {
                        $.post('/_ajax/sketch',
                            { op:'open', scope:'user', 
                            uid : $(this).attr('id') },
                            function(data) {
                                var response = $.parseJSON(data);
                                if(response.result == 'NOT_FOUND') {
                                    alert(data); 
                                    return;
                                }
                                if(session.editor.isDirty) {
                                    var overwrite = 
                                        confirm('Unsaved code in editor.'+
                                                ' Proceed anyway?');
                                    if(!overwrite) return;
                                }
                                loadCode(response.code, 
                                    response.name, response.uid, 
                                    response.share, true);
                                exitSketchList();
                            }
                        );
                    });
                    $("#sketchbook .sketchdelete").click(function() {
                        var deleteit = confirm('Delete Sketch?');
                        if(deleteit) {
                            $.post('/_ajax/sketch',
                                { op:'delete', scope:'user', 
                                uid : $(this).attr('id') },
                                function(data) {
                                    var response = $.parseJSON(data);
                                    if(response.result != 'SUCCESS') {
                                        alert(response.result);
                                        return;
                                    } else {
                                        exitSketchList();
                                    }
                                });
                        }
                        return false;
                    });
                });
    });

    $('#source').val(sampleCode);

    $("#editor").css('width', editorWidth+'px');
    $("#editor #title").css('width', editorWidth+'px');
    $("#editor #title").text('Untitled');
    session.editor.mirror =
        CodeMirror.fromTextArea('source', {
            height : $(document).height() - 45,
            parserfile: ["tokenizejavascript.min.js","parsejavascript.min.js"],
            stylesheet: "_css/cm/jscolors.css",
            path: "_scripts/cm/",
            continuousScanning: 500,
            onChange : dirtyEditor,
            lineNumbers: true
        });
    $('#editor').fadeIn();

    $('#editpanel #runButton').click(runCode);
    $('#editpanel #saveButton').click(saveCode);
    $('#editpanel #shareButton').click(showShareSettings);

    $('#fullscreenButton').click(function() {
            if(session.isFullscreen) {
                $('#fullscreenButton').css('background-image',
                    'url(/_images/fullscr_off.png)')
                session.isFullscreen = false;
            } else {
                $('#fullscreenButton').css('background-image',
                    'url(/_images/fullscr_on.png)')
                session.isFullscreen = true;
            }
        });

    $(document).bind('keydown', 'esc', 
        function() { 
            if(session.isPlaying && session.isFullscreen) {

                $('#fsplayer').fadeOut(function() { 
                    $("#display").remove(); 
                    session.isPlaying = false;
                });

                return;
            }

            if(session.isSketchList) {
                exitSketchList();
                return;
            }
            if(session.isShareOptions) {
                hideShareSettings();
                return;
            }

            if(session.isSettings) {
                $('#settings').fadeOut();
                session.isSettings = false;
                return;
            }
        });

    var adimgHeight = parseInt($('#amimg').attr('height'));
    $('#amazon').css('top', (H-adimgHeight-15)+'px');
    $('#amazon').css('left', '15px');
    $('#amazon').fadeIn();

});

