// JavaScript Document

//Set timing options
var timeDelay = 8500;
//var transitionDelay = 400;
var transitionDelay = 900;
var checkAgainDelay = 1000;

/* ====================================================================================================== */
/* =============================================== FUNCTIONS ============================================ */
/* ====================================================================================================== */
function preLoad (nxt,prv){
	//Preload next and previous images
	nextImageObject = new Image();
	prevImageObject = new Image();	
	nextImageObject.src = '_rd09/images/homepage/slideshow_features/slides/slide'+imgNameArray[nxt]+'.jpg'; 
	prevImageObject.src = '_rd09/images/homepage/slideshow_features/slides/slide'+imgNameArray[prv]+'.jpg'; 
}

//If the photo on the stage is loaded, get the party started, otherwise, wait a bit
function getStarted(){
	//Get the status of the photo currently on the stage
	var slidePhoto = document.getElementById('slideimg');
	var slidePhotoStatus = isImageOk(slidePhoto);
	if(slidePhotoStatus == "complete"){
		//Set the interval for the next transision
		nextInterval = window.setInterval("nextPhoto(0)", timeDelay); 	
	} else {
		//Wait a little longer
		imgWait = setTimeout('getStarted()', checkAgainDelay);				
	}
}
//Events for moving to the next photo
function nextPhoto(button){
	//Dim the photo on the stage
	dimPrevious('next');	
	//If the next button has been clicked, stop automatically rotating images
	if(button == 1){ window.clearInterval(nextInterval); }
	//Wait for the existing image to dim, then load the next image
	setTimeout("loadImage('next')", transitionDelay);	
}
//Events for moving to the previous photo
function prevPhoto(button){
	//Dim the photo on the stage
	dimPrevious();	
	//If the previous button has been clicked, stop automatically rotating images
	if(button == 1){ window.clearInterval(nextInterval); }
	//Wait for the existing image to dim, then load the next image
	setTimeout("loadImage('prev')", transitionDelay);
}

//Dim out the current photo and caption before loading the next one
function dimPrevious(){
	var dimPhoto = opacity('content_slideshow_photos', 100, 0, transitionDelay);
	var dimCaption = opacity('slide_caption', 100, 0, transitionDelay);	
}

//Load the next or previous photo
function loadImage(whereTo){
	//Reset time until next transision -- for slow connections
	clearInterval(nextInterval);	
	//Get the image objects for the image on the stage and the next/previous image
	if(whereTo == "prev"){ 
		var goToImg = prevImg; 
		var goImgObj = prevImageObject;
	} else { 
		var goToImg = nextImg; 
		var goImgObj = nextImageObject;
	}
	//Get the status of the photo currently on the stage
	var slidePhoto = document.getElementById('slideimg');
	var slidePhotoStatus = isImageOk(slidePhoto);
	//Get the status of the requested photo
	var goImgObjStatus = isImageOk(goImgObj);
	//Check if the photo on the stage and the requested photo are loaded, if not, delay, then check again
	if(slidePhotoStatus == "wait" || goImgObjStatus == "wait"){
		//Wait for the delay specified by checkAgainDelay, then retry function
		imgWait = setTimeout('loadImage(\''+whereTo+'\')', checkAgainDelay);
		//Reset time until next transision -- for slow connections
		nextInterval = setInterval("nextPhoto(0)", timeDelay); 
	}else{
		//Reset time until next transision -- for slow connections
		nextInterval = setInterval("nextPhoto(0)", timeDelay); 		
		//Get the divs for photo and caption
		var imgDiv = document.getElementById('content_slideshow_photos');
		var imgCap = document.getElementById('slide_caption');
		//var imgContainer = document.getElementById('');
		//Hide photo and caption
		imgDiv.style.display = "none";
		imgCap.style.display = "none";
		//Change inner HTML of photo div and caption div
		imgDiv.innerHTML = '<img src="_rd09/images/homepage/slideshow_features/slides/slide'+imgNameArray[goToImg]+'.jpg" width="490" height="273" alt="St. Catherine University Photos" id="slideimg" />';
		imgCap.innerHTML = imgCaptionArray[goToImg];
		//Fade-in photo and caption
		opacity('content_slideshow_photos', 0, 100, transitionDelay);
		opacity('slide_caption', 0, 100, transitionDelay);	
		//Redefine current photo
		currentImg = goToImg;
		//Calculate the next image in the order
		if(currentImg == (imgNameLength-1)){ nextImg = 0;
		} else { nextImg = currentImg+1; }
		//Calculate the previous image in the order
		if(currentImg == 0){ prevImg = imgNameLength-1;
		} else { prevImg = currentImg-1; }
		//Preload the new next and previous images
		preLoad(nextImg, prevImg);
	}

}

// Set opacity via fade-through
function opacity(id, opacStart, opacEnd, millisec) { 
    //speed for each frame 
    var speed = Math.round(millisec / 100); 
    var timer = 0; 
    //determine the direction for the blending, if start and end are the same nothing happens 
	//More transparent
    if(opacStart > opacEnd) { 
        for(i = opacStart; i >= opacEnd; i--) { 
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed)); 
            timer++; 
        } 
		if(i = opacEnd){ return "dimmed"; }
	//More opaque	
    } else if(opacStart < opacEnd) { 
        for(i = opacStart; i <= opacEnd; i++) { 
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed)); 
            timer++; 
        } 
		if(i >= opacEnd){ return "opaque"; }		
    } 
} 
//change the opacity for different browsers 
function changeOpac(opacity, id) { 
	if(id != undefined && id != ""){
		var object = document.getElementById(id).style; 
		object.opacity = (opacity / 100); 
		object.MozOpacity = (opacity / 100); 
		object.KhtmlOpacity = (opacity / 100); 
		object.filter = "alpha(opacity=" + opacity + ")";
		object.display = "block";
	}
}

//Cross-browser check to determine if an image has loaded properly
function isImageOk(img) {
    // During the onload event, IE correctly identifies any images that
    // weren't downloaded as not complete. Others should too. Gecko-based
    // browsers act like NS4 in that they report this incorrectly.
    if (!img.complete) {
        return "wait";
    }

    // However, they do have two very useful properties: naturalWidth and
    // naturalHeight. These give the true size of the image. If it failed
    // to load, either of these should be zero.
    if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) {
        return "wait";
    }

    // No other way of checking: assume it's ok.
    return "complete";
}


/* ====================================================================================================== */
/* =========================================== PROGRAM LOGIC ============================================ */
/* ====================================================================================================== */
//Check, make sure page is loaded before preloading or messing with the other photos
DomReady.ready(function() {
	//Get number of images
	imgNameLength = imgNameArray.length;
	//Calculate the next image in the order
	if(currentImg == (imgNameLength-1)){ nextImg = 0; } else { nextImg = currentImg + 1; }
	//Calculate the previous image in the order
	if(currentImg == 0){ prevImg = imgNameLength-1;	} else { prevImg = currentImg-1; }
	//Initialize uiStatus variable
	uiStatus = "";
	//Run the preload function
	preLoad(nextImg, prevImg);
	//If the photo on the stage is loaded, get the party started, otherwise, wait a bit
	getStarted();
});


