﻿/*

    NEEDS A STRUCTURE LIKE THIS!

    you can move the the items around, but they must have these class names

    <div id="gallery">
    
        <a class="gallery-play" href="#">Play</a>
        <a class="gallery-pause" style="display: none" href="#">Pause</a>
        <a class="gallery-prev" href="#">Prev</a>
        <a class="gallery-next" href="#">Next</a>
        <span class="gallery-status"></span>
    
        <div class="gallery-image">
        </div>
        
        <div class="gallery-blurb">
            <div class="gallery-description"></div>
            <div class="gallery-credit"></div>
        </div>
    
        <div class="gallery-thumbnails">
            <a href="#" class="gallery-prev-page">Prev page</a>
            <a href="#" class="gallery-next-page">Next page</a>
            <div class="gallery-scroller">
            </div>
        </div>
    
    </div>
    
*/

/* globals */

var gallery;

var current = 0;        // Starting current thumb
var howmany = 10;        // How many thumbs to show
var total;         // The total number of thumbs (will be worked out in working gallery)
var currentPage = 0;    // The current page of thumbs to show
var timeout = 4000;     // Time between change in the playback mode

// automated globals
//data: galleryParams,
var totalPages;

/* Initialise gallery */

$(document).ready(function(){

    gallery = $("#gallery");
    
    // Get the photos
    $.ajax({
	    url: "gallery_json.aspx",
	    dataType: 'json',
        data: galleryParams,
	    success: function(data) {
		    pics = data;
		    buildgallery();
	    },
	    error: function(request,error) {
	        if(request) {
	            console.log(request);
	        }
	        if(error) {
	            console.log(error);
	        }     
	    }
    });


}); 

/* Gallery functions */

// Function to setup the gallery, called from the AJAX result

buildgallery = function() {

    var photos = pics.album.photos;

    total = pics.album.photos.length;
    totalPages = Math.floor(total / howmany);
    
    // Set the heading
    $("h1.AlbumTitle").text(URLDecode(pics.album.title));
    $("P.AlbumDescription").text(URLDecode(pics.album.description));
    $("span.ProductionTitle").text(URLDecode(pics.album.productiontitle));
    $("a.ProductionID").text("/tour_details.aspx?ID=" + URLDecode(pics.album.productionid));

     // Create the list
    var imagemaxheight = 0;
    var scroller = gallery.find(".gallery-scroller");
    var list = $("<ul></ul>");
    for(var i = 0; i < total; i++) {
        thumb = '<img src="' + photos[i].thumbnail_path + '" alt="' + URLDecode(photos[i].title) + '" />';
        list.append('<li id="pic'+i+'">'+ thumb +'</li>');
        // Find the largest height
        if(photos[i].height > imagemaxheight) {
           imagemaxheight = photos[i].height;
        }
    }
    scroller.append(list);
    
    // Add an image to the pic frame and set the frame height
    gallery.find(".gallery-image").height(imagemaxheight + "px").html("<img/>");
    
    // Set the scroller size based on how many li's are showing
    
    var desiredwidth = (scroller.find("li").outerWidth(true) * howmany) - (scroller.find("li").outerWidth(true) - scroller.find("li").outerWidth());
    scroller.css("width",desiredwidth + "px");
    
    // Bind the next and previous links
    
    gallery.find(".gallery-next-page").click(nextPage);
    gallery.find(".gallery-prev-page").click(prevPage);
    gallery.find(".gallery-next").click(nextImage);
    gallery.find(".gallery-prev").click(prevImage);
    gallery.find(".gallery-play").click(play);
    gallery.find(".gallery-pause").click(pause);
    
	// Bind the arrow keys to previous and next actions
    $().keydown(function(e){
        // Left arrow
        if(e.keyCode == 37) {
            prevImage();
        }
        /// Right arrow
        if(e.keyCode == 39) {
            nextImage();
        }
    });

    // Clicking on a li changes it to the current one 
    
    scroller.find("li").click(function(){
        var changeto = $(this).attr("id").split("pic")[1];
        change(changeto);
    });
    
	// If a hash is passed in the URL, change to that photo, otherwise change to the first in the list
	var hash = document.location.toString().split('#')[1];
	if(hash) {
	    change(hash.split("pic")[1]);
	} else {
	    change(0);
	}

}

// Function to change the current element

change = function(number) {
    number = parseInt(number);
    if(number >= 0 && number < pics.album.photos.length) {
        
        /* Scroller */
        
        var scroller = gallery.find(".gallery-scroller");
        
        // Set the current var
        current = number;
        
        // Set the thumbnail class to current
        
        scroller.find("li.current").removeClass("current");
        scroller.find("li#pic"+number).addClass("current");
        
        // Move the scroller to show the current box
        
        var page = Math.floor(number / howmany);
        if(page != currentPage) {
            changePage(page);
        }
        
        /* Photo */
        
        var currentphoto = pics.album.photos[number];
        
        // Change the blurb
        
        gallery.find(".gallery-description").html("<h2>"+URLDecode(currentphoto.title)+"</h2>"+"<p>"+URLDecode(currentphoto.description)+"</p>");
        gallery.find(".gallery-status").text((number+1) +" of "+ pics.album.photos.length);
        if(currentphoto.credit) {
            gallery.find(".gallery-credit").html("<em>Credit: " + currentphoto.credit + "</em>");
        } else {
            gallery.find(".gallery-credit").html("");
        }
        
        // Change the image
        
        gallery.find(".gallery-image").find("img")
            .fadeOut("fast",function(){
                $(this).attr({ src: currentphoto.photo, alt: URLDecode(currentphoto.title) }).load(function(){
                    $(this).fadeIn("fast");
                });
            })
    };
};

// Previous image

nextImage = function() {
    change(current + 1);
    return false;
};

// Next image

prevImage = function() {
    change(current - 1);
    return false;
};

// Play through images

play = function() {
    timer = setInterval(nextImage,timeout);
    gallery.find(".gallery-play").hide();
    gallery.find(".gallery-pause").show();
    return false;
}

// Pause playback

pause = function() {
    clearInterval(timer);
    gallery.find(".gallery-play").show();
    gallery.find(".gallery-pause").hide();
    return false;
}

/* Scroller functions */

// Change page

changePage = function(page) {
    // If the page is in range, scroll to it, and update the currentPage marker
    if(page >= 0 && page <= totalPages) {
        gallery.find(".gallery-scroller").scrollTo('li#pic'+page*howmany,500,{ axis: 'x' });
        currentPage = page;
    };
};

// Change to the next page of thumbs

nextPage = function() {
    changePage(currentPage +1);
    return false;
};

// Change to the previous page of thumbs

prevPage = function() {
    changePage(currentPage -1);
    return false;
};

/* Utility functions */

// Decode URL encoded strings

function URLDecode(url) {
    // Replace + with ' '
    // Replace %xx with equivalent character
    // Put [ERROR] in output if %xx is invalid.
    var HEXCHARS = "0123456789ABCDEFabcdef";
    var encoded = url;
    var plaintext = "";
    var i = 0;
    while (i < encoded.length) {
        var ch = encoded.charAt(i);
        if (ch == "+") {
            plaintext += " ";
            i++;
        } else if (ch == "%") {
            if (i < (encoded.length-2)
                && HEXCHARS.indexOf(encoded.charAt(i+1)) != -1
                && HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
                plaintext += unescape( encoded.substr(i,3) );
                i += 3;
            } else {
            alert( 'Bad escape combination near ...' + encoded.substr(i) );
            plaintext += "%[ERROR]";
            i++;
            }
        } else {
            plaintext += ch;
            i++;
        }
    }

    return plaintext;
};
