//
// Drawing library
//
function paintCanvas(drawid) {
    var canvasWidth  = 0;
    var canvasHeight = 0;
    var scaleX       = 1.0;
    var scaleY       = 1.0;
    var scaleP       = 1.0;

    function nxCB(actions, ctx, idx, delay, doneCB) { 
        var a = actions;
        var i = idx;
        var cb = doneCB;
        return (function() { step(a, ctx, i, delay, cb); });
    }

    function step(actions, ctx, idx, delay, doneCB) {
        if (idx >= actions.length) {
            if (doneCB) 
                doneCB();
            return;
        }

        var nextCB = function() { step(actions, ctx, idx+1, delay, doneCB); };

        var obj = actions[idx];
        if (obj) {
            if (obj.type == 'canvas') {
                scaleX = canvasWidth  / obj.width;
                scaleY = canvasHeight / obj.height;
                scaleP = scaleX < scaleY ? scaleX : scaleY;
            } else if (obj.type == 'line') {
                ctx.lineCap   = 'round';
                ctx.lineJoin  = 'round';
                ctx.lineWidth = obj.width * scaleP;
                ctx.strokeStyle = 'rgba(' + [obj.rgba[0], obj.rgba[1], obj.rgba[2], obj.rgba[3] / 255.0 ].join(',') + ')';
                ctx.beginPath();
                for (var i = 0; i < obj.points.length; i++) {
                    p = obj.points[i];
                    if (i == 0) {
                        ctx.moveTo(p[0] * scaleX, p[1] * scaleY);
                    } else {
                        ctx.lineTo(p[0] * scaleX, p[1] * scaleY);
                    }
                }
                ctx.stroke();
            } else if (obj.type == 'layer') {
                step(obj.actions, ctx, 0, delay, nextCB);
                return;
            } else if (obj.type == 'image') {
                var image = new Image();
                image.onload = function() {
                    var x = obj.point[0] || 0;
                    var y = obj.point[1] || 0;
                    var w = image.width * obj.scale[0];
                    var h = image.height * obj.scale[1];
                    ctx.drawImage(image, x, y, w, h);
                    nextCB();
                }
                image.src = '/i/100000_'+obj.imageid+'_O.jpg';
                return;
            } else if (obj.type == 'text') {
                if (ctx.fillText) {
                    ctx.font = obj.slant + " " + obj.weight + " " + obj.size + "px " + obj.face;
                    ctx.fillStyle   = 'rgba(' + [obj.rgba[0], obj.rgba[1], obj.rgba[2], obj.rgba[3] / 255.0 ].join(',') + ')';
                    ctx.fillText(obj.text, obj.point[0] * scaleX, obj.point[1] * scaleY);
                }
            } else {
                alert("UNKNOWN: " + obj.type);
            }
        }

        setTimeout(nextCB, delay)
    }

    function draw(actions) {
      var canvas = document.getElementById("canvas");
      if (canvas && canvas.getContext) {
        canvasWidth  = canvas.width;
        canvasHeight = canvas.height;
        var ctx = canvas.getContext("2d");
        if (actions.length > 1000) {
            delay = (60 * 1000) / actions.length;
        } else {
            delay = 100;
        }

        step(actions, ctx, 0, delay, null);
      }
    }

    if (document.getElementById("canvas")) {
        $.getJSON('/api/json/drawing.drawing?drawid=' + drawid, function(response) {
            draw(response.drawing);
        });
    }
}

//
//  Page rendering...
//
var readyfuncs = {
    '#sketch_canvas' : function() {
        var drawing_id = $('.drawingid').get(0).id;

        $('#likebutton').click(function() {
            var button = this;
            url = '/api/json/drawing.like?drawid='+ drawing_id +'&likes=' + ($(this).hasClass('likes') ? '0' : '1');

            $.getJSON(url, function(response) {
                if (response.code != 200) {
                    alert('Error: ' + response.error);
                } else {
                    if (response.likes) {
                        $(button).addClass('likes');
                        $(button).text('unFavorite');
                    } else {
                        $(button).removeClass('likes');
                        $(button).text('Favorite');
                    }
                }
            });

            return false;
        });

        $('#setbackground').click(function() {
            url = '/api/json/profile.setbackground?drawid='+ drawing_id;

            $.getJSON(url, function(response) {
                if (response.code != 200) {
                    alert('Error: ' + response.error);
                } else {
                    Boxy.alert("Is now your background.");
                }
            });

            return false;
        });

        $('#setpicture').click(function() {
            url = '/api/json/profile.setpicture?drawid='+ drawing_id;

            $.getJSON(url, function(response) {
                if (response.code != 200) {
                    alert('Error: ' + response.error);
                } else {
                    Boxy.alert("Your picture has been updated.");
                }
            });

            return false;
        });

        $('#addart').click(function() {
            url = '/api/json/drawing.addart?drawid='+ drawing_id;

            $.getJSON(url, function(response) {
                if (response.code != 200) {
                    alert('Error: ' + response.error);
                } else {
                    Boxy.alert("Added to your library");
                }
            });

            return false;
        });

        if ($('body').hasClass('auth')) {
            $('#ratethis').stars({
                cancelShow: false,
                callback: function(ui, type, value) {
                    $.getJSON('/api/json/drawing.rate?drawid='+ drawing_id +'&rating=' + value, function(response) {
                        if (response.code != 200) {
                            alert('Error: ' + response.error);
                        }
                    });
                }
            }); 
        } else {
            $('#ratethis').stars({
                cancelShow: false,
                disabled: true,
                callback: function(ui, type, value) {
                    $.getJSON('/api/json/drawing.rate?drawid='+ drawing_id +'&rating=' + value, function(response) {
                        if (response.code != 200) {
                            alert('Error: ' + response.error);
                        }
                    });
                }
            }); 
            $('#rategroup').hover(
                function() {
                    $('#ratingpromo').show();
                    $('#ratingcount').hide();
                }, function() {
                    $('#ratingpromo').hide();
                    $('#ratingcount').show();
                }
            );
        }

        $('#commentform').submit(function() {
            var body = $('#commentbody').val();
            var data = { 'drawid' : drawing_id, 'body' : body }

            $.post('/api/json/drawing.comment', data, function(response) {
                $('#comments').append(response.html);
            }, 'json');

            return false;
        });

        $('#sendfriend').boxy({title:'Send to a Friend'});
        $('#sendfriendform').submit(function() {
            var data = { 'drawid' : drawing_id, 'recpt' : $('#id_to').val(), 'message' : $('#id_message').val() }

            $.post('/api/json/drawing.share', data, function(response) {
                var l = $('#sendfriendform').get(0);
                alert('sent');
                Boxy.get(l).hide();
            }, 'json');
            return false;
        });

        paintCanvas(drawing_id);
    },
    '#photos_list' : function() {
        $(".drawing .remove").click(function(event) {
            var title = $(this).parents(".drawing").children("h3").text();
            var photoid = event.target.href.split('#')[1];
            Boxy.confirm("Are you sure you want to delete this photo<br/><b>&nbsp;&nbsp;"+title+"</b>", function() {
                            $.getJSON('/api/json/photos.delete', { 'photoid' : photoid }, function(response) {
                                window.location.reload();
                            });
                        }, {
                            title : 'Delete photo',
                            closeable: true
                        });
            return false;
        })
    },
    '#friends_list' : function() {
        var menu;

        function openMenu(obj) {
            $(obj).addClass("hovering");
            menu = obj;
        }

        function closeMenu(obj) {
            if (obj)
                $(obj).removeClass("hovering");
            menu = null;
        }

        function wireEvents() {
                var megaConfig = {
                    interval: 500,
                    sensitivity: 4,
                    timeout: 500,
                    /* over: function() { $(this).each(function() { openMenu(this); }); }, */
                    over: function() { openMenu(this); },
                    out: function() { $(this).each(function() { closeMenu(this); }); }
                };

                $(".menu").hoverIntent(megaConfig)
                $(".menu a.title").click(function(event) { 
                    closeMenu(menu);
                    openMenu($(event.target).parents(".menu"));
                    return false;
                })

                $(".friend_lists a.item").click(changeMembership);
        }

        function changeMembership(event) {
            var data = event.target.href.split('#')[1];

            var p = data.split(';')

            var url;
            if (p[0] == 'a') {
                url = '/api/json/friends.add';
            } else {
                url = '/api/json/friends.remove';
            }

            $.getJSON(url, { name: p[2], user: p[1] }, function(response) {
                $(event.target).parents(".friend_person").replaceWith(response.html);
                wireEvents();
            });

            closeMenu(menu);
            
            return false;
        };

        function getList(name) {
            $.getJSON('/api/json/friends.list', { name: name }, function(response) {
                if (response.html) {
                    $('#friend_listing').html(response.html);
                } else {
                    alert(response.error);
                }
                wireEvents();
            });
        };

        getList("");

        var box;

        $("#list_create").click(function() {
            if (box) {
                box.show();
            } else {
                box = new Boxy($("#create_form_container"), {
                                title: "Create new list",
                                closeable: true,
                                modal: true
                            });
            }
            return false;
        });

        $("#create_form").submit(function(event) {
            var name = $("#id_listname").val();
            $.getJSON('/api/json/friends.list.create', { name: name }, function(response) {
                $("#id_listname").val("");
                box.hide();
            });
            return false;
        });

        $("#listname_cancel").click(function () {
            box.hide();
            return false;
        });

        $(".list_filter").click(function (event) {
            /*
            var name = $(event.target).get().href;
            var name = event.target.href;
            */
            var name = event.target.href.split('#')[1];

            getList(name);
            
            return false;
        });
    }
}

function pageReadyHandler(id, cname) {
    if ($('.fade').length != 0) {
        setTimeout(function() {
            $('.fade').fadeOut();
        }, 3000);
    }
    readyfuncs['#' + id] && readyfuncs['#' + id]();
}
