﻿var _host,_wpfeControl;
var _templateItems;
var _animationDuration = "0:0:0.3";
var _pageMargin = 10;

// =====================================================================
// Initial Page Load
// =====================================================================
function Root_Loaded(sender, args)
{
    _host = sender.getHost();
    _wpfeControl = document.getElementById('wpfeControl1');
    _templateItems = sender.findName("TemplateItems");
    LoadItems();
}
// =====================================================================
// Clear all the items currently displayed and then fire off a request
// for a fresh set of items
// =====================================================================
function resetTemplateItems()
{
    _templateItems.children.clear();
    LoadItems();
}
// =====================================================================
// Add an additional batch of items to the displayed list
// =====================================================================
function moreTemplateItems()
{
    LoadItems();
}
// =====================================================================
// Fire off an ajax request to get a batch of items with the specified template
// =====================================================================
function LoadItems()
{
    PageMethods.GetItems(_templateItems.children.count,GetItems_Completed);
}
// =====================================================================
// Handle the completion of the PageMethods.GetItems call
// Add all the items to the _templateItems placeholder, and then fire off
// the downloader request for each image
// =====================================================================
function GetItems_Completed(args)
{
    var items = args[0];
    var images = args[1];
    for(i=0;i<items.length;i++)
    {
        var ctrl = _host.CreateFromXaml(items[i]);
        _templateItems.children.add(ctrl);
        SetAnimationDuration(_templateItems.findName(ctrl.name + "DoItemReposition"));
    }
    var sliderButton = _host.findName("sliderButton");
    ResizeTemplateItems(sliderButton["Canvas.Left"]);
    
    for(i=0;i<images.length;i++)
    {
        var downloader = _host.createObject("downloader");
        downloader.completed = "javascript:ItemImageDownload_Completed";
        downloader.open("GET","Image.ashx?url=" + images[i],true);
        downloader.send();
    }
}
// =====================================================================
// When the item image has completed downloading, then set the source of
// the next item that has no source
// =====================================================================
function ItemImageDownload_Completed(sender)
{
    for(i=0;i<_templateItems.children.count;i++)
    {
        var img = _host.findName(i+"Image");
        if( !img.Source )
        {
            img.setSource(sender);
            return;
        }
    }
}
// =====================================================================
// Generic function to set the duration of a specified animation
// this enables you to dynamically change the animation duration
// =====================================================================
function SetAnimationDuration(storyBoard,shouldBegin)
{
    if( !storyBoard ) return;
    for(var j=0;j<storyBoard.children.count;j++)
    {
        var anim = storyBoard.children.getItem(j);
        anim.duration = _animationDuration;
    }
    if( shouldBegin )
        storyBoard.begin();
}
// =====================================================================
// Handle the slider Mouse Down Event
// =====================================================================
var isMouseDown = false;
var beginX;
function Slider_MouseLeftButtonDown(sender, args)
{
    // Set the beginning position of the mouse.
    beginX = args.x;
    
    isMouseDown = true;
    sender.captureMouse();
}
// =====================================================================
// Handle the slider Mouse Up event
// =====================================================================
function Slider_MouseLeftButtonUp(sender, args)
{
    if( isMouseDown )
    {
        sender.releaseMouseCapture();
        isMouseDown = false;
    }
}
// =====================================================================
// Handle the mouse move event when the slider has been clicked
// =====================================================================
function Slider_MouseMove(sender, args)
{
    if( isMouseDown )
    {
        var sliderLine = sender.findName("sliderLine");
        var sliderButton = sender.findName("sliderButton");
        var leftOffset = sliderLine.getParent()["Canvas.Left"];
        var maxSlide = sliderLine.x2 - sliderButton.width;
        
        if( args.x <= leftOffset )
        {
            sliderButton["Canvas.Left"] = 0;
            ResizeTemplateItems(0);
            return;
        }
        if( args.x >= leftOffset + maxSlide )
        {
            sliderButton["Canvas.Left"] = maxSlide;
            ResizeTemplateItems(maxSlide);
            return;
        }
        
        // Retrieve the current position of the mouse.
        var delta = args.x - beginX;
        var sliderLeft = sliderButton["Canvas.Left"];
        if( sliderLeft + delta < 0 ) delta = sliderLeft * -1;
        if( sliderLeft + delta > maxSlide ) delta = maxSlide - sliderLeft;
        if(    (sliderLeft > 0 && sliderLeft < maxSlide) 
            || (sliderLeft <= 0 && delta > 0)
            || (sliderLeft >= maxSlide && delta < 0))
                sliderButton["Canvas.Left"] += delta;
            
        // Update the beginning position of the mouse.
        beginX = args.x;
        
        ResizeTemplateItems(sliderButton["Canvas.Left"]);
    }
}
// =====================================================================
// When the slider is moved, resize all the template items based on the
// new scale.  Then call FlowReposition to determine if any items should
// be moved to a different row
// =====================================================================
function ResizeTemplateItems(newScale)
{
    for(i=0;i<_templateItems.Children.count;i++)
    {
        var item = _templateItems.Children.getItem(i);
        var scale = item.findName(item.name+"Scale");
        scale.scaleX = scale.scaleY = (newScale+50)/100;
    }
    FlowRepostion();
}
// =====================================================================
// Based on the width of the template items, and how wide the page is, 
// reposition any items to the next line if they won't fit in the current view
// =====================================================================
function FlowRepostion()
{
    var _topPadding = 60
    var canvasLeft = 0;
    var canvasTop = _topPadding;
    var borderWidth = 0;
    var borderHeight = 0;
    var padding = 10;
    
    for(i=0;i<_templateItems.Children.count;i++)
    {
        var item = _templateItems.Children.getItem(i);
        if( i==0 )
        {
            var border = item.findName(item.name+"Border");
            var scale = item.findName(item.name+"Scale");
            borderHeight = border.height*scale.scaleX;
            borderWidth = border.width*scale.scaleX;
        }
        if( canvasLeft + borderWidth + padding > _host.actualWidth )
        {
            canvasTop += borderHeight+padding;
            canvasLeft = 0;
        }
        var DoItemReposition = item.findName(item.name + 'DoItemReposition');
        var RepositionLeft = item.findName(item.name + 'RepositionLeft');
        var RepositionTop = item.findName(item.name + 'RepositionTop');
        RepositionLeft.from = item['Canvas.Left'];
        RepositionTop.from = item['Canvas.Top'];
        RepositionLeft.to = canvasLeft;
        RepositionTop.to = canvasTop;
        DoItemReposition.begin();
        
        canvasLeft += borderWidth+padding;
    }
    _wpfeControl.height = Math.max(document.documentElement.offsetHeight, canvasTop+borderHeight+_pageMargin );
}
// =====================================================================
// Catch the window resize event and move the template items if necessary
// =====================================================================
window.onresize = Resize;
function Resize()
{
    //when maximizing in IE, the resize event fires before the actual resize
    //by setting the timeout, maximize and restore works
    setTimeout('FlowRepostion();',1);
}
