var _pdfView = null;
var _token2;
var _ptf = null;
var _downloader = null;
var _canvasWidth = 526;
var _defaultScale = "0.65"  // scaling factor to make sure all objects fit into the page
 
function createSilverlight()
{
	    Silverlight.createObjectEx({
		source: 'amyuni.xaml',
		parentElement: document.getElementById('SilverlightPlugInHost'),
		id: 'SilverlightPlugIn',
		properties: {
			width: '1058',
			height: '100%',
			background:'white',
            isWindowless: 'false',
			version: '1.0'
		},
		events: {
			onLoad: onPageLoad
		},		
		context: null 
	});
	
	_pdfView = document.getElementById( 'SilverlightPlugIn' );
	_canvasWidth = _pdfView.width / 2;
}

function onPageLoad(control, context, root)
{
    // Instantiate the downloader object and store a reference for later use
    _downloader = _pdfView.createObject('downloader');
    
    // Add an event listener to detect when data is available
    _token2 = _downloader.addEventListener('completed', downloadCompleted);

    // Request a PDF document from the Server
    // The Amyuni PDF Creator will be used on the server to load the PDF
    // and return it in a ZIP package similar in format to XPS
    _downloader.open('GET', '/PageTurnPdf/pdf.asp?PDFFile=doc.pdf');

    // Begin asynchronous download of the zip package
    _downloader.send();
}

function ProcessElements(elems)
{
// process all page elements to set:
//  - the source of all image elements
//  - the font of all text elements
// the try/catch blocks are needed because we do not know
// in advance if a specific attribute exists for an object
//
    if ( elems == null )
        return;
    for ( i = 0; i < elems.Count; i++ )
    {
        var elem = elems.getItem(i);
        try
        {
            // set the font source for all text elements to fonts retrieved from the ZIP package
            if ( elem.toString() == "TextBlock" )
            {
                elem.setFontSource( _downloader );
                elem.SetValue( "Canvas.Left", elem.GetValue( "Canvas.Left" ) * _defaultScale );
                elem.SetValue( "Canvas.Top", elem.GetValue( "Canvas.Top" ) * _defaultScale );
            }
            // scale down the objects to make two pages fit
            // this could have been done at the parent Canvas level, but the page-turn framework does not support it
            // Modified for SL2 Beta elem.RenderTransform = _pdfView.content.CreateFromXaml('<' + elem.toString() + '.RenderTransform><ScaleTransform ScaleX="' + _defaultScale + '" ScaleY="' + _defaultScale + '" /></' + elem.toString() + '.RenderTransform>');
	    elem.RenderTransform = _pdfView.content.CreateFromXaml('<ScaleTransform ScaleX="' + _defaultScale + '" ScaleY="' + _defaultScale + '" />');
        }
        catch(e)
        {
        }

        try
        {
            // in this case, the element has an attribute named ImageSource which we need to change
            var src = elem.ImageSource;
            if ( src != null && src != "" )
            {
                // set the source after removing the leading slash
                elem.Fill.setSource(_downloader, src.substring(1));
            }
        }
        catch(e)
        {
        }

        try
        {
            // in this case, the element has a fill brush which is itself an ImageSource
            var src = elem.Fill.ImageSource;
            if ( src != null && src != "" )
            {
                // set the source after removing the leading slash
                elem.Fill.setSource(_downloader, src.substring(1));
            }
        }
        catch(e)
        {
        }

        // loop recursively through all children of the current element
        try
        {
            ProcessElements(elem.children);
        }
        catch(e)
        {
        }
    }
}

function downloadCompleted(sender, args)
{
    // Instantiate the page-turn framework
    _ptf = new PageTurnFramework(_pdfView, _pdfView.content.findName('PageTurnCanvas'));
    
    // Retrieve the XAML description of the document from the downloaded package file
    // Create an empty document with N pages and pass it to the page_turn framework
    // the content of pages is loaded on demand when the framework requests a new page
    // to count the number of pages in the document, we are searching for the last page
    // index in the document description oject
    var Document = sender.getResponseText('Document/document_1.fdoc');
    var start = -1;
    var pages = 1;
    while ( true )
    {
        start = Document.indexOf( "Page" + pages, start + 1 );
        if ( start == -1 )
            break;
        else
            pages++;
    }
    
    // now create N empty pages (N should be even)
    for ( page = 0; page < ((pages+1) / 2); page++ )
    {
        // create empty left and right page
        var emptyCanvas = '<Canvas Background="Gray" Width="' + _canvasWidth + '" Height="816" xmlns="http://schemas.microsoft.com/client/2007" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"/>'
        // scale down the page to make two pages fit
        var LeftPageObj = sender.getHost().content.createFromXaml(emptyCanvas);
        _pdfView.content.root.children.insert(page*2+1, LeftPageObj);
        var RightPageObj = sender.getHost().content.createFromXaml(emptyCanvas);
        RightPageObj.SetValue("Canvas.Left", _canvasWidth);
        _pdfView.content.root.children.insert(page*2+2, RightPageObj);
            
        // Add Left and Right pages to the framework
        _ptf.addPage(LeftPageObj, RightPageObj);
    }
            
    // Initialize the framework
    _ptf.initializeFramework();
    
    // Deregister downloader event handlers
    sender.removeEventListener('completed', _token2);
}

function loadVisiblePages()
{
    // make sure all needed pages are loaded into the control
    // starting with the first visible page, load the 4 consecutive pages
    // this function is called by the page-turn framework each time the user
    // switches pages
    var page = _ptf.getCurrentPageIndex() * 2;
    try
    {
        for ( n = 0 ; n < 4; n++ )
        {
            if ( page + n == 0 )
                continue;       // this is the very first page which is left empty on purpose
                
            // check if this page has been loaded by searching for the object named PageN
            if ( _pdfView.content.findName("Page" + (page+n)) )
                continue;       // page already loaded
                
            // now load the page
            var Xaml = _downloader.getResponseText('Pages/page_' + (page+n) + '.fpage');
            
            // Create the objects from the XAML content.
            var PageTurnObj = _pdfView.content.createFromXaml(Xaml);

            PageTurnObj.Width = _canvasWidth;
            PageTurnObj.Background = "White";

            // process all the elements of the page
            ProcessElements(PageTurnObj.children);

            // Add downloaded XAML content to the root Canvas of the plug-in.
            // first remove the existing empty page
            _pdfView.content.root.children.insert(page + n, PageTurnObj);
            _pdfView.content.root.children.removeAt(page + n + 1);
                
            // Replace empty page N in the framework by the page we just loaded
            if ( n % 2 == 1 )
            {
                PageTurnObj.SetValue("Canvas.Left", PageTurnObj.Width);
                _ptf.setRightPage( PageTurnObj, (page+n-1)/2 );
            }
            else
            {
                _ptf.setLeftPage( PageTurnObj, (page+n)/2 );
            }
       }
   }
   catch( e )
   {
       // end of document
   }
}

function dispose()
{
    // Call framework's dispose method for proper cleanup
    if (_ptf != null)
        _ptf.dispose();
}
