﻿// JScript source code

  /**
  * if automatic mode - create albums array
  */
  if(mode == "automatic") {
    for( i = 0; i< albums.length; i++) {
        count = albums[i][1];
        ext = albums[i][2];
        for(j = 1; j<=count; j++) {
            albums[i][j] = ((String)(j))+"."+ext;
        }
    }
  }  

//contains calls to silverlight.js, example below loads Page.xaml
function createSilverlight()
{
	Silverlight.createObjectEx({
		source: "Page.xaml",
		parentElement: document.getElementById("SilverlightSimplePhotoAlbumHost"),
		id: "SilverlightControl",
		properties: {
			width: (String)(parentCanvasWidth),
			height: (String)(parentCanvasHeight),
			version: "1.1",
			enableHtmlAccess: "true"
		},
		events: {onLoad: sspa_init}
	});
	   
	// Give the keyboard focus to the Silverlight control by default
    document.body.onload = function() {
      var silverlightControl = document.getElementById('SilverlightControl');
      if (silverlightControl)
      silverlightControl.focus();
    }
    return true;
}
// silverlight controll host
var host;
// actual displayed album
var album_index;
// actual displayed photo
var photo_index;
// loaded thumbscontainer width
var loaded_photos_width;
// scroll to
var scroll_to;

var photoSwitch;
var photoSwitch_da;
var Photo;
var defaultAlbumObject;  

// przeliczane rozmiary:
var AlbumItemsHeight;
var AlbumsHeight;
var AlbumsWidth;
var ThumbinalHeight;
var ThumbinalWidth;
var AlbumItemsWidth;
 
    

    
// ładuje albumy z konfiguracji (taki init);                        
function sspa_init() {
    host = document.getElementById("SilverlightControl");
    var e;
    var parentCanvas = host.content.findName("Albums");
    //alert(parentCanvas);

    var parentTop = padding;
    for(i = 0; i<albums.length; i++) {
        e = host.content.createFromXaml("<TextBlock Text='"+albums[i][0]+
                                        "' Cursor='Hand' Canvas.Top='"+parentTop+
                                        "' Canvas.Left='10' FontSize='16' "+
                                        " MouseLeftButtonUp='load_album' "+
                                        " MouseEnter='albumView' MouseLeave='albumHide' />");
                                        
                                        
        parentCanvas.children.Add(e);
        parentTop += ((Number)(e.FontSize) + padding);
        
        if(e.Text == albums[defaultAlbum][0]) {
            defaultAlbumObject = e;
            //alert(e.Text+" ? "+albums[defaultAlbum][0]);
        }
    }
    
    // initialize some vars:
    photoSwitch = host.content.findName("photoSwitch");
    photoSwitch_da = host.content.findName("photoSwitch_da");
    Photo = host.content.findName("Photo");   
    debug = host.content.findName("debug");  
    addEventsListeners();
    //alert(canvas);
    
    overrideConfiguration();
    overrideSizes();
    
    loadDefault();
}
    
    // loads default album (as its name was clicked)- invoked on init only
    function loadDefault() {
        load_album(defaultAlbumObject, null);
    }
    
    // hides album overview with 64x48 thumbs
    function albumHide(sender, args) {
        var canvas = host.content.findName("albumView");
        canvas.Visibility = "Collapsed";
    }
    
    // shows album overview with 64x48 thumbs
    function albumView(sender, args) {
        var album = findAlbumByName(sender.Text);
        
        var canvas = host.content.findName("albumView");
        canvas.children.Clear();
        canvas.Width = 68 * 4;
        canvas.Height = (Math.ceil(((albums[album].length)-1)/4) * 50)+padding;
        canvas["Canvas.Left"] = parentCanvasWidth - canvas.Width;
        parentLeft = padding;
        parentTop = padding;
        canvas["Canvas.Top"] = sender["Canvas.Top"] + sender["FontSize"];
        for(i=1; i<albums[album].length; i++) {
            xamlSource = "<Image Width='64' Height='48' Source='albums/"+
                                            albums[album][0]+"/"+
                                            albums[album][i]+
                                            "' Canvas.Left='"+parentLeft+
                                            "' Canvas.Top='"+parentTop+"' Canvas.ZIndex='250'>"+
                                            "</Image>";
            //alert(xamlSource);
            //alert(xamlSource);
            e = host.content.createFromXaml(xamlSource);
            canvas.children.Add(e);
            //alert(i); 
            parentLeft += 68;
            if(i % 4 == 0) {
                parentLeft = 4;
                parentTop += 50;
            }
        } 
       canvas.Visibility = "Visible";
      // host.content.findName("albumViewGrow").begin();
        
    }
        
    // laduje klikniety album
    function load_album(sender, args) {
    
        var canvas = host.content.findName("Albums");
        //alert(canvas.children[0]);
        for(i=0; i< canvas.children.Count; i++) {
            canvas.children.getItem(i).Foreground = "#FF000000";
        }
    
        sender.Foreground = "#FFFFFFFF";
        clear_album_items(); // clear thumbs container from old thumbs
        album_index = findAlbumByName(sender.Text); // get index of selected album
        var e;
        var parentCanvas = host.content.findName("AlbumItems");

        // ustaw szerocoś canvas w zależności od ilości elementów
        parentCanvas.Width = Math.max(parentCanvasWidth, (albums[album_index].length-2)*(ThumbinalWidth+padding));
        parentCanvas["Canvas.Left"] = 0;
        
        var parentLeft = padding;
        for(i=1; i<albums[album_index].length; i++) {
            xamlSource = "<Image Height='100' Width='120' Source='albums/"+
                                            albums[album_index][0]+"/"+
                                            albums[album_index][i]+
                                            "' Canvas.Left='"+parentLeft+
                                            "' Canvas.Top='"+padding+
                                            "' MouseLeftButtonUp='load_image'/>";
            //alert(xamlSource);
            e = host.content.createFromXaml(xamlSource);
            parentCanvas.children.Add(e);
            parentLeft += (Number)(e["Width"]) + padding;
            //alert(i);
            
        }
       // policz ile będą zajmować minuaturki
       loaded_photos_width = ((albums[album_index].length-1)*125);
       // jeśli mniej niż szerokość strony, to nie trzeba scrollować
       if(loaded_photos_width < parentCanvasWidth) {
            scroll_to = 0;
       //  jeśli więcej, to scrolluj
       }else {
            scroll_to = loaded_photos_width - parentCanvasWidth;
       }
       showPhoto(album_index, 1);
    }


    function nextPhoto(){
        //alert(photo_index+" ? "+albums[album_index].length);
        if(photo_index < (albums[album_index].length -1)) {
            switchSlideToLeft();
            photoSwitch.AddEventListener("Completed", "switchSlideFromRight");
            //switchSlideFromRight();
            scrollAlign();
        } 
    }
    
    function prevPhoto(){
        if(photo_index > 1) {
            switchSlideToRight();
            photoSwitch.AddEventListener("Completed", "switchSlideFromLeft");
            scrollAlign();
        } 
    }
    
    function switchSlideFromRight(){
        showPhoto(album_index, photo_index+1);
        Photo["Canvas.Left"] = Photo.Width;
        photoSwitch_da.To = 0;
        photoSwitch.RemoveEventListener("Completed", "switchSlideFromRight");
        photoSwitch.begin();
    }
    function switchSlideToLeft(){
        photoSwitch_da.To = -Photo.Width;
        photoSwitch.begin();
    }
    function switchSlideToRight(){
        photoSwitch_da.To = Photo.Width;
        photoSwitch.begin();
    }    
    function switchSlideFromLeft(){
        showPhoto(album_index, photo_index-1);
        Photo["Canvas.Left"] = -Photo.Width;
        photoSwitch_da.To = 0;
        photoSwitch.RemoveEventListener("Completed", "switchSlideFromLeft");
        photoSwitch.begin();
    }
    
    function showPhoto(album, photo){ 
    
        var e = host.content.findName("Photo").Source = "albums/"+albums[album][0]+"/"+albums[album][photo];
        
        album_index = album;
        photo_index = photo;                                    
    }
        
    function clear_album_items(){
        var parentCanvas = host.content.findName("AlbumItems");
          parentCanvas.children.clear();
    }
        
    function load_image(sender, args){
        photo = host.content.findName("Photo");
        photo.Source = sender.Source;
        photo_index = findImageBySource(photo.Source);
    }
        
    function findAlbumByName(name) {
        for(i=0; i<albums.length; i++) {
            if(albums[i][0] == name) {
                return i;
            }
        }
        return false;
    }
    
    /**
    */
    function findImageBySource(source) {
        // fragment ścieżki po ostatnim '/' to nasz source
        source = source.substr( source.lastIndexOf("/")+1, source.length);
        for(i=0; i<albums[album_index].length; i++) {
            if(albums[album_index][i] == source) {
                return i;
            }
        }
        return false;
    }
    
    // policz dane i zacznij animację scrollowania    
    function scrollLeft(sender, args) {
        host.content.findName("scroll_da").To = 0;
        host.content.findName("scroll_da").Duration = "0:0:"+ getScrollDuration("Left");
        sender.findName("scroll").begin();
    }
    function scrollRight(sender, args) {
        host.content.findName("scroll_da").To = -(scroll_to);
        host.content.findName("scroll_da").Duration = "0:0:"+ getScrollDuration("Right");
        sender.findName("scroll").begin();
    }
    function scrollLeftSlow(sender, args) {
        host.content.findName("scroll_da").To = 0;
        host.content.findName("scroll_da").Duration = "0:0:"+ (getScrollDuration("Left")*2);
        sender.findName("scroll").begin();
    }
    function scrollRightSlow(sender, args) {
        host.content.findName("scroll_da").To = -(scroll_to);
        host.content.findName("scroll_da").Duration = "0:0:"+ (getScrollDuration("Right")*2);
        sender.findName("scroll").begin();
    }
    function scrollAlign(){
        var to = - ((photo_index * 125)-400);
        
        if(to >= 0) {
            to =0;
        }
        
        if(to <= -(host.content.findName("AlbumItems").Width - parentCanvasWidth)){
            to = -(host.content.findName("AlbumItems").Width - parentCanvasWidth);
        }
        
        host.content.findName("scroll_da").To = to;
        host.content.findName("scroll_da").Duration = "0:0:1";
        host.content.findName("scroll").begin();
    }
    /**
    * oblicza czas wykonania animacji w zależności od tego, kiedy ona startuje
    */
    function getScrollDuration(side) {
        var duration;
        
        var AlbumItems = host.content.findName("AlbumItems");
        
       // duration = (["Canvas.Left"]/ 125 )*0.25; // każde zdjęcie powinno być przescrollowane w 0.1 s
      //  if(duration != 0){
            // wylicz opóźnienie na podstawie przesunięcia
      //      duration = - duration;
      //  }else {
      //      duration =  albums[album_index].length * 0.25;
      //  }
        
        
     //   dotIndex = ((String)(duration).indexOf('.')>0)? (String)(duration).indexOf('.'): (String)(duration).length;
        
     //   duration = (Number)((String)(duration).substr(0, dotIndex+3)) ;
        // to co pozostało do scrollowania = AlbumItems.Widts - SzerokośćWidocznegoOkna(800) + ujemne przesuniecie w lewo*
        // * - to co już zostało przescrollowane
        if(side == "Right") {
           duration =   (((Number)(AlbumItems["Width"]) - parentCanvasWidth + (Number)(AlbumItems["Canvas.Left"]))  / (ThumbinalWidth+padding)) * 0.25;
        }
        if(side == "Left") {
            duration = - (( (Number)(AlbumItems["Canvas.Left"]) )/(ThumbinalWidth + padding))*0.25;
        }
        dotIndex = ((String)(duration).indexOf('.')>0)? (String)(duration).indexOf('.'): (String)(duration).length;
        
        duration = (Number)((String)(duration).substr(0, dotIndex+3)) ;
        return duration;
    }
    
    // pauzuj animacje
    function pauseScroll(sender, args) {
        sender.findName("scroll").pause();
    } 

  
    function addEventsListeners(){
        host.content.findName("prevButton").AddEventListener("MouseLeftButtonDown", "prevPhoto");
        host.content.findName("nextButton").AddEventListener("MouseLeftButtonDown", "nextPhoto");
        
        host.content.findName("scrollLeft").AddEventListener("MouseEnter", "scrollLeft");
        host.content.findName("scrollLeft").AddEventListener("MouseLeave", "pauseScroll");
        
        host.content.findName("scrollLeftSlow").AddEventListener("MouseEnter", "scrollLeftSlow");
        host.content.findName("scrollLeftSlow").AddEventListener("MouseLeave", "pauseScroll");
        
        
        host.content.findName("scrollRight").AddEventListener("MouseEnter", "scrollRight");
        host.content.findName("scrollRight").AddEventListener("MouseLeave", "pauseScroll");
        
        host.content.findName("scrollRightSlow").AddEventListener("MouseEnter", "scrollRightSlow");
        host.content.findName("scrollRightSlow").AddEventListener("MouseLeave", "pauseScroll");
        
        host.content.findName("fullSizeButton").AddEventListener("MouseLeftButtonUp", "toggleFullSize");
        
        host.content.findName("fullSizeButton").AddEventListener("MouseEnter", "animateFullSize");
        host.content.findName("fullSizeButton").AddEventListener("MouseLeave", "animateFullSizeStop");
    }
    
    function animateFullSize(sender, args){
        host.content.findName("fullSizeButtonAnimation").Begin();
    }
    function animateFullSizeStop(sender, args){
        host.content.findName("fullSizeButtonAnimation").Stop();
    }
    
    // startuj animację, która powiększy, lub zmniejszy rozmiar wyświetlanego zdjęcia
    function toggleFullSize() {
        var Albums = host.content.findName("Albums");
        var AlbumItems = host.content.findName("AlbumItems");
        var photoFullSize = host.content.findName("photoFullSize");
        var photoFullSizeWidth = host.content.findName("photoFullSizeWidth");
        var photoFullSizeHeight = host.content.findName("photoFullSizeHeight");
        var albumItemsHeight = host.content.findName("albumItemsHeight");
        var albumsWidth = host.content.findName("albumsWidth");
        var slideNextButton = host.content.findName("slideNextButton");
        var albumsHeight = host.content.findName("albumsHeight");
        
        var fullSizeButtonAnimation = host.content.findName("fullSizeButtonAnimation");
        
        if( Albums["Canvas.Left"] == parentCanvasWidth  && AlbumItems["Canvas.Top"] == parentCanvasHeight ){
            //alert("go partsize");
            albumsWidth.To = PhotoWidth+padding;
            albumItemsHeight.To = PhotoHeight + padding;
            photoFullSizeWidth.To = PhotoWidth;
            photoFullSizeHeight.To = PhotoHeight;
            slideNextButton.To = PhotoWidth - 30; //szerokość next i prev button
            albumsHeight.To = PhotoHeight;
            
            fullSizeButtonAnimation.Children.GetItem(0).From = 10;
            fullSizeButtonAnimation.Children.GetItem(0).To = 20;
            fullSizeButtonAnimation.Children.GetItem(1).From = 10;
            fullSizeButtonAnimation.Children.GetItem(1).To = 20;
            fullSizeButtonAnimation.Children.GetItem(2).From = 10;
            fullSizeButtonAnimation.Children.GetItem(2).To = 5;
            fullSizeButtonAnimation.Children.GetItem(3).From = 10;
            fullSizeButtonAnimation.Children.GetItem(3).To = 5;
        }else {
            //alert("go fullsize");
            albumsWidth.To = parentCanvasWidth;
            albumItemsHeight.To = parentCanvasHeight;
            photoFullSizeWidth.To = parentCanvasWidth;
            photoFullSizeHeight.To = parentCanvasHeight;
            slideNextButton.To = parentCanvasWidth-30;
            albumsHeight.To = 600;
            
            
            fullSizeButtonAnimation.Children.GetItem(0).From = 20;
            fullSizeButtonAnimation.Children.GetItem(0).To = 10;
            fullSizeButtonAnimation.Children.GetItem(1).From = 20;
            fullSizeButtonAnimation.Children.GetItem(1).To = 10;
            fullSizeButtonAnimation.Children.GetItem(2).From = 5;
            fullSizeButtonAnimation.Children.GetItem(2).To = 10;
            fullSizeButtonAnimation.Children.GetItem(3).From = 5;
            fullSizeButtonAnimation.Children.GetItem(3).To = 10;
        }
       host.content.findName("photoFullSize").Begin();
        
    }
    
    
    // do not edit anything below
    function overrideConfiguration() {
        if(window.parentCanvasBackground) {
            host.content.findName("parentCanvas")["Background"] = parentCanvasBackground;
        }
        if(window.AlbumsBackground) {
            host.content.findName("Albums")["Background"] = AlbumsBackground;
        }
        if(window.AlbumItemsBackground) {
            host.content.findName("AlbumItems")["Background"] = AlbumItemsBackground;
        }
        if(window.PhotoContainerBackground) {
            host.content.findName("PhotoContainerBackground")["Background"] = PhotoContainerBackground;
        }
        if(window.prevButtonGradientStop1Color) {
            host.content.findName("prevButtonGradientStop1")["Color"] = prevButtonGradientStop1Color;
        }
        if(window.prevButtonGradientStop2Color) {
            host.content.findName("prevButtonGradientStop2")["Color"] = prevButtonGradientStop1Color;
        }
        if(window.nextButtonGradientStop1Color) {
            host.content.findName("nextButtonGradientStop1")["Color"] = nextButtonGradientStop1Color;
        }
        if(window.nextButtonGradientStop2Color) {
            host.content.findName("nextButtonGradientStop2")["Color"] = nextButtonGradientStop1Color;
        }
        if(window.scrollLeftBackground) {
            host.content.findName("scrollLeft")["Background"] = scrollLeftBackground;
        }
        if(window.scrollLeftOpacity) {
            host.content.findName("scrollLeft")["Opacity"] = scrollLeftOpacity;
        }
        if(window.scrollLeftSlowBackground) {
            host.content.findName("scrollLeftSlow")["Background"] = scrollLeftSlowBackground;
        }
        if(window.scrollLeftOpacity) {
            host.content.findName("scrollLeftSlow")["Opacity"] = scrollLeftSlowOpacity;
        }
        if(window.scrollRightBackground) {
            host.content.findName("scrollRight")["Background"] = scrollRightBackground;
        }
        if(window.scrollRightOpacity) {
            host.content.findName("scrollRight")["Opacity"] = scrollRightOpacity;
        }
        if(window.scrollRightSlowBackground) {
            host.content.findName("scrollRightSlow")["Background"] = scrollRightSlowBackground;
        }
        if(window.scrollRightSlowOpacity) {
            host.content.findName("scrollRightSlow")["Opacity"] = scrollRightOpacity;
        }
        if(window.albumViewBackground) {
            host.content.findName("albumView")["Background"] = albumViewBackground;
        }
    }

    function overrideSizes() {
        host.content.findName("parentCanvas")["Width"] = parentCanvasWidth;
        host.content.findName("parentCanvas")["Height"] = parentCanvasHeight;
        host.content.findName("Photo")["Width"] = PhotoWidth;
        host.content.findName("Photo")["Height"] = PhotoHeight;
        
        AlbumsHeight = PhotoHeight;
        AlbumsWidth = parentCanvasWidth - PhotoWidth - padding;
        var Albums = host.content.findName("Albums")
        Albums.Width = AlbumsWidth;
        Albums.Height = AlbumsHeight;
        Albums["Canvas.Left"] = PhotoWidth + padding;
        
        var AlbumItems = host.content.findName("AlbumItems");
        AlbumItems.Width = parentCanvasWidth;
        AlbumItemsHeight = parentCanvasHeight - PhotoHeight - padding;
        AlbumItems.Height = AlbumItemsHeight;
        AlbumItems["Canvas.Top"] = PhotoHeight + padding;
        
        ThumbinalHeight = AlbumItemsHeight - (2*padding);
        ThumbinalWidth = ThumbinalHeight * (800/600); // typowe ratio
        
        AlbumItemsWidth = parentCanvasWidth-PhotoWidth-padding;
        
        host.content.findName("nextButton")["Canvas.Left"] = PhotoWidth  - 30;
        
        host.content.findName("nextButton")["Height"] = PhotoHeight - (4*padding);
        host.content.findName("prevButton")["Height"] = PhotoHeight - (4*padding);

        var scrollLeft = host.content.findName("scrollLeft");
        var scrollLeftSlow = host.content.findName("scrollLeftSlow");
        var scrollRight = host.content.findName("scrollRight");
        var scrollRightSlow = host.content.findName("scrollRightSlow");
        scrollLeft["Canvas.Top"] = PhotoHeight;
        scrollLeft["Height"] = AlbumItemsHeight;
        scrollLeftSlow["Canvas.Top"] = PhotoHeight;
        scrollLeftSlow["Height"] = AlbumItemsHeight;
        scrollRight["Canvas.Top"] = PhotoHeight;
        scrollRight["Canvas.Left"] = parentCanvasWidth - 20;
        scrollRight["Height"] = AlbumItemsHeight;
        scrollRightSlow["Canvas.Top"] = PhotoHeight;
        scrollRightSlow["Canvas.Left"] = parentCanvasWidth - 2* 20;
        scrollRightSlow["Height"] = AlbumItemsHeight;
    }