var randomImages = Array();
var searchImages = Array();



var lastSectionState = -1;

function restoreSectionState(){
		//alert( 'lss:' + lastSectionState );
		flashIpc( "flashSectionBrowser", "_root.tabSelected", lastSectionState ); //must do this after redisplay so swf is in scope
}


function guiDeclutter(){
	if( document.getElementById('divContentNavigator').style.display == 'none' ){
		document.getElementById('divContentNavigator').style.display = '';
		
		//the flash applet will call for this when it's ready.
		//setTimeout( "restoreSectionState();", 10 );
		
		
	}else{
		document.getElementById('divContentNavigator').style.display = 'none';
	}
}

function guiDebugShowFrame(){
	var node = document.getElementById('iframeAnalytics');//.style.display = '';
	
	if( node.style.display == 'none' ){
		node.style.display = '';
	}else{
		node.style.display = 'none';
	}
}

function guiDebugShowFlashLog(){
	var node = document.getElementById('flashLog');//.style.display = '';
	
	if( node.style.display == 'none' ){
		node.style.display = '';
	}else{
		node.style.display = 'none';
	}
}






//randomize selection of images.
function explore(){
	
	//if we're not in explore mode, switch tabs, else, randomize image display
	if( document.getElementById('tblImageThumbs').style.display == 'none' ){
		document.getElementById('tblImageSearch').style.display = 'none';
		document.getElementById('tblImageGalleries').style.display = 'none';
		document.getElementById('tblImageThumbs').style.display = '';
		
		navClick( 'show_tab_explore' );
	}else{
		randomThumbs(); //logs its own nav click event
	}
	
	lastSectionState = 0; //store section browser state
	
	return;
}


function galleries(){
	document.getElementById('tblImageSearch').style.display = 'none';
	document.getElementById('tblImageThumbs').style.display = 'none';
	document.getElementById('tblImageGalleries').style.display = '';
	
	navClick( 'show_tab_galleries' );
	
	//todo; active-click behaviour to reset galleries state
	
	lastSectionState = 1; //store section browser state

	
	return;
}


function search(){
	document.getElementById('tblImageThumbs').style.display = 'none';
	document.getElementById('tblImageGalleries').style.display = 'none';
	document.getElementById('tblImageSearch').style.display = '';
	
	navClick( 'show_tab_search' );

	lastSectionState = 2; //store section browser state

	return;
}

/*
function popular(){
	alert('popular mode');
	return;
}
*/






function do_search(){
	
	var iMaxResults = 20;
	

	//blank out any non hits
		for( x=0; x<iMaxResults; x++ ){
			changeThumb_SearchResult( x, "./blankMini.png" );
			searchImages[x] = -1;
		}



	
	sSearchTerms = document.getElementById('txtSearchFor').value.toLowerCase();
	
	if( sSearchTerms == '' ){
		navClick( 'search_blank' );
	}else{
		navClick( 'search__' + sSearchTerms );
	}
	
	
	//alert( imagesAll.length );
	//alert( sSearchTerms );
	
	var iHitCount = 0;
	
	for( var x=0; x < imagesAll.length-1; x++ ){
	
		var imgName = imagesAll[x].name.toLowerCase();
	
		//if( imagesAll[x].name == sSearchTerms ){
		if( imgName.indexOf(sSearchTerms) > -1 ){
		
			
			searchImages[iHitCount] = x; //store as many hits as we can get
			if( iHitCount < iMaxResults ){
				//we only have room to display 12 images
				//document.getElementById( "search_" + iHitCount ).src = "./thumb/" + imagesAll[ x ].file;
				
				var imgUrl = "./thumb/" + imagesAll[ x ].file;
				
				setTimeout( 'changeThumb_SearchResult('+iHitCount+',\'' + imgUrl + '\');', 300 * Math.random() ); 
				
			}
			iHitCount++;
		
		}
	
	}
	
	

/*	
	//blank out any non hits
	if( iHitCount < iMaxResults ){
		for( x=iHitCount; x<iMaxResults; x++ ){
			//document.getElementById( "search_" + x ).src = "./blankMini.png";
			changeThumb_SearchResult( x, "./blankMini.png" );
			searchImages[x] = -1;
		}
	}
*/
	
	
	
	if( iHitCount == 0 ){
		//alert("No match.");
	}
	
	//alert('done');
	
	return;
}

function changeThumb_SearchResult( thumb_index, imgUrl ){
	
	//document.getElementById( "search_" + thumb_index ).src = imgUrl;
	
	
	link_node = document.getElementById( "search_href_" + thumb_index );
	//alert(link_node);
	
	document.getElementById( "search_href_" + thumb_index ).href = '#' + getImageTitleForId( searchImages[thumb_index] );
	document.getElementById( "search_" + thumb_index ).src = imgUrl;		
	
}



function changeThumb_GalleryItem( thumb_index, imgUrl ){
	
	//document.getElementById( "search_" + thumb_index ).src = imgUrl;
	
	
	link_node = document.getElementById( "gallery_href_" + thumb_index );
	//alert(link_node);
	
	document.getElementById( "gallery_href_" + thumb_index ).href = '#' + getImageTitleForId( searchImages[thumb_index] );
	document.getElementById( "gallery_" + thumb_index ).src = imgUrl;		
	
}






function do_ExploreRefresh(){
	randomThumbs();
	
	return;
}






//these aren't being used.

function hideCatalog(){
	document.getElementById('tblCatalogBrowser').style.display = 'none';

}

function showCatalog(){
	document.getElementById('tblCatalogBrowser').style.display = '';

}





function setWindowTitle( newTitle ){
	if( newTitle == '' ){
		setWindowTitle_Ex( "Gaily Day" );
	}else{
		setWindowTitle_Ex( "Gaily Day - " + newTitle );
	}
}

function setWindowTitle_Ex( newTitle ){
	document.title = newTitle;
}







function showImage( image ){

	showImage_Ex( randomImages[image] );

}

function showImage_Ex( absoluteImageId ){
	var sImageTitle = getImageTitleForId( absoluteImageId );

	setWindowTitle( sImageTitle );

	window.location = "#" + sImageTitle;

	navClick( 'show_image__explore__' + sImageTitle );


	var swf = document.getElementById("imageViewer");
	swf.SetVariable("_root.imgUrl", imagesAll[ absoluteImageId ].file );

	swf.SetVariable("_root.imageCaption", imagesAll[ absoluteImageId ].name );

}



function showSearchImage( image ){
	
	var absoluteImageId = searchImages[image];
	
	var sImageTitle = getImageTitleForId( absoluteImageId );
	setWindowTitle( sImageTitle );

	navClick( 'show_image__search__' + sImageTitle );

	var swf = document.getElementById("imageViewer");
	swf.SetVariable("_root.imgUrl", imagesAll[ absoluteImageId ].file );

	swf.SetVariable("_root.imageCaption", imagesAll[ absoluteImageId ].name );

}




function showGalleryImage( image ){

	var absoluteImageId = imagesForAlbum[image].id;
	
	//alert( image + ":" + imagesForAlbum[image].name);
	//return;
	
	var sImageTitle = imagesForAlbum[image].name;
	setWindowTitle( sImageTitle );
	navClick( 'show_image__gallery__' + sImageTitle );
	
	
	
	var swf = document.getElementById("imageViewer");
	swf.SetVariable("_root.imgUrl", imagesForAlbum[image].file );
	
	swf.SetVariable("_root.imageCaption", imagesForAlbum[image].name );

}






function flashIpc( swfName, variableName, value ){

	var swf = document.getElementById(swfName);
	swf.SetVariable( variableName, value );

}





//this function is a wrapper around using flashipc jscript hacks to setup an info pane in the flash
//applet. it is called by dynamically generated calls on the actual html page, the body of which is loaded
//from the db.
function infoPane_Base( title ){
	
	var sDomTitle = title.replace(" ", "");
	var node = document.getElementById('divInfoContent_' + sDomTitle);
	var body = node.innerHTML;
	
	flashIpc('imageViewer','_root.sInfoPane_Title', title);
	flashIpc('imageViewer','_root.sInfoPane_Body', body);
	
	flashIpc('imageViewer','_root.bShowInfoPane', 1);

	//alert('info pane base: ' + title + "\n" + body );

}





function getRandomThumb(){
	
	var max = imagesAll.length-2;
	
	var iRandom = 0;
	do{
		iRandom = parseInt( Math.random() * max );
		
		for( iCheck=0; iCheck < randomImages.length; iCheck++ ){
			if( randomImages[iCheck] == iRandom ){
				iRandom = max + 10; //force another image id generation
			}
		}
		
	}while( iRandom > max );
	
	return iRandom;
	
}




function randomThumbs(){
	
	var iMaxResults = 20;
	
	var tOut = 100;

	navClick( 'show_explore_thumbs_random' );

	//do a quick erase of all the images before we load in the next set
	for( x=0; x<iMaxResults; x++ ){
		
		var imgUrl = "./blankMini.png";
		changeThumb( x, imgUrl );
	
	}


	
	for( x=0; x<iMaxResults; x++ ){
		var iRand = getRandomThumb();
		randomImages[x] = iRand;
		
		var imgUrl = "./thumb/" + imagesAll[ iRand ].file;
		//changeThumb( x, imgUrl );
	
		//we do this with a random delay on each load call so that when all the items have been cached there is still some
		//'organic' feel to the loader, instead of just an instant cold shift each image still has a random load latency.
		//setTimeout( 'changeThumb('+x+',\'' + imgUrl + '\');', 300 * Math.random() ); //this method causes a random effect.
		setTimeout( 'changeThumb('+x+',\'' + imgUrl + '\');', tOut );  //this method causes a cascade effect, it's nice.
		tOut += 20;
	
	
	}
	
	return;
}


function changeThumb( thumb_index, imgUrl ){
	
	
	link_node = document.getElementById( "thumb_href_" + thumb_index );
	//alert(link_node);
	
	document.getElementById( "thumb_href_" + thumb_index ).href = '#' + getImageTitleForId( randomImages[thumb_index] );
	document.getElementById( "thumb_" + thumb_index ).src = imgUrl;
	
}




var global_galleryIndex=-1;

function exploreGallery( galleryIndex ){

	//--- this function is called to handle a click of the gallery list.
	//	it should:
	//		- dispatch a request to the server for new data.
	//		- tidy the UI and prepare it for gallery display
	//
	//	data off the real server takes a little while to arrive so if we wait for it
	//	to come back before processing the UI chain for it it looks slow and laggy.
	
	
	//alert("exploreGallery(" + galleryIndex + ")");
	
	global_galleryIndex = galleryIndex;
	xmlGetRequest( './jsonImagesForAlbum.json?id='+galleryIndex, newGalleryData );

		document.getElementById( 'divGalleryCanvas' ).style.overflow = ''; //change scroll bar behaviour
	
		document.getElementById( 'tblGalleriesList' ).style.display = 'none';
		document.getElementById( 'tblGalleryThumbs' ).style.display = '';

		document.getElementById( 'spnGalleryName' ).innerHTML = 'loading..';

		for( x=0; x < 20; x++ ){
			document.getElementById( "gallery_" + x ).src = "./blankMini.png";
		}

	navClick( 'load_gallery__' + galleryIndex );

}


//this is a callback function for when gallery data has arrived back from an XMLHTTP request
function newGalleryData( data ){
	
	if( document.getElementById( 'tblGalleryThumbs' ).style.display != '' ){ return; }
	
	navClick( 'show_gallery_thumbs_id__' + global_galleryIndex );
	
	eval(data);
	
	//alert(global_galleryIndex);
	var newName = getGalleryObjectForGalleryId(global_galleryIndex).name;
	
	//alert(newName);
	if( newName == "" ){
		newName="<site error> :(";
	}
	
	document.getElementById( 'spnGalleryName' ).innerHTML = newName;
	
	navClick( 'show_gallery_thumbs__' + newName );
	
	
	var tOut = 100;
	
	
	for( x=0; x < 20; x++ ){
	
		var imgUrl = "./blankMini.png";
		
		if( x < imagesForAlbum.length-1 ){
			imgUrl = "./thumb/" + imagesForAlbum[x].file
			
			//changeThumb_GalleryItem( x, imgUrl );
			
			setTimeout( 'changeThumb_GalleryItem('+x+',\'' + imgUrl + '\');', tOut );  //this method causes a cascade effect, it's nice.
			tOut += 20;
			
			
			
		}else{
			document.getElementById( "gallery_" + x ).src = "./blankMini.png";
			changeThumb_GalleryItem( x, imgUrl );
		}
		
	
	}
	
	//alert( imagesForAlbum.length + " images in ablum.." );
	
}




function getGalleryObjectForGalleryId( searchId ){

	for( x=0; x < albumsAll.length - 1; x++ ){
		//alert("get gal obj: [" + x + "].id:" + albumsAll[x].id);
		if( albumsAll[x].id == searchId ){
			return albumsAll[x];
		}
	
	}
	
	return null;

}



function galleryResetBrowseState(){
	document.getElementById( 'divGalleryCanvas' ).style.overflow = 'auto';


	document.getElementById( 'tblGalleriesList' ).style.display = '';
	document.getElementById( 'tblGalleryThumbs' ).style.display = 'none';
	
	//fixme; reset all images to blank mini or something..

	document.getElementById( 'spnGalleryName' ).innerHTML = 'browsing..';
	
}








function wantThis( imageCaption ){
	//alert( "want: " + imageCaption );
	
	navClick( 'want_this__' + imageCaption );

	return;
}



function loveThis( imageCaption ){
	alert('<3 ' + imageCaption);
	navClick( 'love_this__' + imageCaption );
	return;
}



function linkThis(){
	navClick( 'link_this__' + window.location );

	prompt( "Link URL - Copy to clipboard..", window.location );
	return;
}



function showLoginBox(){
	navClick( 'show_login_box' );
	RPXNOW.show();
}









function getImageTitleForId( absoluteImageId ){
	try{
		return imagesAll[ absoluteImageId ].name;
	}catch(e){
		return '';
	}

}






function getImageIdForTitle( imageTitle ){
	
	sSearchTerms = imageTitle.toLowerCase();
	
	var imageX = -1;
	
	for( var x=0; x < imagesAll.length-1; x++ ){
	
		var imgName = imagesAll[x].name.toLowerCase();
	
		//alert( imagesAll[x] + " / " + sSearchTerms );
		if( imgName == sSearchTerms ){
		
			imageX = x;
			break;
		
		}//end check for match
	
	}//end loop on all items
	
	
	return imageX;
}













// Provide the XMLHttpRequest class for IE 5.x-6.x:
// Other browsers (including IE 7.x-8.x)  ignore this when XMLHttpRequest is predefined
if( typeof XMLHttpRequest == "undefined" ) XMLHttpRequest = function() {
  try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) {}
  try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) {}
  try { return new ActiveXObject("Msxml2.XMLHTTP") } catch(e) {}
  try { return new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
  throw new Error( "This browser does not support XMLHttpRequest." )
};




function xmlGetRequest( url, cb ){

	var request =  new XMLHttpRequest();
	request.open("GET", url, true);
	
	request.onreadystatechange=function() {
		if (request.readyState==4 ) {
			
			var payload = request.responseText;
			
			if( cb != undefined ){
				cb( payload );
			}
			
		}
	}
	
	request.send(null);

	
	/* -- this code was causing an annoying double response event
	if(!request.getResponseHeader("Date")) {
	  var cached = request;
	  request =  new XMLHttpRequest();
	  var ifModifiedSince = cached.getResponseHeader("Last-Modified");
	  ifModifiedSince = (ifModifiedSince) ?
		  ifModifiedSince : new Date(0); // January 1, 1970
	  request.open("GET", url, false);
	  request.setRequestHeader("If-Modified-Since", ifModifiedSince);
	  request.send("");
	  if(request.status == 304) {
		request = cached;
	  }
	}
	*/

	return true;
}

