var slPlugin;
var photos;
var thumbsize = 75;
var zoomsize = 245;

function CanvasLoaded(sender, args) {
    slPlugin = sender.getHost();
    slPlugin.content.onResize = Resized;
    
    PageMethods.GetPhotosInSet("72057594140080132", DownloadedList);
}

function DownloadedList(data, context) {
    photos = data;
    Resized(null, null);
}

function Resized(sender, args) {

    if(!photos) return;
    
    width = slPlugin.content.ActualWidth;
    cols = Math.floor((width - zoomsize + thumbsize) / thumbsize);
    document.getElementById('SilverlightPlugIn').height = 
        Math.floor(photos.length / cols * thumbsize + zoomsize);

    DrawImages();
}

var imgXaml = '<Image xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" MouseEnter="imageMouseEnter" ' +
    ' MouseLeave="imageMouseLeave" Height="140" Width="140" Stretch="UniformToFill" ' + 
    ' MouseLeftButtonDown="imageClick"';
    
function DrawImages() {
    
    var width = slPlugin.content.ActualWidth;
    var cols = Math.floor((width - zoomsize + thumbsize) / thumbsize);
    var height = slPlugin.content.ActualHeight;

    var Body = slPlugin.content.findName("Body");
    Body.children.Clear();
    
    for(i = 0; i < photos.length; i++) {
        _left = i % cols * thumbsize;
        _top = Math.floor(i / cols) * thumbsize;

        var img = slPlugin.content.createFromXaml(imgXaml + ' x:Name="' + photos[i].SmallUrl + '" />');
        img.Source = photos[i].SmallUrl;
        img.Tag = photos[i].FlickrUrl;
        img["Canvas.Top"] = _top;
        img["Canvas.Left"] = _left;
        Body.children.Add(img);       
    }
}

function imageMouseEnter(sender, args) {
    ani = sender.findName("ImageGrow");
    ani.stop();
    ani["Storyboard.TargetName"] = sender.Name;
    sender["Canvas.ZIndex"] = 1;
    ani.begin();
}

function imageMouseLeave(sender, args) {
    ani = sender.findName("ImageShrink");
    ani.stop();
    ani["Storyboard.TargetName"] = sender.Name;
    sender["Canvas.ZIndex"] = 0;
    ani.begin();
}

function imageClick(sender, args) {
    location.href = sender.Tag;
}