
var scrollbarInitTimerId = 0;
var scrollbarInitTimerRetry = 10;
var scrollbarInitTimerCount = 0;

(function($){
	$.fn.GlobalNextPreviousButtons = function($options)
	{
		log('Begin GlobalNextPreviousButtons');
		
		var activeLink = null; // the activeLink jQuery object
		var activeLinkLevel = 0; // equates to index in levelSelectors array
		var activeLinkIndex = 0; // position of active link within linksArray
		var linksArray = [];
		
		var $defaults = {
			nextButtonSelector  : 'a#nextButton',
			prevButtonSelector  : 'a#prevButton',
			levelSelectors : [
				'.level1',
				'.level2',
				'.level3',
				'.level4',
				'.level5'
			]
		};

		// extend the options
		var $opts = $.extend($defaults, $options);

		// bring the options to the galleria object
		for (var i in $opts) {
			if (i) {
				$.GlobalNextPreviousButtons[i]  = $opts[i];
			}
		}
		
		log($opts);
		
		var findActiveLinks = function(context) {
			
			// Find all of the links for each level
			
			var max = $opts.levelSelectors.length;
			
			linksArray = [];
			
			for( var i = 0; i < max; i++) {
				log('processing ' + $opts.levelSelectors[i]);
				
				var linkContainer = $($opts.levelSelectors[i], context);
				var theseLinks = $('a', linkContainer);
				
				if(theseLinks.length > 0) {
					log($opts.levelSelectors[i] + ' - found ' + theseLinks.length + ' links');
					// log(theseLinks);
					
					linksArray[i] = theseLinks;
					
					for(var k = 0; k < theseLinks.length; k++) {
						if( $(theseLinks[k]).hasClass('active')) {
							thisActiveLink = theseLinks[k];
							activeLink = thisActiveLink;
							activeLinkLevel = i;
							activeLinkIndex = k;
						}
					}
				}
			}
			
			log('active link [' + activeLinkLevel + '][' + activeLinkIndex + '] =');
			log(activeLink);
			
			findNextLink();
			
			findPreviousLink();
		};
		
		var findPreviousLink = function() {
			// The PREV item is either this links prev sibling or
			// the prev nav lists last item
			
			var prevLink = null;
			var markLastItem = false;
			
			// This first fork one was a bad idea...ignore it!
			//
			// If there is nav deeper than the current and NONE of them are
			// active, then that is navigation we have yet to traverse...
			
			/*if( (activeLinkIndex > 0) && (linksArray.length - 1 >= activeLinkLevel + 1) ) {
				log('looking for next level link');
				var noneActive = true;
				for(var j = 0; j < linksArray.length; j++) {
					if( $(linksArray[activeLinkLevel + 1][j]).hasClass('active')) { noneActive = false; }
				}
				if(noneActive) {
					prevLink = linksArray[activeLinkLevel+1][ linksArray[activeLinkLevel+1].length-1 ];
				}
			}*/
			
			
			if(activeLink === null && (linksArray.length > 0)) {
				prevLink = linksArray[0][ linksArray[0].length-1 ];
			}
			
			// If there is an item next to the current, use it
			
			if(prevLink === null && activeLinkIndex-1 >= 0) {
				log('PREV: using prev item in SAME level [' + activeLinkLevel + '][' + (activeLinkIndex-1) + ']');
				prevLink = linksArray[activeLinkLevel][activeLinkIndex-1];
			}
			
			// Traverse the parent levels and find the prev available
			// active link
			
			if (prevLink === null) {
				for(var j = activeLinkLevel-1; j >= 0; j--) {
					
					if(prevLink != null) break; // we found it last iteration
					
					for( var i = 1; i < linksArray[j].length; i++) {
						//log('checking item ' + i + ' which is:');
						//log(linksArray[0][i]);
						if( $(linksArray[j][i]).hasClass('active')) {
							log('PREV: using item [' + (i-1) + '][' + j + ']');
							prevLink = linksArray[j][i-1];
							//markLastItem = true;
							break;
						}
					}
					
				}
				
				// If NO link was found, then go to the very first
				
				if(prevLink === null) {
					log('using last item of first level');
					var lastItemLength = linksArray[ 0 ].length - 1;
					prevLink = linksArray[ 0 ][ lastItemLength ];
					//markLastItem = true;
				}
			}
			
			log('PREV link:');
			log(prevLink);
			
			href = $(prevLink).attr('href');
			//if(markLastItem) {
				href += '&last=true';
			//}
			
			$($opts.prevButtonSelector).attr('href', href);
		};
		
		var findNextLink = function() {
			// The NEXT item is either this links next sibling or
			// the next nav lists first item
			
			var nextLink = null;
			
			
			if(activeLink === null && (linksArray.length > 0)) {
				nextLink = linksArray[0][0];
			}
			
			// If there is a deeper item that we can drill down into then do that
			
			if(nextLink === null && activeLinkLevel < linksArray.length-1) {
				nextLink = linksArray[activeLinkLevel+1][0];
			}
			
			// If there is an item next to the current, use it
			
			if(nextLink === null && linksArray[activeLinkLevel].length-1 >= activeLinkIndex+1) {
				log('NEXT: using next item in SAME level [' + activeLinkLevel + '][' + (activeLinkIndex+1) + ']');
				log('that level contains:');
				log(linksArray[activeLinkLevel]);
				nextLink = linksArray[activeLinkLevel][activeLinkIndex+1];
			}
			
			// Traverse the parent levels and find the next available
			// active link
			
			else {
				for(var j = activeLinkLevel-1; j >= 0; j--) {
					
					if(nextLink != null) break; // we found it last iteration
					
					for( var i = 0; i < linksArray[j].length-1; i++) {
						if( $(linksArray[j][i]).hasClass('active')) {
							log('NEXT: using item [' + (i+1) + '][' + j + ']');
							nextLink = linksArray[j][i+1];
							break;
						}
					}
					
				}
				
				// If NO link was found, then go to the very first
				
				if(nextLink === null) {
					nextLink = linksArray[0][0];
				}
			}
			
			log('NEXT link:');
			log(nextLink);
			
			$($opts.nextButtonSelector).attr('href', $(nextLink).attr('href'));
		};
		
		findActiveLinks(this);
		
		log('End GlobalNextPreviousButtons');
		
		return this;
	}
	
	// Extend plugin here
	
	$.extend({GlobalNextPreviousButtons : {
		
		sample : function(event, id) {
			
		},
		
		otherSample : function() {
			
		}
		
	}
	});
})(jQuery);

$(document).ready( function() {
	$('body').GlobalNextPreviousButtons({
		nextButtonSelector  : 'div.right-arrow > a',
		prevButtonSelector  : 'div.left-arrow > a',
		levelSelectors : [
			'.nav1',
			'.nav2',
			'.nav3',
			'.nav4',
			'.nav5'
		]
	});
	
	$(document).bind("AJAX_CONTENT_REFRESHED", onGlobalNextPreviousButtonsUpdate);
});

function onGlobalNextPreviousButtonsUpdate(event, data) {
	log('onGlobalNextPreviousButtonsUpdate');
	//log('data:');
	//log(data);
	
	// Initialize the next/prev nav
	
	$('body').GlobalNextPreviousButtons({
		nextButtonSelector  : 'div.right-arrow > a',
		prevButtonSelector  : 'div.left-arrow > a',
		levelSelectors : [
			'.nav1',
			'.nav2',
			'.nav3',
			'.nav4',
			'.nav5'
		]
	});
	
	initScrollbars();
}

/**
 * Initialize our javascript scrollbars within the site
 * 
 * We must check to be sure that all images have loaded into the site before we run
 * the init script. This function checks for all images on the site. If loaded, then
 * the scrollbars are initialized. Otherwise it creates a timer and checks back
 * to see if the images are loaded at a later time.
 * 
 * @since 11 Feb 2010
 */
function initScrollbars() {
	clearTimeout ( scrollbarInitTimerId );
	var count = document.images.length;
	var loaded = 0;
	for (var i = 0; i < count; i++) {
		// log('checking item ' + i + ', ' + document.images[i].src)
		if (IsImageOk(document.images[i])) {
			loaded++;
			// log('image ' + document.images[i] + ' is loaded');
		}
	}
	// log(count + ' images found');
	// log(loaded + ' images loaded');
	
	// log('scrollbarInitTimerCount = ' + scrollbarInitTimerCount);
	// log('scrollbarInitTimerRetry =' + scrollbarInitTimerRetry);
	
	// We check to see if all the images are loaded.
	// If they are loaded, or if this script has looped to many times
	// and we think that the image wont load or the user will not wait that long
	// then init the scroll bar. Otherwise try again with another timer.
	
	if(count > loaded && (scrollbarInitTimerCount < scrollbarInitTimerRetry)) {
		scrollbarInitTimerCount++;
		scrollbarInitTimerId = setTimeout ( "initScrollbars()", 200 );
	}
	else {
		scrollbarInitTimerCount = 0;
		VSA_initScrollbars();
	}
}

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) {
		// log('incomplete');
        return false;
    }
    // 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) {
		// log('naturalWidth not defined');
        return false;
    }
    // No other way of checking: assume it’s ok.
    return true;
}

function onScrollContentInit(event, target) {
	//log('onScrollContentInit');
	//log(target);
	$('a.ajax', target).click( onAjaxLinkClicked );
}


$(document).bind("SCROLL_INIT", onScrollContentInit);
