﻿//===============================================================================
// ID		  : $Id: Codex.js 194 2008-05-06 06:20:49Z stefan.schult $
// Author     : $Author: stefan.schult $
// Description: Codex MainJs
//===============================================================================

if (!window.Codex)
	window.Codex = {};

Codex.Page = function() 
{
}

Codex.Page.prototype =
{
	toString: function() 
	{
		return "Codex.Page";
	},
	handleLoad: function(plugIn, userContext, rootElement) 
	{
		this.plugIn			= plugIn;
		this.rootElement	= rootElement;
		this.atStart		= true;
		this.PackageZip		= null;
		this.isSplashScreenWaiting = true;
		this.isLoading		= true;
		this.pluginResize	= new PluginResize(rootElement);
		this.pluginResize.add(rootElement, Silverlight.createDelegate(this, this.updateScreenLayout));
		this.isFullscreen = false;
		this.scanDraggingEnabled = false;
		this.defaultLanguage = "de";
		this.transcriptionFont = null;
		this.Language = this.getLanguage();
		this.InterfaceLanguage = new InterfaceLanguage(rootElement);
		this.InterfaceLanguage.update(this.Language);
		var textButtonStartApp = rootElement.findName("textButtonStartApp");
		textButtonStartApp["Canvas.Left"] = (textButtonStartApp.getParent().Width-textButtonStartApp.ActualWidth)/2;
		var textButtonProjectInfo = rootElement.findName("textButtonProjectInfo");
		textButtonProjectInfo["Canvas.Left"] = (textButtonProjectInfo.getParent().Width-textButtonProjectInfo.ActualWidth)/2;

 		
		this.hasNavBandOfPagesAnimation = null;
		this.NavBandItem = {
			Width : 310,
			Height : 344,
			ScaleFactor: 698,
			MarginX: 15
		}
		//rootElement.findName("AppLoadingAnimation").begin();alert('')
		
		// Sample event hookup:	
        this.ScrollbarsTextBox = new Scrollbars(rootElement);
		this.ScrollbarsTextBox.add(rootElement.findName("TextScrollerBox"), 'V');
		this.ScaleScan = new ScaleScan(rootElement.findName("ScaleControl"), rootElement.findName("ScanCanvasScaleTransform"), rootElement.findName("ZoomScanAnimation"));

        this.ScrollbarsDropDown = new Scrollbars(rootElement);
		SplashSreen = rootElement.findName("SplashScreen");
//		SplashSreen.addEventListener("MouseLeftButtonUp", Silverlight.createDelegate(this, this.handleSkipSplashSreen));
		
		rootElement.addEventListener("KeyUp", Silverlight.createDelegate(this, this.onKeyUp));
		rootElement.findName("ButtonFlyOutScanInfo").addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.handleFlyOutScanInfo));
		rootElement.findName("ButtonFullscreen").addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.onButtonFullscreenMouseLeftButtonUp));
		rootElement.findName("ButtonSkipLeft").addEventListener("MouseLeftButtonUp", Silverlight.createDelegate(this, this.handleButtonSkip));
		rootElement.findName("ButtonSkipRight").addEventListener("MouseLeftButtonUp", Silverlight.createDelegate(this, this.handleButtonSkip));
		rootElement.findName("ButtonGetTOC").addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.onButtonGetTOCMouseLeftButtonDown));
		rootElement.findName("ScanOrigin").addEventListener("Loaded", Silverlight.createDelegate(this, this.handleScanLoaded));
		rootElement.findName("FlyInScanInfoAnimation").addEventListener("Completed", Silverlight.createDelegate(this, this.handleFlyInScanInfoAnimationCompleted));
		rootElement.findName("ButtonBookSelectionLeft").addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.handleButtonBookSelectionMouseLeftDown));
		rootElement.findName("ButtonBookSelectionRight").addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.handleButtonBookSelectionMouseLeftDown));
		
		this.SkipButtons = {
			ButtonSkipLeft : new SkipButton(rootElement.findName("ButtonSkipLeft")),
			ButtonSkipRight : new SkipButton(rootElement.findName("ButtonSkipRight"))
		};
		
		this.BookSelectionButtons = {
			ButtonLeft : new BookSelectionButton(rootElement.findName("ButtonBookSelectionLeft")),
			ButtonRight : new BookSelectionButton(rootElement.findName("ButtonBookSelectionRight"))
		};
		
		this.LinkButtons = {};
		
		this.TaskbarButtons = {};
		this.TaskbarButtons.ButtonZoomArea =		new TaskBarButton(rootElement.findName("ButtonZoomArea"));
		this.TaskbarButtons.ButtonZoomArea.withClickedState = true;
		this.TaskbarButtons.ButtonScanDragging =	new TaskBarButton(rootElement.findName("ButtonScanDragging"));
		this.TaskbarButtons.ButtonScanDragging.withClickedState = true;
		this.TaskbarButtons.ButtonZoom100 =			new TaskBarButton(rootElement.findName("ButtonZoom100"));
		this.TaskbarButtons.ButtonZoom100.addClickEvent(Silverlight.createDelegate(this, this.resetScanOrigin));
		this.TaskbarButtons.ButtonTranscription =	new TaskBarButton(rootElement.findName("ButtonTranscription"));
		this.TaskbarButtons.ButtonTranscription.withClickedState = true;
		this.TaskbarButtons.ButtonTranscription.addClickEvent(Silverlight.createDelegate(this, this.handleTranscriptionBlock));
		this.TaskbarButtons.ButtonTranslation =		new TaskBarButton(rootElement.findName("ButtonTranslation"));
		this.TaskbarButtons.ButtonTranslation.withClickedState = true;
		this.TaskbarButtons.ButtonTranslation.addClickEvent(Silverlight.createDelegate(this, this.handleFlyOutTextbox));
		
		this.ScanDragging = new ScanDragging(rootElement.findName("ScanOrigin"));
		
		this.Lasso = new Lasso(rootElement.findName("LassoArea"), rootElement.findName("LassoArea").Children.GetItem(0))
		this.Lasso.addEvent(Silverlight.createDelegate(this, this.handleZoomArea));

		this.TaskbarButtons.ButtonZoomArea.addClickEvent(Silverlight.createDelegate(this, function(sender, eventArgs){
			this.TaskbarButtons.ButtonScanDragging.cancelClickedState();
			this.Lasso.setVisibility((this.Lasso.getVisibility() == "Collapsed") ? "Visible" : "Collapsed");
			this.ScanDragging.setDraggingEnabled(false);
		}))
		this.TaskbarButtons.ButtonScanDragging.addClickEvent(Silverlight.createDelegate(this, function(sender, eventArgs){
			this.TaskbarButtons.ButtonZoomArea.cancelClickedState();
			this.Lasso.setVisibility("Collapsed");
			this.ScanDragging.setDraggingEnabled(!this.ScanDragging.getDraggingEnabled());
		}))
		
		this.flyOutTextBoxCookie = rootElement.findName("FlyOutTextboxAnimation").AddEventListener("Completed", Silverlight.createDelegate(this, this.completedFlyOutTextbox));
		this.CurrentBook = {
			title : null,
			id: null,
			pages : []
		};
		this.NavBandOfPagesAnimation = this.rootElement.findName("NavBandOfPagesAnimation");
		this.NavBandOfPagesAnimation.AddEventListener("Completed", Silverlight.createDelegate(this, this.completedNavBandOfPagesAnimation));
		this.PageSlider = this.rootElement.findName("PageSlider");
		this.PageSlider.addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.handlePageSliderMouseLeftButtonDown));
		this.PageSlider.addEventListener("MouseLeave", Silverlight.createDelegate(this, this.handlePageSliderMouseLeave));
		this.PageSliderSectors = this.rootElement.findName("PageSliderSectors");
		rootElement.findName("PageSliderInfoAnimation1").addEventListener("Completed", Silverlight.createDelegate(this, this.completedPageSliderInfoAnimation1));
		this.handleNavBandBook(rootElement);
		rootElement.findName("ScrollBookSelectionAnimation").addEventListener("Completed", Silverlight.createDelegate(this, this.completedScrollBookSelectionAnimation));
		
		this.TextMarquees = [];
		this.TextMarquees.push(new MarqueeAtMouseOver(rootElement.findName("OuterScanInfoTitle"), rootElement.findName("ScanInfoTitle")))
		
		var downloader = this.plugIn.createObject("downloader");
		downloader.addEventListener("completed", Silverlight.createDelegate(this, this.onPackageDownloadCompleted));
		downloader.open("GET", "Package.zip");
		downloader.send();

//		var SplashScreenWaiting = rootElement.findName("SplashScreenWaiting");
//		SplashScreenWaiting.addEventListener("completed", Silverlight.createDelegate(this, this.onSplashScreenWaitingCompleted));
//		SplashScreenWaiting.begin();
////		rootElement.findName("DebugBox").addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.debugButton));
	},
	
	debugButton: function(sender, eventArgs)
	{
		this.TranslationBox.updateLayout();
	},
	
	onPackageDownloadCompleted: function(sender, eventArgs)
	{
		this.PackageZip = sender;
		sender.findName("PageImageBrush").setSource(sender, Package.Images.Background);
		sender.findName("SplashScreenImageBrush").setSource(sender, Package.Images.Splash.Band);
		sender.findName("SplashScreen").Children.GetItem(0).Children.GetItem(0).setSource(sender, Package.Images.Splash.Pages);
		sender.findName("SplashScreen").Children.GetItem(0).Children.GetItem(1).setSource(sender, this.Language.SplashScreenText);
		sender.findName("ButtonSkipLeft").Children.GetItem(0).setSource(sender, Package.Images.Icons.SkipButArrowBg0);
		sender.findName("ButtonSkipLeft").Children.GetItem(4).setSource(sender, Package.Images.Icons.SkipButArrowLeft);
		sender.findName("ButtonSkipRight").Children.GetItem(0).setSource(sender, Package.Images.Icons.SkipButArrowBg1);
		sender.findName("ButtonSkipRight").Children.GetItem(4).setSource(sender, Package.Images.Icons.SkipButArrowRight);
		sender.findName("LoadingBarImage").setSource(sender, Package.Images.Loading);
		sender.findName("ButtonZoomArea").Children.GetItem(4).setSource(sender, Package.Images.Icons.ZoomArea);
		sender.findName("ButtonScanDragging").Children.GetItem(4).setSource(sender, Package.Images.Icons.Hand);
		sender.findName("ButtonZoom100").Children.GetItem(4).setSource(sender, Package.Images.Icons.Zoom100);
		sender.findName("ButtonSkipRight").Children.GetItem(4).setSource(sender, Package.Images.Icons.SkipButArrowRight);
		sender.findName("BookSelectionChosen").Children.GetItem(1).setSource(sender, Package.Images.Index.ThumbChosen);
		sender.findName("ButtonBookSelectionLeft").Children.GetItem(0).setSource(sender, Package.Images.Icons.ArrowBookSelection0);
		sender.findName("ButtonBookSelectionLeft").Children.GetItem(1).setSource(sender, Package.Images.Icons.ArrowBookSelection1);
		sender.findName("ButtonBookSelectionRight").Children.GetItem(0).setSource(sender, Package.Images.Icons.ArrowBookSelection2);
		sender.findName("ButtonBookSelectionRight").Children.GetItem(1).setSource(sender, Package.Images.Icons.ArrowBookSelection3);
		sender.findName("ButtonFullscreen").Children.GetItem(0).setSource(sender, Package.Images.Icons.Fullscreen0);
		sender.findName("PageSliderSlider").Children.GetItem(0).setSource(sender, Package.Images.Pageslider);
		sender.findName("Woosh").setSource(sender, Package.Images.Woosh);
		this.onGetTableOfContents();
		
	},
	
	showButtonStartApp: function(sender, eventArgs)
	{
		var ShowButtonStartAppAnimation = sender.findName("ShowButtonStartAppAnimation")
		ShowButtonStartAppAnimation.addEventListener("completed", Silverlight.createDelegate(this, this.onShowButtonStartAppAnimationCompleted));
		ShowButtonStartAppAnimation.begin();
	},
	
	onShowButtonStartAppAnimationCompleted: function(sender, eventArgs)
	{
		this.LinkButtons.ButtonProjectInfo =		new LinkButton(sender.findName("ButtonProjectInfo"), "http://www.ub.uni-leipzig.de/site.php?page=projekte/handschriften/3_1&lang=de&stil=fc");
		this.TaskbarButtons.ButtonStartApp =		new TaskBarButton(sender.findName("ButtonStartApp"));
		this.TaskbarButtons.ButtonStartApp.withClickedState = true;
		this.TaskbarButtons.ButtonStartApp.addClickEvent(Silverlight.createDelegate(this, this.skipSplashScreen));
	},
	
	skipSplashScreen: function(sender)
	{
		this.atStart = false;
		var SplashScreenLoadingCompleted = sender.findName("SplashScreenLoadingCompletedAnimation")
		SplashScreenLoadingCompleted.addEventListener("completed", Silverlight.createDelegate(this, this.onSplashScreenLoadingCompletedAnimationCompleted));
		SplashScreenLoadingCompleted.begin();
	},
	
	onSplashScreenLoadingCompletedAnimationCompleted: function(sender, eventArgs)
	{
		sender.findName("SplashScreen").Visibility = "Collapsed";
		sender.findName("Content").Visibility = "Visible";
	},
	
	handleSkipSplashSreen: function(sender, eventArgs)
	{
		sender.Visibility = "Collapsed";
		sender.findName("Content").Opacity = 1;
		
	},
	
	getLanguage: function(language)
	{
		var hash = window.location.hash;
		if(hash != ""){
			hash = (hash.indexOf("#") != -1) ? hash.substr(1) : hash;
			hashArray = hash.split("=");
			if(hashArray[0] == "lang"){
				var language = hashArray[1];
			}
		}
		if(language){
		} else {
			var language = (navigator.browserLanguage) ? navigator.browserLanguage : navigator.language;
		}
		if(Languages[language]) {
			return Languages[language];
		}else{
			return Languages[this.defaultLanguage];
		}
	},
	
	onGetTableOfContents: function()
	{
		var description = new CodexSinaiticus.ServiceInterface.ContentDescription();
		description.language = this.Language.CurrentLanguage;
	    
		CodexSinaiticus.ServiceImplementation.PageProvider.GetTableOfContents(
			description, 
			Silverlight.createDelegate(this, this.onGetTableOfContentsCompleted),
			null,
			null); 
	},
	
	onGetTableOfContentsCompleted: function(result, context, methodName)
	{
		var FlyoutScrollerInnerBox = this.rootElement.findName("FlyoutScrollerInnerBox");
		var IndexItemXaml = '<Canvas xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="{0}" Width="125" Height="55" Canvas.Left="0" Canvas.Top="0" Background="#00000000">';
			IndexItemXaml+= '<Canvas Visibility="Collapsed">';
				IndexItemXaml+= '<Rectangle Width="125" Height="55" Stroke="#C5000000" StrokeThickness="1" RadiusY="4" RadiusX="4" Fill="#00000000"/>';
				IndexItemXaml+= '<Rectangle Width="123" Height="53" Stroke="#FF8a8a8a" StrokeThickness="1" RadiusY="3" RadiusX="3" Canvas.Left="1" Canvas.Top="1"><Rectangle.Fill><LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"><GradientStop Color="#18000000" Offset="0"/><GradientStop Color="#65000000" Offset="1"/><GradientStop Color="#43000000" Offset="0.78"/></LinearGradientBrush></Rectangle.Fill></Rectangle>';
			IndexItemXaml+= '</Canvas>';
			IndexItemXaml+= '<Image Width="27" Height="44" Canvas.Left="13" Canvas.Top="12" />';
			IndexItemXaml+= '<Canvas x:Name="{0}OuterTitle" Height="15" Width="65" Canvas.Left="50" Canvas.Top="20" Background="#00D4ED1A">';
			IndexItemXaml+= '<Canvas.Clip>';
			IndexItemXaml+= '<RectangleGeometry Rect="0,0,65,15"/>';
			IndexItemXaml+= '</Canvas.Clip>';
			IndexItemXaml+= '<Canvas.RenderTransform><TransformGroup>';
			IndexItemXaml+= '<ScaleTransform x:Name="{0}OuterTitleScaleTransform" ScaleX="1" ScaleY="1"/>';
			IndexItemXaml+= '</TransformGroup></Canvas.RenderTransform>';
			IndexItemXaml+= '<TextBlock x:Name="{0}Title" Text="{1}" FontFamily="Arial" Foreground="#{2}FFFFFF" FontSize="12">';
			IndexItemXaml+= '<TextBlock.RenderTransform><TransformGroup>';
			IndexItemXaml+= '<TranslateTransform x:Name="{0}TitleTranslateTransform" X="0"/>';
			IndexItemXaml+= '</TransformGroup></TextBlock.RenderTransform>';
			IndexItemXaml+= '</TextBlock>';
			IndexItemXaml+= '</Canvas>';
			IndexItemXaml+= '</Canvas>';
		var cols = 7;
		var BookSelectionItems = this.rootElement.findName("BookSelectionItems");
			BookSelectionItems.Children.Clear();
		var firstBookWithPages = null;
	    for(var i = 0; i<result.Books.length; i++){
			var isAvailable = result.Books[i].HasPages && ((AvailableBooks) ? AvailableBooks["B" + result.Books[i].Id] : true);
			var ItemString = String.format(IndexItemXaml, "Book"+result.Books[i].Id, result.Books[i].Title, (isAvailable) ? "FF" : "33");
			var ItemXaml = this.plugIn.content.createFromXaml(ItemString);
			if(isAvailable){
				ItemXaml.addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.handleIndexOfBooksMouseLeftButtonDown));
				if(firstBookWithPages === null) {
					firstBookWithPages = i;
				}
				ItemXaml.addEventListener("MouseEnter", Silverlight.createDelegate(this, this.handleIndexOfBooksMouseEnter));
				ItemXaml.addEventListener("MouseLeave", Silverlight.createDelegate(this, this.handleIndexOfBooksMouseLeave));
				ItemXaml.Children.GetItem(1).setSource(this.PackageZip, Package.Images.Index.Thumb);
			} else {
				ItemXaml.Children.GetItem(1).setSource(this.PackageZip, this.Language.BookNotAvailable);
			}
			ItemXaml.Tag = "({" + String.format("Chapters:'{0}', HasPages:{1}, Id:{2}, Title:'{3}', Index:{4}", result.Books[i].Chapters, (isAvailable) ? 'true': 'false', result.Books[i].Id, result.Books[i].Title, i) + "})";
			ItemXaml["Canvas.Left"] = ItemXaml.Width * i;
			BookSelectionItems.Children.add(ItemXaml);
			this.TextMarquees.push(new MarqueeAtMouseOver(ItemXaml, this.rootElement.findName(ItemXaml.Name + "Title")));
	    }
		var BookSelectionBackground = this.rootElement.findName("BookSelectionBackground");
		for(var i= 0; i < BookSelectionBackground.Children.Count; i++){
			var bgItem = BookSelectionBackground.Children.getItem(i);
			bgItem["Width"] = bgItem.Children.getItem(0)["Width"] = bgItem.Children.getItem(1)["Width"] = bgItem.Children.getItem(2)["Width"] = result.Books.length*ItemXaml["Width"];
		}
//		this.onGetPagesByBook(eval(BookSelectionItems.Children.getItem(9).Tag));
		this.onGetPagesByBook(eval(BookSelectionItems.Children.getItem(firstBookWithPages).Tag));
	},
	
	handleIndexOfBooksMouseEnter: function(sender, eventArgs)
	{
		var book = eval(sender.Tag);
		if(book.HasPages && book.Id != this.CurrentBook.id){
			sender.Children.getItem(0).Visibility = "Visible";
		}
	},
	
	handleIndexOfBooksMouseLeave: function(sender, eventArgs)
	{
		var book = eval(sender.Tag);
		if(book.HasPages){
			sender.Children.getItem(0).Visibility = "Collapsed";
		}
	},
	
	handleIndexOfBooksMouseLeftButtonDown: function(sender, eventArgs)
	{
		this.onGetPagesByBook(eval(sender.Tag));
		sender.Children.getItem(0).Visibility = "Collapsed";
	},
	
	handleGotoSelectedBook: function()
	{
		var GotoSelectedBookAnimation =			this.rootElement.findName("GotoSelectedBookAnimation");
		var GotoSelectedBookAnimationDouble0 =	this.rootElement.findName("GotoSelectedBookAnimationDouble0");
		GotoSelectedBookAnimation.stop();
		GotoSelectedBookAnimationDouble0.To =	-this.CurrentBook.Canvas["Canvas.Left"];
		GotoSelectedBookAnimation.begin();
	},
	
	isScrollBookSelectionAnimation: false,
	handleButtonBookSelectionMouseLeftDown: function(sender, eventArgs)
	{
		var factor = 1;
		if(sender.Name.indexOf("Left") != -1){
			factor = -1;
		}
		var maxItemsViewAble = Math.floor(sender.findName("OuterBookSelection").Width/sender.findName("Book1").Width)-1;
		var maxX = -(sender.findName("BookSelectionItems").Children.Count+2) * sender.findName("Book1").Width;
		var BookSelectionTranslateTransform = sender.findName("BookSelectionTranslateTransform");
		var moveBy = maxItemsViewAble * sender.findName("Book1").Width * factor;
		var moveTo = BookSelectionTranslateTransform.X + moveBy;
		if(this.isScrollBookSelectionAnimation || moveTo > (maxItemsViewAble)*sender.findName("Book1").Width || moveTo<maxX) {
			return;
		}
		this.isScrollBookSelectionAnimation = true;
		var ScrollBookSelectionAnimation =			this.rootElement.findName("ScrollBookSelectionAnimation");
		var ScrollBookSelectionAnimationDouble0 =	this.rootElement.findName("ScrollBookSelectionAnimationDouble0");
		ScrollBookSelectionAnimationDouble0.By =	moveBy;
		ScrollBookSelectionAnimation.begin();
		/*sender.findName("Debug").Text = "" + moveTo;
		BookSelectionTranslateTransform.X = moveTo;*/
	},
	
	completedScrollBookSelectionAnimation: function(sender, eventArgs)
	{
		this.isScrollBookSelectionAnimation = false;
	},
	
	onGetPagesByBook: function(result)
	{
		this.setChosenBook(result);
		var description = new CodexSinaiticus.ServiceInterface.BookDescription();
		description.bookId = result.Id;
		CodexSinaiticus.ServiceImplementation.PageProvider.GetPagesByBook(
			description, 
			Silverlight.createDelegate(this, this.onGetPagesCompleted),
			null,
			null); 
	},
	
	setChosenBook: function(result)
	{
		var chosenBoxWidth = 180;
		this.CurrentBook.title = result.Title;
		this.CurrentBook.id = result.Id;
		this.CurrentBook.index = result.Index;
		var BookSelectionItems = this.rootElement.findName("BookSelectionItems");
		var currentItem = this.rootElement.findName("BookSelectionItems").Children.getItem(this.CurrentBook.index);
		this.CurrentBook.Canvas = currentItem;
		for(var i = 0; i<BookSelectionItems.Children.Count; i++){
			var selectionItem = BookSelectionItems.Children.getItem(i);
			if(i>this.CurrentBook.index){
				selectionItem["Canvas.Left"] = i*selectionItem["Width"] + (chosenBoxWidth-selectionItem["Width"])
			} else {
				selectionItem["Canvas.Left"] = i*selectionItem["Width"];
			}
			var selectionItemOuterTitle = selectionItem.findName(selectionItem.Name + "OuterTitle");
			var selectionItemOuterTitleScaleTransform = selectionItem.findName(selectionItem.Name + "OuterTitleScaleTransform");
			if(i==this.CurrentBook.index){
				selectionItem.Children.getItem(1).Visibility = "Collapsed";
				selectionItemOuterTitle["Canvas.Left"] = 70;
				selectionItemOuterTitle["Canvas.Top"] = 20;
				selectionItemOuterTitleScaleTransform.ScaleX = selectionItemOuterTitleScaleTransform.ScaleY = 1.15;
			}else {
				selectionItem.Children.getItem(1).Visibility = "Visible"
				selectionItemOuterTitle["Canvas.Left"] = 50;
				selectionItemOuterTitle["Canvas.Top"] = 20;
				selectionItemOuterTitleScaleTransform.ScaleX = selectionItemOuterTitleScaleTransform.ScaleY = 1;
			}
		}
		var BookSelectionBackgroundBefore = this.rootElement.findName("BookSelectionBackgroundBefore");
		BookSelectionBackgroundBefore["Canvas.Left"] = -(BookSelectionBackgroundBefore["Width"]-currentItem["Canvas.Left"]);
		var BookSelectionBackgroundAfter = this.rootElement.findName("BookSelectionBackgroundAfter");
		BookSelectionBackgroundAfter["Canvas.Left"] = currentItem["Canvas.Left"]+chosenBoxWidth;
		var BookSelectionChosen = this.rootElement.findName("BookSelectionChosen");
		BookSelectionChosen["Canvas.Left"] = currentItem["Canvas.Left"];
		
	},
	
	onGetPagesCompleted: function(result, context, methodName)
	{
		this.handleGotoSelectedBook();
		var test = 0;
		var tempCanvas = this.plugIn.content.createFromXaml(result.Xaml);
		var sizeOfFolios = result.Size;
		if(AvailableFolios){
			var left = 0;
			for(var i = 0; i<result.Size; i++){
				var tag = eval(tempCanvas.Children.getItem(i).tag);
				if(!AvailableFolios[String.format("F{0}_{1}", tag.Quire, tag.Folio)]){
					tempCanvas.Children.getItem(i).Opacity = 0;
				}
			}
		}
		this.PageSliderSectors.Children.Clear();
		var sectorsWidth = this.PageSliderSectors.Width / sizeOfFolios;
		this.CurrentBook.pages = [];
		var firstAvailablePage = null;
		for(var i = 0; i<sizeOfFolios; i++){
			var tag = eval(tempCanvas.Children.getItem(i).tag);
			var isAvailable = (tempCanvas.Children.getItem(i).Opacity != 0);
			tag.isAvailable = isAvailable;
			if(firstAvailablePage === null && isAvailable){
				firstAvailablePage = i;
				tag.firstAvailablePage = true;
			} else {
				tag.firstAvailablePage = false;
			}
			this.CurrentBook.pages.push(tag);
			var tag = eval(tempCanvas.Children.getItem(i).tag);
			var tempSector = this.plugIn.content.createFromXaml(String.format('<Canvas Width="{0}" Canvas.Left="{1}" Height="20" Background="#00FF{3}"><Path Canvas.Top="15" Width="1" Height="2" Stretch="UniformToFill" Visibility="{4}" Stroke="#FFACACAC" Canvas.Left="{2}" Data="M0,0 L0,2"/></Canvas>', sectorsWidth, sectorsWidth*i, sectorsWidth/2, (i%2 == 1) ? 'FF00' :'00FF' , (isAvailable) ? 'Visible' :'Collapsed' ));
			tempSector.Tag = "({'pageId' : "+i+"})";
			if(isAvailable){
				tempSector.addEventListener("MouseLeftButtonUp", Silverlight.createDelegate(this, this.handlePageSliderMouseLeftButtonUp));
				tempSector.addEventListener("MouseEnter", Silverlight.createDelegate(this, this.handlePageSliderMouseEnter));
				tempCanvas.Children.getItem(i).addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.handleNavBandOfPagesMouseLeftDown));
			}
			this.PageSliderSectors.Children.Add(tempSector);
		}
		this.rootElement.findName("NavBandOfPages").Children.Clear();
		this.rootElement.findName("NavBandOfPages").Children.Add(tempCanvas);
		this.rootElement.findName("NavBandOfPagesTranslateTransform").X = 0;
		this.rootElement.findName("ScanInfoTitle").Text = this.CurrentBook.title;
		this.rootElement.findName("PageSliderInfoTitle").Text = this.CurrentBook.title;
		this.loadCodexPage(firstAvailablePage);
		
	},

	loadCodexPage: function(pageId){
		this.movePageSliderSlider(pageId);
		var PreviousPage = this.CurrentPage;
		this.CurrentPage = this.CurrentBook.pages[pageId];
		this.CurrentPage.Id = pageId;
		this.CurrentPage.gotTranslation = false;
		this.CurrentPage.gotTransscription = false;
		this.rootElement.findName("ScanInfoQuire").Text = "" + this.CurrentPage.Quire;
		this.rootElement.findName("ScanInfoFolio").Text = "" + this.CurrentPage.Folio;
		this.rootElement.findName("ScanInfoSide").Text = (this.CurrentPage.Side == 1) ? this.Language.SideBack: this.Language.SideFront;
		if(this.playFlyOutTextbox){
			this.onGetTranslation();
		}
		if(this.showTranscriptionBlock){
			this.onGetTranscription();
		}
		var ScanOrigin = this.rootElement.findName("ScanOrigin");
		var nextPageAvailable = (this.CurrentBook.pages[pageId+1] && this.CurrentBook.pages[pageId+1].isAvailable);
		this.rootElement.findName("ButtonSkipRight").Visibility = (this.CurrentPage.Id >= this.CurrentBook.pages.length-1 || !nextPageAvailable) ? "Collapsed" : "Visible";
		this.rootElement.findName("ButtonSkipLeft").Visibility = (this.CurrentPage.firstAvailablePage) ? "Collapsed" : "Visible";
		
		this.rootElement.findName("LoadingImageArea").Visibility = "Visible";
		this.rootElement.findName("FlyOutScanInfoThumb").Source = this.rootElement.findName("NavBandOfPages").Children.GetItem(0).Children.GetItem(pageId).Children.getItem(0).Source;;
		
		var downloader = this.plugIn.createObject("downloader");
		downloader.addEventListener("completed", Silverlight.createDelegate(this, this.onScanDownloadCompleted));
//		downloader.addEventListener("progressChanged", Silverlight.createDelegate(this, this.onScanDownloadProgressChanged));
		downloader.open("GET", this.CurrentPage.Sli.FileName);
		downloader.send();
	},
	resetScanOrigin: function(sender, eventArgs){
		this.ScaleScan.resetScale();
		this.rootElement.findName("ScanOrigin")["Canvas.Left"] = this.rootElement.findName("ScanOrigin")["Canvas.Top"] =0
	},
	
	handleNavBandOfPagesMouseLeftDown: function(sender, eventArgs){
		var tag = eval(sender.tag);
		for(var i=0; i<sender.getParent().Children.Count;i++){
			if(sender.getParent().Children.getItem(i).Name == sender.Name) this.loadCodexPage(i);
		}
	},
	
	onScanDownloadProgressChanged: function(sender, eventArgs){
		return;
		var LoadingImageAreaRectangle = sender.findName("LoadingImageAreaRectangle");
		LoadingImageAreaRectangle["Width"] = sender.downloadProgress * (LoadingImageAreaRectangle.GetParent().Width-2*LoadingImageAreaRectangle["Canvas.Left"]);
	},
	
	onScanDownloadCompleted: function(sender, eventArgs){
		this.resetScanOrigin();
		var ScanOrigin = sender.findName("ScanOrigin");
		ScanOrigin.Children.GetItem(0).setSource(sender, "");
		ScanOrigin.Height	= ScanOrigin.Children.GetItem(0).Height	= ScanOrigin.Children.GetItem(1).Height	= this.CurrentPage.Sli.Height;
		ScanOrigin.Width	= ScanOrigin.Children.GetItem(0).Width	= ScanOrigin.Children.GetItem(1).Width	= this.CurrentPage.Sli.Width;
		this.updateScanOriginScale(sender);
		this.rootElement.findName("LoadingImageArea").Visibility = "Collapsed";
		sender.findName("NavBandOfPagesAnimationDoubleAni1").to = -(this.CurrentPage.Id*((this.NavBandItem.Width+this.NavBandItem.MarginX)));
//		sender.findName("Debug").Text = "" + sender.findName("NavBandOfPagesAnimationDoubleAni1").to;
		this.hasNavBandOfPagesAnimation = true;
		this.NavBandOfPagesAnimation.begin();
		this.isLoading = false;
		if(this.atStart){
			this.showButtonStartApp(sender);
		}
	},
	
	onKeyUp: function(sender, keyEventArgs){
		if ((keyEventArgs.key == 16) && (keyEventArgs.Ctrl == true)){
			this.handleFlyOutTextbox(sender, null);
		}
		if ((keyEventArgs.key == 15) && (keyEventArgs.Ctrl == true)){
			this.onButtonFullscreenMouseLeftButtonUp(sender, null);
		}
	},
	
	handleButtonSkip: function(sender, eventArgs) 
	{
		if(!this.hasNavBandOfPagesAnimation){
			var nextPage = 0;
			switch(sender.Name){
				case "ButtonSkipRight":
					if(this.CurrentPage.Id+1<this.CurrentBook.pages.length){
						nextPage = 1;
					}
					break;
				case "ButtonSkipLeft":
					if(this.CurrentPage.Id>0){
						nextPage = -1;
					}
					break;
			};
			if(nextPage != 0){
				this.loadCodexPage(this.CurrentPage.Id+nextPage);
			}
		}
	},
	
	isPageSliderMouseLeftButtonDown : false,
	handlePageSliderMouseLeftButtonDown: function(sender, eventArgs) 
	{
		this.visiblePageSliderInfo(true);
		this.isPageSliderMouseLeftButtonDown = true;
//		sender.findName("Debug").Text = sender.Name;
		this.movePageSliderSlider(this.PageSliderSectorMouseEnter);
		
	},

	handlePageSliderMouseLeave: function(sender, eventArgs) 
	{
		this.visiblePageSliderInfo(false);
		if(this.isPageSliderMouseLeftButtonDown){
			this.isPageSliderMouseLeftButtonDown = false;
			this.movePageSliderSlider(this.CurrentPage.Id);
		}
	},
	
	handlePageSliderMouseLeftButtonUp: function(sender, eventArgs) 
	{
		this.isPageSliderMouseLeftButtonDown = false;
		var tag = eval(sender.Tag);
		this.visiblePageSliderInfo(false);
		this.loadCodexPage(tag.pageId);
	},
	
	handlePageSliderMouseEnter: function(sender, eventArgs) 
	{
		var tag = eval(sender.Tag);
		this.PageSliderSectorMouseEnter = tag.pageId;
		if(this.isPageSliderMouseLeftButtonDown){
			this.movePageSliderSlider(this.PageSliderSectorMouseEnter);
		}
	},
	
	movePageSliderSlider: function(sector){
		var PageSliderSlider = this.rootElement.findName("PageSliderSlider");
		var SingleSector = this.PageSliderSectors.Children.getItem(sector);
		this.rootElement.findName("textPageSliderInfoQuire").Text = this.Language.Quire;
		this.rootElement.findName("PageSliderInfoQuire").Text = "" + this.CurrentBook.pages[sector].Quire;
		this.rootElement.findName("textPageSliderInfoFolio").Text = this.Language.Folio;
		this.rootElement.findName("PageSliderInfoFolio").Text = "" + this.CurrentBook.pages[sector].Folio;
		this.rootElement.findName("textPageSliderInfoSide").Text = this.Language.Side;
		this.rootElement.findName("PageSliderInfoSide").Text = (this.CurrentBook.pages[sector].Side == 1) ? this.Language.SideBack: this.Language.SideFront;
		this.rootElement.findName("PageSliderThumb").Source = this.rootElement.findName("NavBandOfPages").Children.GetItem(0).Children.GetItem(sector).Children.getItem(0).Source;
		PageSliderSlider["Canvas.Left"] = SingleSector["Canvas.Left"] + SingleSector.Children.getItem(0)["Canvas.Left"];
	},
	
	visiblePageSliderInfo: function(visible){
		var StoryboardIn	= this.rootElement.findName("PageSliderInfoAnimation1");
		var StoryboardOut	= this.rootElement.findName("PageSliderInfoAnimation0");
		if(visible){
			this.rootElement.findName("PageSliderInfo").Visibility = "Visible";
			StoryboardIn.pause();
			StoryboardOut.begin();
		} else {
			StoryboardOut.pause();
			StoryboardIn.begin();
		}
	},
	
	completedPageSliderInfoAnimation1: function(sender, eventArgs)
	{
		sender.findName("PageSliderInfo").Visibility = "Collapsed";
	},
	
	completedNavBandOfPagesAnimation: function(sender, eventArgs)
	{
		this.hasNavBandOfPagesAnimation = false;
	},
	
	playFlyOutScanInfo: false,
	handleFlyOutScanInfo: function(sender, eventArgs) {
		var StoryboardIn	= sender.findName("FlyInScanInfoAnimation");
		var StoryboardOut	= sender.findName("FlyOutScanInfoAnimation");
		var ButtonFlyOut	= sender.findName("ButtonFlyOutScanInfo");
		var FlyOutScanInfo	= sender.findName("FlyOutScanInfo");
		if(this.playFlyOutScanInfo){
			StoryboardOut.pause();
			StoryboardIn.begin();
		} else {
			FlyOutScanInfo.Visibility = "Visible";
			StoryboardIn.pause();
			StoryboardOut.begin();
		};
		this.playFlyOutScanInfo = !this.playFlyOutScanInfo;
		ButtonFlyOut.Children.getItem(2).Visibility = (ButtonFlyOut.Children.getItem(2).Visibility == "Visible") ? "Collapsed" : "Visible";
	},
	handleFlyInScanInfoAnimationCompleted: function(sender, eventArgs) {
		sender.findName("FlyOutScanInfo").Visibility = "Collapsed";
	},
	handleZoomArea: function(sender, eventArgs) {
		var Scan = sender.findName("Scan");
		var ScanOrigin = sender.findName("ScanOrigin");
		var ScanCanvasScaleTransform = sender.findName("ScanCanvasScaleTransform");
		var scaleX = Scan.Width/eventArgs.Width;
		var scaleY = Scan.Height/eventArgs.Height;
		var ScaleFactor = ((scaleX > scaleY) ? scaleY : scaleX);
		var center = {
			X : Scan.Width/2,
			Y : Scan.Height/2
		}
		var scaleCenter = {
			X : (ScanOrigin["Canvas.Left"]-(eventArgs.X+(eventArgs.Width/2)-(Scan.Width/2)))/ScanCanvasScaleTransform.ScaleX,
			Y : (ScanOrigin["Canvas.Top"]-(eventArgs.Y+(eventArgs.Height/2)-(Scan.Height/2)))/ScanCanvasScaleTransform.ScaleY
		}
//		ScanOrigin["Canvas.Left"] = scaleCenter.X;
//		ScanOrigin["Canvas.Top"] = scaleCenter.Y;
		
		sender.findName("ZoomAreaAnimationLeft").To = scaleCenter.X;
		sender.findName("ZoomAreaAnimationTop").To = scaleCenter.Y;
		sender.findName("ZoomAreaAnimation").begin();
		this.ScaleScan.rectangleScale(ScaleFactor*0.9);
		return;		
	},
	
	
	showTranscriptionBlock: false,
	handleTranscriptionBlock: function(sender, eventArgs){
		if(!this.showTranscriptionBlock){
			this.onGetTranscription();
		}
		var StoryboardIn	= sender.findName("TranscriptionAnimation1");
		var StoryboardOut	= sender.findName("TranscriptionAnimation0");
		if(this.showTranscriptionBlock){
			StoryboardOut.pause();
			StoryboardIn.begin();
		} else {
			StoryboardIn.pause();
			StoryboardOut.begin();
		};
		this.showTranscriptionBlock = !this.showTranscriptionBlock;
	},
	onGetTranscription: function() {
		var description = new CodexSinaiticus.ServiceInterface.PageDescription();
		description.quire = this.CurrentPage.Quire;
		description.folio = this.CurrentPage.Folio;
		description.side = this.CurrentPage.Side;
		CodexSinaiticus.ServiceImplementation.PageProvider.GetTranscriptionByPage(
			description, 
			Silverlight.createDelegate(this, this.onGetTranscriptionCompleted),
			null,
			null); 
	},
	onGetTranscriptionCompleted: function(result, context, methodName) {
		//var  = result.Xaml;
		var alignObjectName = String.format("Q{0}_{1}_{2}",this.CurrentPage.Quire, this.CurrentPage.Folio, this.CurrentPage.Side);
		var alignmentCols = (TranscriptionAlignment[alignObjectName]) ? TranscriptionAlignment[alignObjectName] : TranscriptionAlignment[String.format("Q0_0_{0}",this.CurrentPage.Side)];
		var notAvailable = false;
		try {
			var Xaml = this.plugIn.content.createFromXaml(result.Xaml);
		} catch (e){
			var XamlString = String.format('<Canvas><Canvas Tag="col"><TextBlock Tag="hasError" FontSize="55" Foreground="#FFFF0000" FontWeight="Bold">{0}</TextBlock></Canvas></Canvas>', this.Language.TranscriptionNotAvail);
			var Xaml = this.plugIn.content.createFromXaml(XamlString);
		}
		var cols = 0;
		for(var i=0; i<Xaml.Children.Count; i++){
			if(Xaml.Children.GetItem(i).Tag=="col"){
				var Col = Xaml.Children.GetItem(i);
				Col["Canvas.Left"] = alignmentCols[cols].X1;
				Col["Canvas.Top"] = alignmentCols[cols].Y1;
				cols++;
				for(var j=0; j<Col.Children.Count; j++){
					Col.Children.GetItem(j)["Canvas.Top"] = 36 * j;
					if(Col.Children.GetItem(j).Tag != "hasError"){
						Col.Children.GetItem(j).Text = Col.Children.GetItem(j).Text.toUpperCase()
						Col.Children.GetItem(j).setFontSource(this.PackageZip);
						Col.Children.GetItem(j).fontFamily  = "Gentium";
					}
				}
			}
		}
		this.rootElement.findName("Transcription").Children.Clear();
		Xaml.Visibility = "Visible"
		this.rootElement.findName("Transcription").Children.Add(Xaml);
	},

	playFlyOutTextbox: false,
	handleFlyOutTextbox: function(sender, eventArgs) {
		var StoryboardIn	= sender.findName("FlyInTextboxAnimation");
		var StoryboardOut	= sender.findName("FlyOutTextboxAnimation");
		var ButtonFlyOut	= sender.findName("ButtonFlyOutScanInfo");
		if(this.playFlyOutTextbox){
			StoryboardOut.pause();
			StoryboardIn.begin();
		} else {
			StoryboardIn.pause();
			StoryboardOut.begin();
		};
		this.playFlyOutTextbox = !this.playFlyOutTextbox;
	},
	completedFlyOutTextbox: function(sender, eventArgs) {
		if(!this.CurrentPage.gotTranslation){
			this.onGetTranslation();
		}
	},
	onGetTranslation: function() {
		
		var description = new CodexSinaiticus.ServiceInterface.PageDescription();
		description.quire = this.CurrentPage.Quire;
		description.folio = this.CurrentPage.Folio;
		description.side = this.CurrentPage.Side;
		description.language = this.Language.CurrentLanguage;
		var xamlFragment = '<TextBlock Canvas.Top="10" Canvas.Left="10" FontSize="12" Foreground="#FF3c3c3c" Text="Loading translation..." />';
		textBlock = this.plugIn.content.createFromXaml(xamlFragment, false);
		var TextScrollerInnerBox = this.rootElement.findName("TextScrollerInnerBox");
		if(TextScrollerInnerBox.Children.Count >0){
			TextScrollerInnerBox.Children.remove(TextScrollerInnerBox.Children.getItem(0));
		}
		TextScrollerInnerBox.Children.add(textBlock);

		CodexSinaiticus.ServiceImplementation.PageProvider.GetTranslationByPage(
			description, 
			Silverlight.createDelegate(this, this.onGetTranslationCompleted),
			null,
			null
		);
	},
	onGetTranslationCompleted: function(result, context, methodName) {
		translationBoxText = this.plugIn.content.createFromXaml(result.Xaml, false);
		var TextScrollerInnerBox = this.rootElement.findName("TextScrollerInnerBox");
		TextScrollerInnerBox.Children.remove(TextScrollerInnerBox.Children.getItem(0));
		if(translationBoxText.Children.count == 0){
			var translationBoxXaml = '<TextBlock Canvas.Top="10" Canvas.Left="10" FontSize="12" Foreground="#FF3c3c3c" Text="'+ this.Language.TranslationNotAvail +'" />';
			translationBoxText = this.plugIn.content.createFromXaml(translationBoxXaml, false);
			TextScrollerInnerBox.Children.add(translationBoxText);
			TextScrollerInnerBox.Height = translationBoxText.ActualHeight;
		} else {
			TextScrollerInnerBox.Children.add(translationBoxText);
			this.TranslationBox = new TranslationBox(translationBoxText);
			this.TranslationBox.updateLayout();
			this.pluginResize.addAfter("translationBox", Silverlight.createDelegate(this, function(){
				this.TranslationBox.updateLayout()
				this.ScrollbarsTextBox.updateLayout();
			}));
		}
		this.CurrentPage.gotTranslation = true;

		 this.ScrollbarsTextBox.updateLayout();
	},

	onButtonGetTOCMouseLeftButtonDown: function(sender, eventArgs)
	{	
		this.handleNavBandBook(sender);
	},
	
	playNavBandBook: false,
	handleNavBandBook: function(sender){
		var StoryboardIn	= sender.findName("TaskbarAnimation1");
		var StoryboardOut	= sender.findName("TaskbarAnimation0");
		var ButtonGetTOCRotateTransform	= sender.findName("ButtonGetTOCRotateTransform");
		var textBookSelection	= sender.findName("textBookSelectionOpen");
		if(this.playNavBandBook){
			StoryboardOut.pause();
			StoryboardIn.begin();
			ButtonGetTOCRotateTransform.Angle = 0;
			textBookSelection.Text = this.Language.BookSelectionOpen;
		} else {
			StoryboardIn.pause();
			StoryboardOut.begin();
			ButtonGetTOCRotateTransform.Angle = 90;
			textBookSelection.Text = this.Language.BookSelectionClose;
		};
		this.playNavBandBook = !this.playNavBandBook;
	},
	
	// Event handler for clicking the full-screen mode button.
	onButtonFullscreenMouseLeftButtonUp: function(sender, eventArgs)
	{
		// Toggle between embedded mode and full-screen mode.
		sender.getHost().content.fullScreen = !sender.getHost().content.fullScreen;
		this.isFullscreen = !this.isFullscreen;
		
		sender.Children.getItem(0).setSource(this.PackageZip, (this.isFullscreen)? Package.Images.Icons.Fullscreen1 : Package.Images.Icons.Fullscreen0 );
	},
	
	// Event handler for clicking the full-screen mode button.
	updateScreenLayout: function(sender, Dimension)
	{
		var scaleFactor = Dimension.Current.height / Dimension.Previous.height;
		if(sender.findName("SplashScreen").Visibility == "Visible"){
			var SplashScreen = sender.findName("SplashScreen");
			var scaleFactorX = Dimension.Current.width / 1024;
			var scaleFactorY = Dimension.Current.height / 698;
			SplashScreen.Width =  Dimension.Current.width;
			SplashScreen.Height =  Dimension.Current.height;
			sender.findName("SplashScreenScaleTransform").ScaleX = sender.findName("SplashScreenScaleTransform").ScaleY = (scaleFactorX<scaleFactorY) ? scaleFactorX : scaleFactorY ;
			if(scaleFactorX<scaleFactorY){
				SplashScreen.Children.GetItem(0)["Canvas.Left"] = 0;
				SplashScreen.Children.GetItem(0)["Canvas.Top"] = ((scaleFactorX<1) ? SplashScreen.Height - sender.findName("SplashScreenScaleTransform").ScaleX*SplashScreen.Height : sender.findName("SplashScreenScaleTransform").ScaleX*SplashScreen.Height - SplashScreen.Height)/2;
			}else {
				SplashScreen.Children.GetItem(0)["Canvas.Top"] = 0;
				SplashScreen.Children.GetItem(0)["Canvas.Left"] = ((scaleFactorY<1) ? SplashScreen.Width - sender.findName("SplashScreenScaleTransform").ScaleX*SplashScreen.Width : sender.findName("SplashScreenScaleTransform").ScaleX*SplashScreen.Width - SplashScreen.Width)/2;
			}
		}
		var Boxes = sender.findName("Boxes");
		Boxes.Height = Math.round(Boxes.Height * scaleFactor);
		Boxes.Width = Math.round(Boxes.Width * scaleFactor);
		Boxes["Canvas.Top"] = Math.round((Dimension.Current.height-Boxes.Height)/2);
		Boxes["Canvas.Left"] = Math.round((Dimension.Current.width-Boxes.Width)/2);

		var BoxesTranslateTransformAnimation = sender.findName("BoxesTranslateTransformAnimation");
		BoxesTranslateTransformAnimation.To = (Boxes["Canvas.Left"]-60)*-1;
		var BoxesTranslateTransform = sender.findName("BoxesTranslateTransform");
		BoxesTranslateTransform.X = (this.playFlyOutTextbox) ? BoxesTranslateTransformAnimation.To : 0 ;

		var ScanBox = sender.findName("ScanBox");
		ScanBox.Children.GetItem(0).Children.GetItem(0).Width = Boxes.Width; 
		ScanBox.Children.GetItem(0).Children.GetItem(0).Height = Boxes.Height; 

		var Scan = sender.findName("Scan");
		Scan.Width = Boxes.Width-12; 
		Scan.Height = Boxes.Height-12; 
		Scan.Clip = String.format("M0,0 L{0},0 L{0},{1} L0,{1} z", Scan.Width, Scan.Height);
		
		
		var TextBox = sender.findName("TextBox");
		TextBox.Height = Boxes.Height-30; 
		TextBox.Children.GetItem(0).Height = TextBox.Height; 
		TextBox.Children.GetItem(0).Children.GetItem(0).Children.GetItem(0).Height = TextBox.Height; 
		TextBox.Children.GetItem(0).Children.GetItem(1).Height = TextBox.Height-12;
		TextBox.Clip = String.format("M0,0 L{0},0 L{0},{1} L0,{1} z", TextBox.Width, TextBox.Height);

		var InlineText = sender.findName("InlineText");
		InlineText.Height = TextBox.Height-102; 

		var TextBottom = sender.findName("TextBottom");
		TextBottom["Canvas.Top"] = InlineText.Height + InlineText["Canvas.Top"]+10;
		TextBottom.Height = 70;

		var InlineTextBorders = sender.findName("InlineTextBorders");
		InlineTextBorders.Children.GetItem(1)["Canvas.Top"] = InlineText.Height-1;
		InlineTextBorders.Children.GetItem(2).Height = InlineText.Height;
		InlineTextBorders.Children.GetItem(3).Height = InlineText.Height;
		
		var TextScrollerBox = sender.findName("TextScrollerBox");
		TextScrollerBox.Height = InlineText.Height-2;
		TextScrollerBox.Children.GetItem(0).Height = TextScrollerBox.Height;

		var TextScrollerBoxScrollbarV = sender.findName("TextScrollerBoxScrollbarV");
		TextScrollerBoxScrollbarV.Height = TextScrollerBox.Height;
		
		TextScrollerBoxScrollbarV.Children.getItem(2)["Canvas.Top"] = TextScrollerBox.Height - TextScrollerBoxScrollbarV.Children.getItem(2).Height;
		
		this.updateTextBoxLayoutWidth(sender);
		this.updateScanOriginScale(sender);

		// Layout Areas
		var LassoArea = sender.findName("LassoArea");
		var LoadingImageArea = sender.findName("LoadingImageArea");
		LassoArea.Width = LoadingImageArea.Width = Scan.Width;
		LassoArea.Height = LoadingImageArea.Height = Scan.Height;
		
		LoadingImageAreaImage = LoadingImageArea.Children.getItem(0);
		LoadingImageAreaImage["Canvas.Top"] = (LoadingImageArea.Height - LoadingImageAreaImage.Height) / 2;
		LoadingImageAreaImage["Canvas.Left"] = (LoadingImageArea.Width - LoadingImageAreaImage.Width) / 2;

		// Layout NavBandOfPages
		this.updateNavBandOfPagesLayout(sender, Dimension.Current);
//		var NavBandOfPages = sender.findName("NavBandOfPages");
		
		this.ScanDragging.updateLayout();

		// Layout Taskbar
		var TaskBar = sender.findName("TaskBar");
		TaskBar["Canvas.Top"] = (Dimension.Current.height-TaskBar.Height);
		TaskBar["Width"] = Dimension.Current.width;

		var TaskBarPath = sender.findName("TaskBarPath");
		TaskBarPath.Width = TaskBar["Width"]+2;

		var ControlBar = sender.findName("ControlBar");
		ControlBar["Canvas.Left"] = (Dimension.Current.width-ControlBar.Width)/2;
		
		var PageSlider = sender.findName("PageSlider");
		PageSlider["Canvas.Left"] = (Dimension.Current.width-PageSlider.Width)/2;
		
		var OuterBookSelection = sender.findName("OuterBookSelection");
		var ICanvas = OuterBookSelection.Children.GetItem(0);
		OuterBookSelection["Width"] = ICanvas["Width"] = Dimension.Current.width-30;
		sender.findName("ButtonBookSelectionLeft")["Canvas.Left"] = OuterBookSelection["Width"]-20;

		var BookSelection = sender.findName("BookSelection");
		BookSelection["Canvas.Left"] = Math.round((OuterBookSelection["Width"]-180)/2);

		sender.findName("OuterBookSelectionRectangleGeometry").Rect = sender.findName("OuterBookSelectionRectangleGeometry2").Rect = String.format("0,0,{0},{1}", OuterBookSelection.Width, OuterBookSelection.Height);
	
		var ButtonFullscreen = sender.findName("ButtonFullscreen");
		ButtonFullscreen["Canvas.Left"] = Dimension.Current.width-24;
		
		var SkipButtons = sender.findName("SkipButtons");
		SkipButtons["Canvas.Top"] = (Dimension.Current.height-SkipButtons.Height)/2;
		SkipButtons["Width"] = Dimension.Current.width;

		var ButtonSkipRight = sender.findName("ButtonSkipRight");
		ButtonSkipRight["Canvas.Left"] = Dimension.Current.width - ButtonSkipRight["Width"] - 30;
		
		try {
			this.TranslationBox.updateLayout();
		} catch(e){}
		this.ScrollbarsTextBox.updateLayout();
		
	},
	updateNavBandOfPagesLayout: function(sender, Plugin){
		var NavBandOfPages = sender.findName("NavBandOfPages");
		var NavBandOfPagesScaleTransform = sender.findName("NavBandOfPagesScaleTransform");
		var NavBandItem = this.NavBandItem;
		var scale = Plugin.height * 1 / NavBandItem.ScaleFactor;
		NavBandOfPagesScaleTransform.ScaleX = NavBandOfPagesScaleTransform.ScaleY = scale; 
		NavBandOfPages["Canvas.Top"] = Math.round((Plugin.height-this.NavBandItem.Height*scale)*0.5);
		NavBandOfPages["Canvas.Left"] = Math.round((Plugin.width-this.NavBandItem.Width*scale)*0.5);

	},
	updateTextBoxLayoutWidth: function(sender){
		var TextBox = sender.findName("TextBox");
		TextBox["Canvas.Left"] = TextBox.getParent().Width-6;
		TextBox.Width = this.rootElement.Width - TextBox.getParent().Width - 105; 
		TextBox.Children.GetItem(0).Width = TextBox.Width; 
		TextBox.Children.GetItem(0).Children.GetItem(0).Children.GetItem(0).Width = TextBox.Width;
		TextBox.Children.GetItem(0).Children.GetItem(1).Width = TextBox.Width-12;
		TextBox.Clip = String.format("M0,0 L{0},0 L{0},{1} L0,{1} z", TextBox.Width, TextBox.Height);
		sender.findName("InnerTextBoxAnimation").To = -TextBox["Width"];
		TextBox.Children.GetItem(0)["Canvas.Left"] = (!this.playFlyOutTextbox) ? -TextBox["Width"] : -6;

		var InlineText = sender.findName("InlineText");
		InlineText.Width = TextBox.Width-38;

		var InlineTextBorders = sender.findName("InlineTextBorders");
		InlineTextBorders.Children.GetItem(3)["Canvas.Left"] = InlineText.Width-1;
		InlineTextBorders.Children.GetItem(0).Width = InlineText.Width;
		InlineTextBorders.Children.GetItem(1).Width = InlineText.Width+1;

		var TextBottom = sender.findName("TextBottom");
		TextBottom.Width = InlineText.Width+26;
		TextBottom.Children.GetItem(0).Width = TextBottom.Width;
		TextBottom.Children.GetItem(1)["Canvas.Left"] = TextBottom.Width-TextBottom.Children.GetItem(1).Width-5;

		var TextScrollerBox = sender.findName("TextScrollerBox");
		TextScrollerBox.Width = InlineText.Width-17;
		TextScrollerBox.Children.GetItem(0).Width = TextScrollerBox.Width;

		var TextScrollerInnerBox = sender.findName("TextScrollerInnerBox");
		TextScrollerInnerBox.Width = TextScrollerBox.Width;


		var TextScrollerBoxScrollbarV = sender.findName("TextScrollerBoxScrollbarV");
		TextScrollerBoxScrollbarV['Canvas.Left'] = TextScrollerBox.Width;

	},
	updateScanOriginScale: function(sender){
		if(this.CurrentPage){
			var Scan = sender.findName("Scan");
			var ScanCanvas = sender.findName("ScanCanvas");
			var ScanOriginScaleTransform = sender.findName("ScanOriginScaleTransform");
			var ScanOrigin = sender.findName("ScanOrigin");
			ScanOriginScaleTransform.ScaleX = ScanOriginScaleTransform.ScaleY = Scan.Height/this.CurrentPage.Sli.Height;
			ScanCanvas.Height	= Scan.Height;
			ScanCanvas.Width	= Math.ceil(ScanOriginScaleTransform.ScaleY*this.CurrentPage.Sli.Width);
			 
		}
	}

}

InterfaceLanguage = function(rootElement){
	var thisClass = this;
    this.toString = function(){
        return "InterfaceLanguage";
    };
    this.rootElement = rootElement;
}
InterfaceLanguage.prototype = {
	update : function(Language){
		var rootElement = this.rootElement;
		for(var item in Language){
			if(rootElement.findName("text" + item)){
				rootElement.findName("text" + item).Text = Language[item];
			}
		}
	}
}

TranslationBox = function(Canvas){
	this.rootElement = Canvas;
	this.margin = [5,5,5,5];
	this.padding = [5,5,5,5];
	this.fontDescender = 2;
	this.versLeft = 55; 
	this.rootChildren = this.rootElement.Children;
	this.parentCanvas = this.rootElement.getParent();
	this.top = 0;
}
TranslationBox.prototype = {
	updateLayout: function(){
		this.top = 0;
		var childWidth = this.parentCanvas.Width - this.margin[1] * 2;
		var DebugText = "childWidth: " + childWidth;
		for(var i=0; i<this.rootChildren.count; i++){
			var Child = this.rootChildren.getItem(i);
			var Child0 = Child.Children.getItem(0);
			var textBoxHeight = 0;
			DebugText+= "\n " + i + ": " + this.top;
			switch(Child.Tag){
				case "Vers":
					var Child1 = Child.Children.getItem(1);
					Child1.Height = 0;
					Child1.Width = 0;
					Child0["Canvas.Top"]		= this.padding[0];
					Child1["Canvas.Top"]		= this.padding[0];
					Child0["Canvas.Left"]	= this.padding[3];
					Child1["Canvas.Left"]	= this.versLeft;
					Child1["Width"]			= childWidth - this.versLeft - this.padding[1] - this.padding[3];
					textBoxHeight = Math.ceil(Child1.ActualHeight) + this.padding[0] + this.padding[2];
					Child1.Height = textBoxHeight;
					break;
				case "BookTitle":
					Child0.Height = 1;
					textBoxHeight = Math.ceil(Child0.ActualHeight) + this.padding[0] + this.padding[2];
					Child0["Canvas.Top"]	= this.padding[0];
					Child0["Canvas.Left"]	= this.padding[3];
					break;
			}
			Child.Width = childWidth;
			Child.Height = textBoxHeight;
			Child["Canvas.Top"] = this.margin[0] + this.top;
			this.top+= this.margin[0] + textBoxHeight;
			Child["Canvas.Left"] = this.margin[1];
			DebugText+= ", " + Child["Height"] + ", " + Child1.ActualWidth;
		}
		this.parentCanvas.Height = this.top + this.margin[2];
		//this.rootElement.findName("Debug").Text = DebugText
	}
}


/*Helper-----------------------------------*/

function SetImageFailed(sender, eventArgs){
	sender.tag = "({'ImageFailed':false})";
	var test = sender;
}
