var currItemIndex = 0;
var storyItemsArray = new Array();
var currStoryId = null;

function loadPortfolio() {
      Element.show('storyCover');
      Element.hide('gallery_thumbs');
      new Effect.Grow('gallery_thumbs');
      new Effect.Fade('storyCover');
}

function loadStory(storyId, loadFirstVsLast) {
//Loads all the images/videos of a story (so they're ready to be navigated through)
// and displays the first one or the last one (depending on the value of loadFirstVsLast arg:
// if loadFirstVsLast==TRUE or undefined, load first; if loadFirstVsLast==FALSE, load last.
//This function is triggered when the user clicks a story's thumbnail at bottom of the page,
// or when user flips to the "next" item from the last item in a story, 
// or flips to the "previous" item from the first item in a story.
    
    //Provide "default value" for "optional arg" if not provided
    if (typeof loadFirstVsLast == 'undefined' ) loadFirstVsLast = true;
    
    currStoryId = storyId; //So the rollovers know not to do anything on the currently-selected story
    
    SetOpacities(storyId);
    
   	//"Cover up" the main image or video so it doesn't blink during laoding:
   	new Effect.Appear('imgCover', {duration: 1});

     //Wait for effect to complete before continuing execution
    setTimeout(function() { //Note that we put the rest of our code in an anonymous function,
                            // so that we don't have to have a separate function with a stupid name like "part_two".

    //"Erase" existing item id's in the js array (and on the page's img src's if images)
    if (!portfolio_is_video) {
		$('mainImages').innerHTML = '';
	}
    storyItemsArray.length = 0;
    
    //Get a list of urls and ids for images/videos in the given story
    // -- when this is done, the showStory() function will be called to complete the job.
    var url = 'ajax/portfolio.loadstory.php';
    var params = 'video=' + (portfolio_is_video ? '1' : '0')
			   + '&s=' + storyId;
    var myAjax = new Ajax.Request(
        url, 
      	{
      		method: 'get', 
      		parameters: params,
      		onSuccess: function(request) {
      		    var storyItems = eval('(' + request.responseText + ')'); //Convert JSON string to array
      		    showStory(storyItems, loadFirstVsLast);
  		    }
  		    //Note that failure to retrieve image/video data results in "nothing happening" -- image area on page stays blank.
      	});    

    }, 1000); //setTimeout() duration
}

function SetOpacities(storyId) {
//Sets the opacity of the given story thumbnail to 1.0, and the opacity for all other thumbnails to 0.3
    var selectStoryId = 'thumb_'+storyId;
    new Effect.Appear(selectStoryId, {from: 0.5, to: 1.0, duration: 2.0});
    var thumbs = $$('div.story');
    thumbs.each(function(elmt) {
        if ((elmt.id != selectStoryId) && (Element.getOpacity(elmt.id) > 0.9)) { //NOTE: "Full" opacity is sometimes 0.9999 instead of 1.0!
            new Effect.Fade(elmt.id, {from: 1.0, to: 0.5, duration: 0.5});
        }
    });
}

function showStory(storyItems, loadFirstVsLast) {
//This function takes an array of data pertaining to the images or videos of the currently-loaded story,
// puts their id's into our global array of item id's,
// then if applicable (if images) it writes <img> tags for them to the DOM (although display is hidden), 
// then shows the first or last item in the array (depending on value
//   of loadFirstVsLast arg -- TRUE or undefined means load first, FALSE means load last).
//This is called when ajax completes from loadStory().

    //Provide "default value" for "optional arg" if not provided
    if (typeof loadFirstVsLast == 'undefined' ) loadFirstVsLast = true;

	if (portfolio_is_video) {
		storyItems.each(function(video, idx) {
			storyItemsArray[idx] = video;
		});
	} else {
	    //Loop through response object and put its img id's and src's in various places
	    var newMainImagesHtml = '';
	    var imgLeft = 0;
	    var imgTop = 0;
	    storyItems.each(function(img, idx) {
	        storyItemsArray[idx] = img.imgId;
	        imgLeft = ((644 - img.imgWidth) / 2);
	        imgTop = ((430 - img.imgHeight) / 2); //NOTE: We are NOT vertically aligning for now, but this is here for future use if we cahgne our mind.
	        newMainImagesHtml = newMainImagesHtml
	                          + '<img src="' + img.imgUrl + '"'
	                          + ' id="img_' + img.imgId + '"'
	                          + ' style="display:none; position:absolute; top:0px; left:'+imgLeft+'px;"'
	                          + ' border="0"'
	                          + ' />';
	    });

	    //Write the new img src'es to the page so they are forced to load now
	    $('mainImages').innerHTML = newMainImagesHtml;
	}
    
    //Show the first or last image in the story
    currItemIndex = loadFirstVsLast ? 0 : storyItemsArray.length - 1;

	if (portfolio_is_video) {
		loadVideo('../'+storyItemsArray[currItemIndex].videoUrl, storyItemsArray[currItemIndex].imageUrl, 2500);
	} else {
		Element.show('img_'+storyItemsArray[currItemIndex]);
	}
    
	setTimeout(function() {
        new Effect.Fade('imgCover', {duration: 1});
    }, 2000);

    setTimeout(function() {
        document['imgCover'].src = 'images/nav/imgLoad.gif';
    }, 1000);
}

function hilightThumb(on_vs_off, storyId) {
//Pass TRUE for on_vs_off to hilight the thumbnail, pass FALSE to un-hilight the thumbnail.
//We will determine if the given id is for the currently-selected story, and if so we will NOT do the hilight.
    var selectStoryId = 'thumb_'+storyId;

    if (currStoryId != storyId) {
        if (on_vs_off) {
            Element.setOpacity(selectStoryId, 0.9999); //Safari doesn't like opacity 1.0 (?!?!)
        } else {
            Element.setOpacity(selectStoryId, 0.5);
        }
    }
}

function swap(next) {
//Shows a different image or video in the main image container
//Pass 1 for "next" item, -1 for "previous" item.
//If currently viewing the "last" item of a story and you want to show the "next" item,
// we will actually load the first item of the next story. Similarly, if viewing the "first"
// item of a story and you want to show the "previous" item, we will actually load the 
// last item of the previous story.
    
    if ((next == -1) && (currItemIndex == 0)) {
        //at first item, load last item of "previous" story
        var newStoryId = getNextOrPrevStoryId(next);
        loadStory(newStoryId, false);
    } else if ((next == 1) && (currItemIndex == storyItemsArray.length - 1)) {
        //at last item, load first item of "next" story
        var newStoryId = getNextOrPrevStoryId(next);
        loadStory(newStoryId, true);
    } else {
        //in middle of story, load next/prev item in current story
		var newItemIndex = getNextOrPrevItemIndex(next);
		if (portfolio_is_video) {
			new Effect.Appear('imgCover', {duration: 0.25});
			setTimeout(function() {
				loadVideo('../'+storyItemsArray[newItemIndex].videoUrl, storyItemsArray[newItemIndex].imageUrl, 1500);
			}, 250);
			setTimeout(function() {
				new Effect.Fade('imgCover', {duration: 1});
			}, 1500);
		} else {
	        var currImg = 'img_'+storyItemsArray[currItemIndex];
	        var newImg = 'img_'+storyItemsArray[newItemIndex];
	        new Effect.Fade(currImg, {duration: 0.75});
	        new Effect.Appear(newImg, {duration: 0.75});
		}
        currItemIndex = newItemIndex;
    }
}

function getNextOrPrevItemIndex(next) {
//Pass 1 for "next" item in the story, -1 for "previous" item in the story.
//Note that we are basing our calculations off of the global vars at the top of this script.
//ALSO NOTE that we do NOT deal with the logic of flipping stories when the last item of this story
// is reached -- instead we "wrap-around" within the current story -- if we are currently
// at the "last" item of the story, we return the index of the "first" item in the story (and vice-versa)!
    
    var nextImgIndex;
    
  	if (next == 1) {
        if (currItemIndex == storyItemsArray.length - 1) {
            nextImgIndex = 0;
        } else {
            nextImgIndex = currItemIndex + 1;
        }
    } else {
        if (currItemIndex == 0) {
            nextImgIndex = storyItemsArray.length - 1;
        } else {
            nextImgIndex = currItemIndex - 1;
        }
    }
    
    return nextImgIndex;
}

function getNextOrPrevStoryId(next) {
//Pass 1 for "next" story, -1 for "previous" story.
//Note that we assume a global array called "portfolioStoryIds" has been defined in the html head somewhere!
//We will "wrap-around" within the stories of the current portfolio -- if we are currently showing the "last" 
// story in the portfolio and you want to get the "next" story, we return the id of the first story in the portfolio
// (and vice-versa).

    var nextStoryIndex = 0; //0 is just default value in case something goes wrong -- should never happen though.
    var currStoryIndex = portfolioStoryIds.indexOf(currStoryId);

  	if (next == 1) {
  	    if (currStoryIndex == portfolioStoryIds.length - 1) {
  	        nextStoryIndex = 0;
        } else {
            nextStoryIndex = currStoryIndex + 1;
        }
    } else {
        if (currStoryIndex == 0) {
            nextStoryIndex = portfolioStoryIds.length - 1;
        } else {
            nextStoryIndex = currStoryIndex - 1;
        }
    }
    
    return portfolioStoryIds[nextStoryIndex];
}

function loadVideo(videoUrl, imageUrl, delay) {
	try {
		so.write('player'); //Re-embed the flash player to avoid flicker when play button is hit.
		setTimeout(function() { //This delay is so the above call to so.write('player') has some time to finish -- not sure why it needs this, but without this delay, this doesn't work.
			$('mpl').sendEvent('LOAD', {file:videoUrl, image:imageUrl});
		}, delay);
		
	} catch (e) {
		//do nothing -- this probably means flash is not installed, in which case an appropriate message is displayed by the flash loader.
	}
}

