
var BasePath="fotos/";


var FADE_STEP = 2; // in percentage opacity
var FADE_TIME = 500; // in milliseconds
var FADE_INTERVAL = 10; // in milliseconds
var AUTO_PLAY_INTERVAL = 5000; // in milliseconds

//==============================================================================
// end configuration, do not modify below this line
//==============================================================================

var visible=false; // indicates whether slideshow is visible or not
// visible == true if ...
//  - slideshow is completely faded in
//  - slideshow is currently busy fading in
var fading=false; // indicates whether slideshow is currently fading in or out
var fadeTimer=null;
var fadeStart=null;
var crossfadeTimer=null;
var crossfadeStart=null;
var autoPlayTimer=null;

var currDiv=0; // which image div is currently visible
// during crossfading, currDiv has the value of the image currently fading in

var showOpacity = 0; // opacity of the complete slideshow
var opacities = new Array(0, 0); // the opacities of both image divs, on a scale
    // from 0 to 100.
var photos = new Array(null,null); // the URLs of the photos currently loaded
//var descriptions = new Array(null,null); // the descriptions of the photos currently loaded
var newPhoto = null; // the photo to be loaded when the current crossfade is finished
var series; // the id of the series we're viewing

var photoList = null;
var currPos = null;

var prevImg = new Image(); // hold previous and next image data
var nextImg = new Image(); // these are preloaded for a better experience

var prevHTML = null; // The contents of slideshowprev
var nextHTML = null; // The contents of slideshownext

var prevButImg = new Image(); // preload all buttons
var prevButHoverImg = new Image();
var nextButImg = new Image();
var nextButHoverImg = new Image();
var closeButImg = new Image();
var closeButHoverImg = new Image();
prevButImg.src = BasePath + "../images/slideshow_vorige.png";
prevButHoverImg.src = BasePath + "../images/slideshow_vorige_hover.png";
nextButImg.src = BasePath + "../images/slideshow_volgende.png";
nextButHoverImg.src = BasePath + "../images/slideshow_volgende_hover.png";
closeButImg.src = BasePath + "../images/slideshow_sluiten.png";
closeButHoverImg.src = BasePath + "../images/slideshow_sluiten_hover.png";

// Sets a list of all IDs of photos in this series. This is used for prev/next buttons.
function setPhotoList(theList) {
    photoList = theList;
}

function setPrevNext(id) {
    var i = null;
    // search id in photoList
    if (currPos != null) {
        // first see if id is adjacent to the current photo (optimization)
        if (photoList[currPos].id == id) {
            i = currPos;
        } else if (currPos > 0 && photoList[currPos-1].id == id) {
            i = currPos-1;
        } else if (currPos < photoList.length - 1 && photoList[currPos+1].id == id) {
            i = currPos+1;
        }
    }
    if (i == null) {
        // search the whole list until we find the right id
        for (i = 0; i < photoList.length; i++) {
            if (photoList[i].id == id) {
                break; // keep this value for i
            }
        }
        if (i >= photoList.length) { // id not found
            return false;
        }
    }
    // now that we know where id is in the list, set prev/next buttons
    if (i > 0) { // there is a previous photo, show the button
        if (prevHTML != null) {
            document.getElementById('slideshowprev').innerHTML = prevHTML;
        }
        prevImg.src = BasePath + "/" + series + "/foto_" + photoList[i-1].id + ".jpg"; // prefetch the right images
    } else { // no previous photo, hide the button
        if (document.getElementById('slideshowprev').innerHTML != '') {
            prevHTML = document.getElementById('slideshowprev').innerHTML;
        }
        document.getElementById('slideshowprev').innerHTML = '';
    }
    if (i < photoList.length-1) { // there is a next photo, show the button
        if (nextHTML != null) {
            document.getElementById('slideshownext').innerHTML = nextHTML;
        }
        nextImg.src = BasePath + "/" + series + "/foto_" + photoList[i+1].id + ".jpg"; // prefetch the right images
    } else { // no next photo, hide the button
        if (document.getElementById('slideshownext').innerHTML != '') {
            nextHTML = document.getElementById('slideshownext').innerHTML;
        }
        document.getElementById('slideshownext').innerHTML = '';
    }
    currPos = i; // save the position we're now at

}

function autoPlay(doPlay) {
	if (doPlay) {
		document.getElementById('playpause').innerHTML =
				'<img src="images/slideshow_pause.png" alt="pauzeren" onclick="autoPlay(false);" onmouseover="this.src=\'images/slideshow_pause_hover.png\';" onmouseout="this.src=\'images/slideshow_pause.png\';" />';
		nextPhoto(false);
		autoPlayTimer = setInterval("nextPhoto(false)",AUTO_PLAY_INTERVAL);
	} else {
		document.getElementById('playpause').innerHTML =
				'<img src="images/slideshow_play.png" alt="afspelen" onclick="autoPlay(true);" onmouseover="this.src=\'images/slideshow_play_hover.png\';" onmouseout="this.src=\'images/slideshow_play.png\';"/>';
		clearInterval(autoPlayTimer);
        autoPlayTimer = null;
	}
}

function prevPhoto(stopAutoPlay) {
    if (currPos > 0) {
        showPhoto(series, photoList[currPos-1]);
    }
    if (stopAutoPlay) {
    	autoPlay(false);
    }
}

function nextPhoto(stopAutoPlay) {
    if (currPos < photoList.length-1) {
        showPhoto(series, photoList[currPos+1]);
    }
    if (stopAutoPlay) {
    	autoPlay(false);
    }
}

function showPhoto(s, photo) { // series and photo id+description
    // first check whether the slideshow fits in the window
    if (getViewportHeight() < document.getElementById('slideshow').offsetHeight || !browserOk()) {
        return false;
    }
    series = s;
    setPrevNext(photo.id);
    
    // we should either fade in photo id or crossfade to photo id
    if (!visible) {
        if (fading) { // currently fading out
            // initiate a crossfade and fade in again
            newPhoto = {
            		id: photo.id,
            		url: BasePath + "/" + series + "/foto_" + photo.id + ".jpg",
            		description: photo.description
            };
            if (crossfadeTimer == null) {
            	var date = new Date();
            	crossfadeStart = date.getTime();
                crossfadeTimer=setInterval("crossfade()",FADE_INTERVAL);
            }
        } else {
            // completely faded out, load the selected image and fade in
            photos[currDiv] = BasePath + "/" + series + "/foto_" + photo.id + ".jpg";
            document.getElementById("slideshowimg" + currDiv).innerHTML =
                    "<img src=\"" + photos[currDiv] + "\" alt=\"Foto niet gevonden\">\n";
            jQuery('#slideshowdesc' + currDiv).each(function() {
            	jQuery(this).val(photo.description);
            	jQuery(this).html(photo.description);
            	jQuery(this).attr('title', photo.id);
            	jQuery(this).parent().children('.status').html('');
            });
        	document.getElementById("slideshowitem" + currDiv).style.display='block';
        	document.getElementById("slideshowitem" + (1-currDiv)).style.display='none';
            setOpacity("slideshowitem" + currDiv, 100);
            setOpacity("slideshowitem" + (1-currDiv), 0);
            opacities[currDiv] = 100;
            opacities[1-currDiv] = 0;

            // prepare the slideshow for fading in
            showOpacity=0;
            setOpacity("slideshow", 0);
          	document.getElementById("slideshow").style.visibility = 'visible';
   	        fadeTimer=setInterval("fade()",FADE_INTERVAL);
        }
        visible=true;
        var date = new Date();
        fadeStart = date.getTime();
    } else {
        // faded in or fading in
        // initiate a crossfade
    	newPhoto = {
        		id: photo.id,
        		url: BasePath + "/" + series + "/foto_" + photo.id + ".jpg",
        		description: photo.description
        };
        if (crossfadeTimer == null) {
        	var date = new Date();
        	crossfadeStart = date.getTime();
            crossfadeTimer=setInterval("crossfade()",FADE_INTERVAL);
        }
    }
    setAdminText(photo.id);
    return true;
}

function hidePhoto() {
    visible=false;
    var date = new Date();
    fadeStart = date.getTime();
    if (fadeTimer == null) {
        fadeTimer = setInterval("fade()",FADE_INTERVAL);
    }
    autoPlay(false);
}

// Shows a "show photo" or "hide photo" link, depending on the visibility
// of the photo with the given ID
function setAdminText(id) {
	if (document.getElementById('slideshowzichtbaarheid') == null) {
		// probably no admin logged in
		return;
	}
	var visible;
	if (document.getElementById('foto_' + id).className == 'foto_verborgen') {
		visible = 0;
	} else {
		visible = 1;
	}
	document.getElementById('slideshowzichtbaarheid').innerHTML =
		'<p class="admin"><a href="fotos_beheer.php?action=foto_zichtbaarheid&amp;id=' +
				id + '&amp;zichtbaar=' + (1-visible) + 
				'" onclick="return photoVisible(' + (1-visible) + '); return true;">' +
				'Foto ' + (visible ? 'verbergen' : 'tonen') + '</a></p>';
}

function saveDescription(form) {
	//alert(jQuery(form).children('[name="omschrijving"]').first().attr('title'));
	jQuery(form).children('.status').html('Opslaan...');
	
	jQuery.post(
			'fotos_beheer_ajax.php?action=edit_foto',
			{
				id: jQuery(form).children('[name="omschrijving"]').first().attr('title'),
				omschrijving: jQuery(form).children('[name="omschrijving"]').first().val()
			},
			function(data) {
				if(typeof(data.error) != 'undefined' && data.error != null) {
					jQuery(form).children('.status').html('Fout');
					alert('Fout bij het opslaan: ' + data.error);
				} else {
					jQuery(form).children('.status').html('Opgeslagen!');
				}
			},
			'json'
	);
	
	return false;
}

// sets the opacity of the element with id "element" to opac,
// with opac on a scale from 0 to 100.
function setOpacity(element, opac) {
    if(document.all) { // ... for IE ...
		document.getElementById(element).style.filter =
                "alpha(opacity=" + opac + ")";
	} else { // ... and for real browsers
		document.getElementById(element).style.opacity = opac/100;
	}
}

function fade() {
    if (visible) { // fading in
        showOpacity += FADE_STEP;
    	var date = new Date();
    	minOpacity = Math.round((date.getTime()-fadeStart)*100/FADE_TIME);
    	showOpacity = Math.max(showOpacity,minOpacity);
        if (showOpacity > 100) { 
            showOpacity = 100;
            fading = false;
            fadeStart = null;
            clearInterval(fadeTimer);
            fadeTimer=null;
        } 
    } else { // fading out
        showOpacity -= FADE_STEP;
    	var date = new Date();
    	maxOpacity = 100-Math.round((date.getTime()-fadeStart)*100/FADE_TIME);
    	showOpacity = Math.min(showOpacity,maxOpacity);
        if (showOpacity < 0) { 
            showOpacity = 0; 
            fading = false;
            fadeStart = null;
            clearInterval(fadeTimer);
            fadeTimer=null;
            // hide everything, fading is done
            document.getElementById("slideshow").style.visibility = 'hidden';
        }
    }
    setOpacity("slideshow", showOpacity);
}

function crossfade() {
	var date = new Date();
	minCrossfadeProgress = Math.round((date.getTime()-crossfadeStart)*100/FADE_TIME);

    if (photos[currDiv]) { // only fade in if a photo is actually loaded
        opacities[currDiv] += FADE_STEP;
    	opacities[currDiv] = Math.max(opacities[currDiv], minCrossfadeProgress);
    } else if (newPhoto) { // we have a new photo to fade in
        // start crossfading to the new photo waiting
        document.getElementById("slideshowimg" + currDiv).innerHTML =
                "<img src=\"" + newPhoto.url + "\" alt=\"Foto niet gevonden\">\n";
        jQuery('#slideshowdesc' + currDiv).each(function() {
        	jQuery(this).val(newPhoto.description);
        	jQuery(this).html(newPhoto.description);
        	jQuery(this).attr('title', newPhoto.id);
        	jQuery(this).parent().children('.status').empty();
        });
        document.getElementById("slideshowitem" + currDiv).style.display='block';
        photos[currDiv] = newPhoto;
        
        var date = new Date();
        crossfadeStart = date.getTime();
        newPhoto = null;
    }

    if (opacities[currDiv] > 100) {
        opacities[currDiv] = 100;
    }
    opacities[1-currDiv] -= FADE_STEP;
    opacities[1-currDiv] = Math.min(opacities[1-currDiv], 100-minCrossfadeProgress);
    if (opacities[1-currDiv] < 0) {
        opacities[1-currDiv] = 0;
    }
    setOpacity("slideshowitem0", opacities[0]);
    setOpacity("slideshowitem1", opacities[1]);
    
    if (opacities[currDiv] == 100 && opacities[1-currDiv] == 0) {
        photos[1-currDiv] = null; // no photo loaded in the faded out div
        
        currDiv = 1 - currDiv; // divs switch roles
        document.getElementById("slideshowitem" + currDiv).style.display='none';
        if (!newPhoto) { // quit fading
        	crossfadeStart = null;
            clearInterval(crossfadeTimer);
            crossfadeTimer = null;
        }
    }
}

function getViewportHeight() {
    // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
    if (typeof window.innerHeight != 'undefined') {
        return window.innerHeight;
    }
    // IE6 in standards compliant mode (i.e. with a valid doctype declaration as the first line in the document)
    else if (typeof document.documentElement != 'undefined'
            && typeof document.documentElement.clientHeight !=
            'undefined' && document.documentElement.clientHeight != 0) {
        return document.documentElement.clientHeight;
    }
    // older versions of IE
    else {
        return document.getElementsByTagName('body')[0].clientHeight;
    }
}

function browserOk () {
	if (navigator.appVersion.indexOf("MSIE") != -1) {
    	// bah, IE again, only allow 8+
    	version = parseFloat(navigator.appVersion.split("MSIE")[1]);
    	return version >= 8;
	}
	// Yay, a real browser
	return true;
}

