//
// Copyright(c) 2008, Melissa Jenkins
// Blacknosugar.com Website Scroller
// All Rights Reserved
//

//
// So we can work in both ie &  ff pass in rather than using globals
var sequenceNumber;
var sequence;
var widths;

var awidths, aheights;
var lefts = [];

//
var topper = 300;
var lyrwidth = 0;
var time; // timer for click scroll
var itime; // timer for delayed colouring on scrollbar
var amount;

//
var leftSide;
var scrollStep;
var theTime;


// how much of the left hand picture should be left on the screen
var leftBuffer = 120;

// at what point should scrolling stop, expressed as the left side of the screen
var leftStop = 0;

function setSequence( seq, mwidths )
{
	// store the sequence
	sequence = seq; widths = mwidths; 
	sequenceNumber = 0;

	// figure out the left offset for each image
	var c = 0;
	for (var i=0; i < sequence.length; i++) {
	    lefts[i] = gObj( sequence[ i ] ).offsetLeft;
	    //		c += 0+widths[i];
	}

	// needed below
	var x = gObj('scroller');
	
	// start out by finding out how big the total scrolling area is
	// we'll need this for the rest of the functions
	lyrheight = x.clientHeight;
	lyrwidth = x.clientWidth;
	
	// how fast are we scrolling accross
	scrollStep = 150;
	theTime = 60;
	
	// and reset the rest of the stuff
	time = 0;
	leftSide = 0;
	
	// setup the scroll bar and hook any changes to the position so we can update the images
	x.scrollLeft = leftSide;
	x.onscroll = updateImages;
	window.onresize = doResize;

}

// get the new window size
function doResize() {
	lyrwidth = gObj('scroller').clientWidth;
}

function showSubAlbums() {

	// there are times when we need to adjust the scroller directly
	var x = gObj('scroller');
	
	index = sequence.left;

	// just before the end of the last picture
	leftStop = lefts[ index ] + widths[ index ];
	leftStop -= leftBuffer;

	// we need to go back as we've scrolled past it
	if( leftSide > leftStop ) {
		amount = - scrollStep;
	}
	else {
		amount = scrollStep;
	}

	// make sure it's not less than 0
	if( leftStop < 0 ) leftStop = 0;
	
	// hack - safari seems to delay sending an onscroll until well after scrolling has finished.
	// by turning off the onscroll notification for a while we don't end up with two coloured
	// images
	if ( $.browser.safari) {
		x.onscroll = null;
	}
	
	
	// actually do some scrolling
	scroll();
}

//
// scroll left or right to the picture index
function goTo( index, jump ) {

	if( ! sequence.length ) {
		return;
	}

	// clear any existing timeout
	clearTimeout( time );
	time = 0;

	if( index == -1 || isNaN(index) ) {
		return;
	}

	// there are times when we need to adjust the scroller directly
	var x = gObj('scroller');
	//	var sbar = gObj( 'rightpanel' );

	// if we are already selected then go directly to the enlarged version
	// jump will only be false if the page is scrolling to it - true basically means
	// coming in from the history or a url link
	if( index == sequenceNumber && jump == false ) {

		//	    x.style.display = "none";
		//	    gObj("sidebar_contents").src = "/image/index.xml?id=" + sequence[ sequenceNumber ] + "&width=" + (lyrwidth*.66);
		//	    sbar.style.display = "block";

		//	    document.title = document.title.replace( / -.*$/, '') + " - " + sequence[ sequenceNumber ] + " details";
	    
	    // we need to set the 
	    return;
	}
	else {
		//	    sbar.style.display = 'none';
	    x.style.display = 'block';
	}

	// stop silly overflow type stuff
	index = index % sequence.length;

	// make the current one grey
	greyImage( sequenceNumber );
		
	// this needs to figure out which way to go
	leftStop = lefts[ index ];
	sequenceNumber = index;
	
	// load images that will become visible before we are done scrolling
	for (var i=sequenceNumber; i < sequence.length; i++) {
		if( lefts[i]  <= (leftStop+lyrwidth+300) ) {
			greyImage( i );
		}
	}

	tempScrollStep = scrollStep;
	if( jump == true ) {
	    x.scrollLeft =  leftStop - leftBuffer;
	    normalImage( sequenceNumber );
	}
	else {
	
	    // we need to go back as we've scrolled past it
	    if( leftSide > leftStop ) {
			amount = - scrollStep;
	    }
	    else {
			amount = scrollStep;
	    }
	    
	    // leave a bit on the left, unless the first picture
	    leftStop -= leftBuffer;
	    if( leftStop < 0 ) leftStop = 0;
		
		// hack - safari seems to delay sending an onscroll until well after scrolling has finished.
		// by turning off the onscroll notification for a while we don't end up with two coloured
		// images
		if ( $.browser.safari) {
			x.onscroll = null;
		}
			
	
	    // actually do some scrolling
	    scroll();
	}
}

function updateImages() {
	
	// this gets called for automated stuff as well so do nothing!
	if( time != 0 ) {
		return;
	}

	if( itime != 0 ) {
		clearTimeout( itime );
		itime = 0;
	}

	//	$('div.sidebar').hide();
	
	var x = gObj('scroller');
	
	// where are we now...
	leftSide = x.scrollLeft;

	// edges
	var wR = leftSide+lyrwidth-leftBuffer;
	var wL = leftSide+leftBuffer;
	
	// which image are we closest to
	var newSequence = 0;
	for (; newSequence < sequence.length; newSequence++) {
		// edges of this picture
		var L = lefts[newSequence];
		var R = L + widths[newSequence];
		
		// two wide for the screen
		if( L < wL && R > wR ) {
			break;
		}

		// first one in the list doesn't have enough margin
		if( newSequence == 0 && L >= leftSide-leftBuffer ) {
			break;
		}
		
		// or first one on the screen
		if( L >= wL && L < wR ) {
			break;
		}
	}

	// don't go past the end
	if( newSequence == sequence.length ) {
		newSequence = sequence.length -1;
	}

	// if we've got a new one then we need to update the colours
	if( newSequence != sequenceNumber ) {
		greyImage( sequenceNumber ) ;
	
		// do it on a timer should help the refresh a bit
		itime =  setTimeout('updateImagesInner(' + newSequence + ')', 400 );
	}
	
	// load the one before the current coloured one as it will be on the screen
	if( sequenceNumber > 0 ) {
		greyImage( sequenceNumber -1 );
	}
}

// called on scroll notifications - responsible for figuring out what picture is active and making it coloured
function updateImagesInner( newSequence ) {
	
	// clear the timer, this will only happen after the right timeout has happened
	itime = 0;
	
	// and load the right one as coloured
	sequenceNumber = newSequence;
	normalImage( sequenceNumber );

	//	$.history.load ( sequenceNumber );
	
	// load images that are almost visible
	for (var i=sequenceNumber+1; i < sequence.length; i++) {
		if( lefts[i]  <= (leftSide+(2*lyrwidth))) {
			greyImage( i ) ;
		}
	}
}

//
// Automatically grey an image
function greyImage( number )
{
	if( isNaN(number) || number < 0 || number >= sequence.length )
		return;
	
	if( gObj( sequence[ number ] + "_inner" ).style.backgroundImage != "url('/images/uploaded/gs_" + sequence[number] + ".jpg' )") {
		gObj( sequence[ number ] + "_inner" ).style.backgroundImage = "url('/images/uploaded/gs_" + sequence[number] + ".jpg' )";
		//		gObj( sequence[ number ] + "_a" ).href= "#" + number;
		gObj( sequence[ number ] + "_outer" ).className = "tipX" + ( number < sequenceNumber ? " leftarrow" : (number > sequenceNumber) ? " rightarrow" : "");
	}

	if( gObj( sequence[ number ] + "_loading" ).style.display != "none" ) {
		gObj( sequence[ number ] + "_loading" ).style.display = "none";
	}
}

// Go through all of the images and make sure they have the right cursor
function setArrows()
{
	for( i = 0; i < sequence.length; i++ ) {
		var newClass = "tip";
		var helptext = "";
		var outer = gObj( sequence[ i ] + "_outer" );
		if( i < sequenceNumber ) {
			newClass = "tipX leftarrow";
			helptext = "/help/previous picture.xml";
		}
		else if( i > sequenceNumber ) {
			newClass = "tipX rightarrow";
			helptext = "/help/next picture.xml";
		}
		// check to see if it doesn't have an existing tip, if it doesn't then explain why
		else if( outer.getAttribute( "noactions") ) {
			helptext = "/help/no attributes.xml";
		}
			
		outer.setAttribute("helptext", helptext );
		outer.className = newClass;
	}
}

//
// Automatically grey an image
var precacheTimeout;
function normalImage( number )
{
	var test = new Image();
	test.src = "/images/uploaded/" + sequence[number] + ".jpg";
	test.onload = imageReplacement;
	if( test.width == 0 || ! test.complete ) {
		gObj( sequence[ number ] + "_loading" ).style.display = "block";

		// hack for ie
		if( $.browser.msie ) {
			setTimeout( function() { gObj( sequence[ number ] + "_loading" ).style.display = "none"; }, 10000 );
		}
						
	}
	else {
	    imageReplacement(); // it's done so tell it to behave 
	}
}

// This is called when the image has finished loading, at this point we need to display it, and I think we should preload the
// next image
function imageReplacement() {
	
    gObj( sequence[ sequenceNumber ] + "_loading" ).style.display = "none";
    
    if( gObj( sequence[ sequenceNumber ] + "_inner" ).style.backgroundImage != "url('/images/uploaded/" + sequence[ sequenceNumber ] + ".jpg' )") {
		gObj( sequence[ sequenceNumber ] + "_inner" ).style.backgroundImage = "url('/images/uploaded/" + sequence[ sequenceNumber ] + ".jpg' )";
    }

    // it's finished loading so start the next one
    if( precacheTimeout ) {
		clearTimeout( precacheTimeout );
    }
    precacheTimeout = setTimeout( 'preLoad('+((sequenceNumber+1)%sequence.length)+');', 500 );

	// set the title
	var title = gObj( sequence[ sequenceNumber ] ).getAttribute("title");
	if( title != "" ) {
		title = " : " + title;
	}
    document.title = document.title.replace( / :.*$/, '') + title;
	
	// update all the arrows, necessary because we may have scrolled more than one image
	setArrows();
}

//
// Called on a timer to start the loading of the next image - we don't care when it finishes as it's just to save
// some time
function preLoad( number ) {
    // Start a pre-loading of the next image
    var test = new Image();
    test.src = "/images/uploaded/" + sequence[number] + ".jpg";
    precacheTimeout = 0;
}

//
// Inner function for scrolling - needs to have the amount set
function scroll() {
	
    leftSide += amount;

	// Update the position
    var x = gObj('scroller');
    x.scrollLeft =  leftSide;
    
    // Stops will be set, when hit stop!
    if( (amount < 0 && leftSide + amount < leftStop) ||
		(amount > 0 && leftSide + amount > leftStop))
	
	{
	    // stop the scrolling
	    leftSide = leftStop;
	    x.scrollLeft = leftSide;

		normalImage( sequenceNumber );

		// hack - safari seems to delay sending an onscroll until well after scrolling has finished.
		// by turning off the onscroll notification for a while we don't end up with two coloured
		// images... we do need to turn it back on again though ;)
		if ( $.browser.safari) {
			setTimeout( function() { x.onscroll = updateImages; }, 200 );
		}
	    
	    // done scrolling so kill the timer
	    clearTimeout( time );
	    time  = 0;
	    return;
	}
    
    time = setTimeout('scroll()',theTime);
}


// Helper Function
function gObj(obj) {
	return document.getElementById( obj );
}

//
// Used to show and hide controls in forms
function hide( i ) {
	gObj(i).style.display = "none";
	//	gObj(i).value = j;
	gObj("label_"+i).style.display = "none";
	if( gObj("desc_"+i)) { gObj("desc_"+i).style.display = "none" };
	if( gObj("br_"+i)) { gObj("br_"+i).style.display = "none" };
}
function show( i ) {
	gObj(i).style.display = "inline";
	gObj("label_"+i).style.display = "inline";
	if( gObj("desc_"+i)) { gObj("desc_"+i).style.display = "block" };
	if( gObj("br_"+i)) { gObj("br_"+i).style.display = "block" };
}

//
function callback(hash)
{
	if( ! time ) {
		if( hash ) {
			goTo( parseInt(hash ), true );
		}
		else {
			normalImage( 0 );
		}
	}
}

function initialisepage()
{
	// also need to put a handler on each image
	$("div[@rel='history']").click(function() {

			// if it does have an anchor than update the page properly -->
			var image = parseInt( this.getAttribute("ps"));
			
			// replace everything after the hash
			var newlocation = document.location.href.replace( /#.*$/,'') + "#" + image;
		
			if( sequenceNumber != image ) {
				goTo( image, false );
			}
			
			if ( ! $.browser.safari) {
				document.location.replace( newlocation );
			}
			return true;
		});

	// deal with IE 6
	if( $.browser.msie && $.browser.version < 7 ) {
		$("div[@rel='history']").hover(
			function() {
				if( $(this).hasClass("tip")) {
					$(this).find("span").css("display","block");
				}
			},
			function() {
				$(this).find("span").css("display","none");
			});
	}
	
	if (document.URL.indexOf('#') != -1) {
		image = document.URL.split('#')[1];
		if( image ) {
			window.setTimeout( function() {  goTo( image, true ); }, 100 );
		}
	} else {
		goTo( 0, true );
	}
	
}

// tweak the url to include help or remove it
function addhelp() {
	var search = document.URL;
	var anchor = document.location.hash;
	search = search.replace( /help=yes|[#].*$/g, "" );
	if( search.indexOf( '?' ) >= 0 ) {
		search += "&help=yes";
	}
	else {
		search += "?help=yes";
	}
		
	search = search.replace( /&&/g, "&" ).replace( /(&$|^&|[\?]&)/g, "" ).replace( /[\?]$/, "" );
	document.location.replace (search + anchor );
}

function removehelp() {
	var search = document.URL;
	var anchor = document.location.hash;
	search = search.replace( /help=yes|[#].*$/g, "" );
	search = search.replace( /&&/g, "&" ).replace( /(&$|^&)/g, "" ).replace( /[\?]$/, "" );
	document.location.replace (search + anchor );
}

function addtosearch( keywords, event ) {
	if( event ) {
		event.preventDefault(); // stop firefox processing it
	}
	
	var st = gObj( "search_text" );
	st.className = "search";
	if( st.value != "" ) {
		var removeduplicates = st.value.replace( keywords, "" );
		keywords = removeduplicates  + "," + keywords;
	}
	st.value = keywords.replace(/,,/,",").replace(/^,|,$/,"");
	return false;
	
}