//	Feel free to use the code in this script for your own page but remember: Credits to AcumenPictures.com whould be highly appreciated! :-)
//

// Set some global viarables since inner function variables are not usable in other functions unless you 'return their values'
var menuitems = ""; var Page = ""; var LastSet; var ThumbSqSize // Size for the Collection Thumbnails
var collset = new Array(); var ImageLNK = new Array(); var CR="Test" // CR = Content Returned from OpenContent()
var APIKEY = "&api_key=8ca656008d8104187a117c93be604d41" // Your declaired API key at FlickR
var CollSel = "AP_"	// The creteria on which a collection is selected for futher processing
var AC = new Array("x","y","0"); // Arrow Controll array; Current photo, Max Photo, Respond 1/0
var PH = 200

var settitle = ""; var ActiveColl = ""	// Variables for internal use

// Now the Fun(ctions) start :-)
function dw(t,c)	// write down given Content into the defined Table
{
	if (!document.getElementById(t)) // In case of a back-forward action in the browser, the page reloads to prevent a JS error
	{
		alert("Whoops, helaas moet de pagina herladen worden om fouten te voorkomen.");
		location.reload(true);
		return;
	}
	
	document.getElementById(t).innerHTML=c;
	
	if(document.getElementById("Photo"))	// Reduce the size of photos loaded from the sets
	{
        document.getElementById("Photo").height = PH;
        // PH
	}

	return;
}

function Step_1()	// This is the first function to be started and handle all prerequisites for Step_2
{
	BuildMenuItem("About", "Me","","content/welkom.txt") // Create menu items
	BuildMenuItem("About", "AcumenPictures","","content/acumenpictures.txt")
	LoadJSON("method=flickr.collections.getTree","&user_id=35347253%40N00","&jsoncallback=CollReader");	// Start querying the FlickR API and finish in Step_2
	return;
}

function Sizes() // Trouble shooter
{
alert("Sizes, Hoogtes\n"+
		"Tabel: "+document.getElementById('M1').offsetHeight+"\n"+
		"Head Space: "+document.getElementById('S1').offsetHeight+"\n"+
		"Header: "+document.getElementById('H1').offsetHeight+"\n"+
		"Cel CC1: "+document.getElementById('CC1').offsetHeight+"\n"+
		"Footer: "+document.getElementById('F1').offsetHeight+"\n"+
		"Foot Space: "+document.getElementById('S3').offsetHeight+"\n"+
		"")

}

function Step_2() // Page Builder/loader function
{	
	BuildMenuItem("Links", "Algemeen","","content/links-algemeen.txt") // Create menu items
	BuildMenuItem("Links", "Producten","","content/links-producten.txt")
//	BuildMenuItem("Links", "Modellen","","content/links-modellen.txt")

	BuildMenuItem("Overige", "Contact","","content/contact.txt")
	BuildMenuItem("Overige", "Disclaimer","","content/disclaimer.txt")


	dw("M2",menuitems);	// create the menu items
	OpenContent("C1","content/welkom.txt")
	return;
}


function SetTitle(rsp)
{
	if (rsp.stat != "ok")	// if not okay, alert with error!
	{
		alert("Titleload status: "+rsp.stat+"\nError message: "+rsp.message)
		return;
	}
	
	if (document.getElementById("SC1"))	// Check to see if this is the Set page
	{	dw("H2","Set: "+rsp.photoset.title._content)
		if (rsp.photoset.description._content)
		{
			dw("SC1",rsp.photoset.description._content)
		}
	}
	
	if (document.getElementById(rsp.photoset.id))	// Check to see if this is the Collection page
	{
		document.getElementById(rsp.photoset.id).title = rsp.photoset.title._content;
	}
		
	return;
}

function CollReader(rsp)	// More info about JSON: http://www.flickr.com/services/api/response.json.html
{
	if (rsp.stat != "ok")	// if not okay, alert with error!
	{
		alert("PhotoCollection load status: "+rsp.stat+"\nError message: "+rsp.message)
		return;
	}

	var c = 0	// Array field counter in 1st dimension, one per Collection
	for (var i=0; i<rsp.collections.collection.length; i++)	// Read all collections in array Collections
	{
		var coll = rsp.collections.collection[i];
		if (coll.title.indexOf(CollSel) == 0)	// Do things when collection starts with the Collection Selector variable value ("AP_" by default)
		{
			BuildMenuItem('Portfolio', coll.title.substring(CollSel.length),'"'+coll.id+'","'+coll.title.substring(CollSel.length)+'"') // Create menu item for each FlickR collection
			
			collset[c] = new Array(coll.set.length+1)
			collset[c][0] = '"'+coll.id+'"' // Because the first dimension is not usable, possition 0 will be filled with the collection ID
			
			for (var j=0; j<coll.set.length; j++) // Read all sets in selected collection and put the set ID's in an array
			{
				var set = coll.set[j];
				collset[c][j+1] = set.id
			}
			c++
		}
	}
	
	Step_2()	// Lets build the page now
	return;
}

function OpenColl(collid, Title, Start) // Start = the first set to start with
{
	ThumbSqSize = 250 // Thumbnail size + 10px
	
	var SetContentH = document.getElementById('C1').offsetHeight-20
	var SetContentW = document.getElementById('C1').offsetWidth-14
	var MaxRows = Math.floor(SetContentH / ThumbSqSize)
	var MaxColls = Math.floor(SetContentW / ThumbSqSize)
	var Spacer = ((document.getElementById('C1').offsetHeight - (ThumbSqSize+4)*MaxRows+16))/4
	
	var Prev; var Next; var CurRow = 1
	if (!Start) {Start = 1}

	for (var i=0; i<collset.length; i++) // Read all sets in selected collection and put the set ID's in an array
	{
		if (collset[i][0] == '"'+collid+'"')
		{
			dw("H2","Collectie: "+Title)
			var CThumbs = collset[i].length
			if (CThumbs > (MaxRows*MaxColls)+Start)
			{
				CThumbs = (MaxRows*MaxColls)+Start
				Next = CThumbs
			}
			
			if (Start > (MaxRows*MaxColls))
			{
				Prev = Start-(MaxRows*MaxColls)
			}
			
			// Page = "<Table Border=0><DIV style='height: "+MaxSize+"; overflow-x: hidden;'></DIV></Table>"
			Page = "<Table Align=Center Class='CollTable' ID='CC1'><TR><DIV style='height: "+Spacer+"; overflow-x: hidden;'></DIV></TR>"
			
			for (var j=Start; j<CThumbs; j++) // Build the page
			{
				if (j-(Start-1) > MaxColls*CurRow)
				{
					Page = Page + "</TR><TR>"	// Start new Row
					CurRow++
				}
				Page = Page + "<TD Class='CollThumbs' ID="+collset[i][j]+" Height="+ThumbSqSize+" Width="+ThumbSqSize+" Align=Center>Loading...</TD>"
			}
			
			Page = Page + "</TR><TR><TD Class='CollBottom' ID='Prev'></TD>"	// End Row and create the Previous Cell in the next row	
			if (CThumbs-Start != 1)
			{
				for (var cells=1; cells < MaxColls-1; cells++) // Variable cell builder to assure that Next will be in the most right table cell
				{
					Page = Page + "<TD Class='CollBottom'ID=Bottom-"+cells+" Align=Center></TD>" 
				}
				Page = Page + "<TD Class='CollBottom' ID='Next' Align=Right></TD>" // Create Next Cell
			}
			Page = Page +"</TR></Table>"
			dw("C1",Page)	// Create Collection Thumbnail Table

			if (Prev) {	dw("Prev","<A Href=javascript:OpenColl('"+collid+"','"+Title+"',"+ Prev +")>Previous</A>")	}	// Check for Previous page
			if (Next) {	dw("Next","<A Href=javascript:OpenColl('"+collid+"','"+Title+"',"+ Next +")>Next</A>")		}	// Check for Next page
			
			for (var j=Start; j<CThumbs; j++) // Fill the page
			{
				LoadJSON("method=flickr.photosets.getInfo","&photoset_id="+collset[i][j],"&jsoncallback=SetTitle") // Get Set Title
				LoadJSON("method=flickr.photosets.getPhotos","&photoset_id="+collset[i][j],"&jsoncallback=FillColl") // Load API for each set
			}
			
		}
	}
}

function FillColl(rsp)
{
	if (rsp.stat != "ok")	// if not okay, alert with error!
	{
		alert("PhotoSet load status: "+rsp.stat+"\nError message: "+rsp.message)
		return;
	}
					
	for (var i=0; i<rsp.photoset.photo.length; i++) // Read all photos in array photo
	{
		var photo = rsp.photoset.photo[i];
		if (photo.isprimary == "1")	// This is the set image
		{
			dw(rsp.photoset.id, "<A Href=javascript:LoadJSON('method=flickr.photosets.getPhotos','&photoset_id="+rsp.photoset.id+"','&jsoncallback=BuildSet')><Img Src=http://farm"+photo.farm+".static.flickr.com/"+photo.server+"/"+photo.id+"_"+photo.secret+"_m.jpg Border=0></A>")
		}
	}
	return;
}

function BuildSet(rsp)
{	
	if (rsp.stat != "ok")	// if not okay, alert with error!
	{
		alert("PhotoSet load status: "+rsp.stat+"\nError message: "+rsp.message)
		return;
	}
	
	LoadJSON("method=flickr.photosets.getInfo","&photoset_id="+rsp.photoset.id,"&jsoncallback=SetTitle") // Get Set Title
	
	var SetContentH = document.getElementById('C1').offsetHeight-20
	var SetContentW = document.getElementById('C1').offsetWidth
	
	var Page = "<Table Height="+SetContentH+" Class='SetTable'>"
	SetContentH = SetContentH - 100
	
	Page = Page +	"<TR><TD Class='SetThumbs' ID='SC1' Height="+SetContentH+" Align=Center><DIV style='width: "+SetContentW+"; overflow: auto;'><H1>Er is helaas geen beschrijving van deze set beschikbaar.<BR>Klik op een foto onderin om deze te bekijken.</H1></DIV></TD></TR>"+
					"<TR><TD Class='SetThumbs' ID='ST1'><DIV style='width: "+SetContentW+"; overflow-x: scroll;'>"+
						"<Table Align='Center' Class='SetThumbs' ID='ST1'><TR ID='SR1' Class='SetThumbs'>"

	for (var i=0; i<rsp.photoset.photo.length; i++) // Read all photos in array photo
	{
		var photo = rsp.photoset.photo[i];
		var URL = "http://farm"+photo.farm+".static.flickr.com/"+photo.server+"/"+photo.id+"_"+photo.secret
		if (i != rsp.photoset.photo.length-1) {var next = i+1} else {var next = 0}
        if (i == 0) {var prev = rsp.photoset.photo.length-1} else {var prev = i-1}
        
		ImageLNK[i] = "<A Href=javascript:dw('SC1',ImageLNK["+prev+"]) class='Menu' id='PhotoPrev'></A><A Href=javascript:dw('SC1',ImageLNK["+next+"]) class='Menu' id='PhotoNext'><Img Src='"+URL+"_z.jpg?zz=1' ID='Photo' Alt='"+photo.title+"' Title='Klik voor de volgende foto' Border=0></A>"
		
		Page = Page + "<TD ID='"+i+"'><A Href=javascript:dw('SC1',ImageLNK["+i+"])><Img Src='"+URL+"_s.jpg' Border=0 Title='"+photo.title+"'></A></TD>"
	}
	var Page = Page + "</TR></Table></DIV></TD></TR></Table>"
	dw("C1",Page)
    PH = document.getElementById('SC1').offsetHeight-20
    if (navigator.appName.indexOf("Microsoft") > -1) {PH = PH - 15}
}

function LoadJSON(method,id,extra)	// method is the kind of API you want to call, ID is the ID of for example the photoset, extra is the extras you want to add, for example the call back function for FlickR. Default jsonFlickrApi
{	
	if (!extra)
	{	var extra = ""	}
	
	var fileref=document.createElement('script')
	fileref.setAttribute("type","text/javascript")
	fileref.setAttribute("src", "http://api.flickr.com/services/rest/?" + method + APIKEY + id + extra +"&format=json")	
	if (typeof fileref != "undefined")
	{
		document.getElementsByTagName("head")[0].appendChild(fileref)
	}
}

function BuildMenuItem(menugroup,itemname,collid,link)	// Create menu items (also these based on FlickR collections) and uses global variable "menuitems" for it.
{
	if (menuitems.indexOf(menugroup) < 0) // create menu header
	{
		if (menuitems.indexOf("</UL>") != menuitems.length-5 && menuitems.indexOf("<UL class='Menu'>") != -1)	// Only close an UL when there is already one. 
		{
			menuitems = menuitems + "</UL>"
		}
		menuitems = menuitems + "<H3>"+menugroup+"</H3><UL class='Menu'>"
	}

	if (collid) // does exist when it is a FlickR
	{
		menuitems = menuitems + "<LI><B><A Href=javascript:OpenColl("+collid+") class='Menu'>"+itemname+"</A></B>"
		return;
	} 

	menuitems = menuitems + "<LI><B><A Href=javascript:OpenContent('C1','"+link+"') class='Menu'>"+itemname+"</A></B>"

}

function OpenPage(content)
{
	dw("H2"," ");
	if (!content)
	{
		alert("Geen Content!")
		OpenContent("C1","content/welkom.txt");
		return;
	}
	if (content == "Me")
	{
		OpenContent("C1","content/welkom.txt"); 
		return;
	}
	
	if (content == "AcumenPictures")
	{
		OpenContent("C1","content/acumenpictures.txt"); 
		return;
	}
	
}

function OpenContent(t,file)
{
	dw("H2"," ");
	var txtFile = new XMLHttpRequest();
	txtFile.open("GET", file, true);
	txtFile.onreadystatechange = ParseContent;
	txtFile.send(null);
	
	function ParseContent()
	{
		if (txtFile.readyState === 4) // Makes sure the document is ready to parse.
		{  
		    if (txtFile.status === 200) // Makes sure it's found the file.
			{  
				dw(t, txtFile.responseText);
				// allText = txtFile.responseText;
				// lines = txtFile.responseText.split("\n"); // Will separate each line into an array
		    }
			else
			{ alert("Whoops, bestand '"+file+"' niet gevonden!\nFoutcode: "+txtFile.status)	}
		}
	}

	return;
}


function handleArrowKeys(evt) {
   evt = (evt) ? evt : ((window.event) ? event : null); // Internet Explorer Fix
   switch (evt.keyCode) {
            case 37:        // Left
                var LP = document.getElementById('PhotoPrev').href;               
                var arr = LP.substring(LP.indexOf("[")+1,LP.indexOf("]"))
                dw('SC1',ImageLNK[arr]);
                break;    
            case 38:        // Up
                document.getElementById("Photo").height = document.getElementById("Photo").height+10
                break;    
            case 39:        // Right
                var LP = document.getElementById('PhotoNext').href;               
                var arr = LP.substring(LP.indexOf("[")+1,LP.indexOf("]"))
                dw('SC1',ImageLNK[arr]);
                break;    
            case 40:        // Down
                document.getElementById("Photo").height = document.getElementById("Photo").height-10
                break;    
         }
   
   
    // alert("Blup, je drukte op toets nummer: "+linkPage)
}


// and now we kick off :-)
document.onkeyup = handleArrowKeys;
Step_1();
// alert(window.innerHeight+"x"+window.innerWidth);

