// JavaScript Document
/**************************************
     Copyright 2009 Nathan Veyon
**************************************/
//Set the onload and resize functions;
//window.onload = initAll;
//window.onload = addElementsToPage;

window.onresize = resize;

//set variables
var interval = 0;
var int1 = 0;
var int2 = 0;
var stopped = false;
var myWidth = "";
var myHeight = "";
var folder = "";
var file = "";
var response = "";
var ARpics = [];
var ARtypes = ["jpg","png","jpeg","gif"];
var ARtemp = [""];
var preURL = "http://www.touchinglivesforchrist.com/pics/";
var num = "";
var pre = 'buttons/';
var ARbuttons = ['sub',pre+'lbmore.png','imgleft',pre+'lbleft.png','imgright',pre+'lbright.png','imgexit',pre+'lbexit.png'];
var ARel = ['div','shade','body','div','container','body','div','base','container','div','box','base','div','buttons','base','div','more','buttons','div','lbnavigation','buttons','div','left','lbnavigation','div','space','lbnavigation','div','right','lbnavigation','div','exit','buttons','div','submenu','buttons','a','amore','more','a','aleft','left','a','aright','right','a','aexit','exit','img','sub','amore','img','imgleft','aleft','img','imgright','aright','img','imgexit','aexit','div','extras','submenu']

loaded = false;
loadedel = false;

//******************************************************************************************\\
//general functions

//Starter function called as soon as the page is loaded
//the functions should be listed in the order they are called 
//functions maybe not as linear as the appear
function initAll() {
getDim();
if(!loadedel) {
addElementsToPage();
//addSubDivs();
loadedel=true;}
loaded = true;
checkLinks();
getData();
ie8test();
}

//if window is resized change the dimensions of the layers
function resize() {
if(loaded) {
getDim();
setDim();}
}

//Creates the picture objects
//I did not use the preset one so I could have an id if it is needed and have a minW and min H
function OBJpic(name,width,height,minDim,id) {
	this.name=name;
	this.width=width;
	this.height=height;
	this.minW=minDim[0];
	this.minH=minDim[1];
	this.id=id;
}

//Adds and element to the document
//a is the type eg div, img, a /b is the id of the element /c is the parent element for the new child
//if c is body then it is attached directly to the body tag
function addElem(a,b,c) {
	elem = document.createElement(a);
	elem.setAttribute('id',b);
	if(a=='a') {
		elem.setAttribute('href','#');
	}
	if(c=='body') {
		document.getElementsByTagName(c)[0].appendChild(elem);
	}
	else {
		document.getElementById(c).appendChild(elem);
	}
}

//sets the pictures in box
var elem;
function setPic() {
	addElem('img','lbimg','box')
	document.getElementById('lbimg').src=preURL+folder+ARpics[num].name;
}

//******************************************************************************************\\
//Finds the dimensions of the page
//sets the myWidth and myHeight variables
//Also subtracts the scrollbar width from the width
function getDim() {
if( typeof( window.innerWidth ) == 'number' ) {
	//Non-IE
	myWidth = window.innerWidth;
	myHeight = window.innerHeight;
} 
else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
} 
else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
}
myWidth = (myWidth - getScrollerWidth())
}

//Finds the width of the scrollbar
//Obtained from another website I do not remember whose
//but it can probably be found by searching for function to find scrollbar width
function getScrollerWidth() {
	var scr = null;
	var inn = null;
	var wNoScroll = 0;
	var wScroll = 0;
	
	// Outer scrolling div
	scr = document.createElement('div');
	scr.style.position = 'absolute';
	scr.style.top = '-1000px';
	scr.style.left = '-1000px';
	scr.style.width = '100px';
	scr.style.height = '50px';
	
	// Start with no scrollbar
	scr.style.overflow = 'hidden';
	// Inner content div
	inn = document.createElement('div');
	inn.style.width = '100%';
	inn.style.height = '200px';
	
	// Put the inner div in the scrolling div
	scr.appendChild(inn);
	// Append the scrolling div to the doc
	document.body.appendChild(scr);
	
	// Width of the inner div sans scrollbar
	wNoScroll = inn.offsetWidth;
	// Add the scrollbar
	scr.style.overflow = 'auto';
	// Width of the inner div width scrollbar
	wScroll = inn.offsetWidth;
	
	// Remove the scrolling div from the doc
	document.body.removeChild(document.body.lastChild);
	
	// Pixel width of the scroller
	return (wNoScroll - wScroll);
}

//******************************************************************************************\\
//Creates the different Elements of the page by calling general function addElem()
function addElementsToPage() {
	for(var i=0; i<ARel.length; i+=3) {
		addElem(ARel[i],ARel[(i+1)],ARel[(i+2)]);
	}
}

//Creates the submenu slots for pictures
function addSubDivs() {
	var name = '';
	var con = '';
	var z = 0;
	for(var x=1; x<=4; x++){
		con = 'con'+x;
		addElem('div',con,'extras');
		document.getElementById(con).style.width='100%';
		document.getElementById(con).style.height='80px';
		document.getElementById(con).style.border='none';
		for(var i=1; i<=5; i++) {
			name = "el"+z;
			z++;
			addElem('div',name,con);
			if(i<5) {
				addElem('div','spaceDiv',con);
			}
		}
	}
	for(var x=0; x<20; x++) {
		addElem('a','sma'+x,('el'+x));
	}
}

function returnFalse() {
	return false;
}

function setSubPic() {
	for(var x=0; x<ARpics.length; x++) {
		addElem('img','cImg'+x,('sma'+x));
		if(num == x) {
			document.getElementById('cImg'+x).style.borderColor = 'red';
			document.getElementById('cImg'+x).style.borderStyle = 'solid';
			document.getElementById('cImg'+x).style.borderWidth = '1px';
			document.getElementById('cImg'+x).onclick = returnFalse;
		}
		else {
			document.getElementById('cImg'+x).onclick = goToImg;
		}
		document.getElementById('cImg'+x).width=ARpics[x].minW;
		document.getElementById('cImg'+x).height=ARpics[x].minH;
		document.getElementById('cImg'+x).src=preURL+folder+ARpics[x].name;
	}
}

//******************************************************************************************\\
//check to see when the link to show the picture viewer is clicked 
//is called to run as soon as the page is loaded and also sets the folder var
function checkLinks() {
	var allLinks = document.getElementsByTagName("a");
	for(var i=0; i<allLinks.length; i++) {
		//alert(allLinks[i].id);
		if(allLinks[i].id.indexOf("PicView") > (-1)) {
			//alert("the right one " +allLinks[i].id);
			folder = allLinks[i].id.substring(7);
			allLinks[i].onclick = startPicView;
			num = i;
			return false;
		}
	}
}

function goToImg() {
	num = this.id.split(this.id.substring(0,4))[1];
	deletePic();
	startReset();
	exitSubmenu();
}

//Starts picture viewer
function startPicView() {
	document.getElementById('box').style.height=300+'px';
	document.getElementById('box').style.width=300+'px';
	document.getElementById('base').style.height=300+'px';
	document.getElementById('base').style.width=300+'px';
	startViewing();
}

//Starts picture Viewing
//sets the two layers to visible and then starts the resizing to fit the image
function startViewing() {
	//document.getElementById('container').style.top=document.documentElement.scrollTop + 20 + 'px';
	document.getElementById('shade').style.visibility='visible';
	document.getElementById('container').style.visibility='visible';
	//alert("hi");
	num=0;
	//alert('hello');
	//resetPic(0,0);
	startReset();
	//alert('and again');
}
function startReset() {
	//tester = true;
	int1 = setInterval("resetPic('width')",1);
	int2 = setInterval("resetPic('height')",1);
}
var h = 0;
function stopReset(v) {
	clearInterval(v=='width'?int1:int2);
	h++;
	h==2?setPic():"";
	h = h==2?0:h;
}
var tester = true
var tester2 = true;
function resetPic(v) {
	aDim = document.getElementById('box').style;
	bDim = document.getElementById('base').style;
	dDif = ARpics[num][v] - aDim[v].split('px')[0];
	if((Math.abs(dDif)/100) > 2){
		r = 100;
	}
	else if((Math.abs(dDif)/10) > 2){
		r = 10;
	}
	else {
		r = 1;
	}
	if(dDif==0) {
		stopReset(v);
	}
	else if(dDif > 0) {
		aDim[v] = ((aDim[v].split('px')[0]/1) + r) + 'px';
		bDim[v] = ((aDim[v].split('px')[0]/1) + r + 50) + 'px';
	}
	else{
		aDim[v] = ((aDim[v].split('px')[0]/1) + -r) + 'px';
		bDim[v] = ((aDim[v].split('px')[0]/1) + -r + 50) + 'px';
	}
}
//Resets the the box and base to the size of the image
//var w,h,wDif,hDif,wi,he,a,b,l,r,ve;
/*function resetPic(w,h) {
	wi = document.getElementById('box').style.width.split('px')[0];
	he = document.getElementById('box').style.height.split('px')[0];
	document.getElementById('box').style.height = ((he/1) + h) + 'px';
	document.getElementById('box').style.width = ((wi/1) + w) + 'px';
	document.getElementById('base').style.height = ((he/1) + h + 50) + 'px';
	document.getElementById('base').style.width = ((wi/1) + w + 50) + 'px';
	a = ARpics[num].width;
	b = ARpics[num].height;
	wDif = a - document.getElementById('box').style.width.split('px')[0];
	hDif = b - document.getElementById('box').style.height.split('px')[0];
	if((Math.abs(wDif)/100) > 2){
		l = 100;
	}
	else if((Math.abs(wDif)/10) > 2){
		l = 10;
	}
	else {
		l = 1;
	}	
	if((Math.abs(hDif)/100) > 2){
		r = 100;
	}
	else if((Math.abs(hDif)/10) > 2){
		r = 10;
	}
	else {
		r = 1;
	}
	
	if((wDif == 0) && (hDif == 0)) {
		setPic();
	}
	else if((wDif == 0) && (hDif > 0)) {
		setTimeout("resetPic(0,r)", .01);
	}
	else if((wDif == 0) && (hDif < 0)) {
		setTimeout("resetPic(0,(-r))", .01);
	}
	else if((wDif > 0) && (hDif == 0)) {
		setTimeout("resetPic(l,0)", .01);
	}
	else if((wDif > 0) && (hDif > 0)) {
		setTimeout("resetPic(l,r)", .01);
	}
	else if((wDif > 0) && (hDif < 0)) {
		setTimeout("resetPic(l,(-r))", .01);
	}
	else if((wDif < 0) && (hDif == 0)) {
		setTimeout("resetPic((-l),r)", .01);
	}
	else if((wDif < 0) && (hDif < 0)) {
		setTimeout("resetPic((-l),(-r))", .01);
	}
	else if((wDif < 0) && (hDif > 0)) {
		setTimeout("resetPic((-l),r)", .01);
	}
}*/

//******************************************************************************************\\
//Gets the data from the server using PHP
//Then calls several functions to initalize some items
function getData() {
	//alert("first " +folder);
	var temp = folder.split('slash');
	folder = '';
	for(var i = 0; i<temp.length; i++) {
		folder = folder + temp[i] + '/';
		//alert("value of folder now " + folder);
	}
	folderContent(folder);
	setLinks();
	setDim();
	setButtons();
}

//Uses HTTP to send out the name of the folder to find the image names and dimensions
///////////////////////////////////////////////////////////////////////////////////////////////
//HTTP REQUEST SECTION

var xmlHttp;

//Calls up the http request
function folderContent(str)
{
	//alert(str);
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
  {
  alert ("Browser does not support HTTP Request")
  return
  } 
var url="/getFiles.php"
url=url+"?q="+str
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged;
//alert(url);
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}

//Whent he states changes the answer is saved and processed
function stateChanged() {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
		ARtemp = xmlHttp.responseText.split("*");
		sortPics(ARtemp);
	} 
}

//Checks for compatibility and createst the appropriate HTTP obejct
function GetXmlHttpObject() {
	var xmlHttp=null;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	}
	catch (e) {
		// Internet Explorer
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e) {
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return xmlHttp;
}

//processes the data to create the image objects
function sortPics(a) {
	x=0;
	ARpics.splice(0,ARpics.length);
	for(var i=0; i<a.length; i+=3) {
		ARpics[x] = new OBJpic(a[i],a[(i+1)],a[(i+2)],getMinDim(a[(i+1)],a[(i+2)]),x);
		x++;
	}
}

//Sets the minature width and height for the images
function getMinDim(a,b) {
	var ARminDim =[];
	if(a>b) {
		ARminDim[0] = 75;
		ARminDim[1] = Math.floor(b/(a/75));
	}
	else {
		ARminDim[0] = Math.floor(a/(b/75));
		ARminDim[1] = 75;
	}
	return ARminDim;
}

//Sets the lbnavigation buttons so when clicked appropriate function is called
function setLinks() {
	document.getElementById('exit').onclick = exitViewer;
	document.getElementById('right').onclick = goRight;
	document.getElementById('left').onclick = goLeft;
	document.getElementById('more').onclick = viewMore;
}

//sets the Dimensions of the two lowest z index layers
function setDim() {
	document.getElementById("shade").style.width=myWidth+'px';
	document.getElementById("container").style.width=myWidth+'px';
	document.getElementById("shade").style.height=myHeight+'px';
}

//Sets the pictures for the different lbnavigation buttons
function setButtons() {
	for(var i=0; i<ARbuttons.length; i+=2) {
		document.getElementById(ARbuttons[i]).src=ARbuttons[(i+1)];
	}
}

//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\\
//lbnavigation buttons
//Go to the picture on the right
function goRight() {
	exitSubmenu();
	deletePic();
	if(num==(ARpics.length-1)) {
		num=0;
		startReset();
	}
	else {
		num++;
		startReset();
	}
	return false;
}

//Go to the picture on the left
function goLeft() {
	exitSubmenu();
	deletePic();
	if(num==0) {
		num= ARpics.length-1;
		startReset();
	}
	else {
		num--;
		startReset();
	}
	return false;
}

//exits the image viewer
function exitViewer() {
	exitSubmenu();
	document.getElementById('shade').style.visibility='hidden';
	document.getElementById('container').style.visibility='hidden';
	deletePic();
	return false;
}

//deletes the present picture to help reset
function deletePic() {
	document.getElementById('box').removeChild(document.getElementById('lbimg'));
}

//View more pictures
var ifClicked = false;
function viewMore() {
	if(ifClicked) {
		ifClicked = false;
		//stopped = true;
		clearInterval(interval);
		deleteSubImg();
		document.getElementById('sub').src='buttons/lbmore.png';
		document.getElementById('submenu').style.visibility='hidden';
		document.getElementById('extras').style.visibility = 'hidden';
		document.getElementById('extras').style.height='0px';
		document.getElementById('extras').style.width='0px';
		document.getElementById('submenu').style.height='0px';
		document.getElementById('submenu').style.width='0px';
		document.getElementById('submenu').style.bottom='0px';
	}
	else {
		ifClicked = true;
		addSubDivs();
		setSubPic();
		document.getElementById('sub').src='buttons/lbless.png';
		document.getElementById('submenu').style.visibility='visible';
		document.getElementById('submenu').style.top='40px';
		document.getElementById('submenu').style.width='0px';
		document.getElementById('submenu').style.height='0px';
		document.getElementById('extras').style.height='auto';
		document.getElementById('extras').style.width='auto';
		stopped = false;
		intervalSet("moveDown()");
	}
	return false;
}

function deleteSubImg() {
	for(var i=0; i<ARpics.length; i++) {
		document.getElementById('sma'+i).removeChild(document.getElementById('cImg'+i));
	}
	removeChildren(document.getElementById('extras'));
}

function removeChildren(node) {
	if(node.hasChildNodes()) {
		while(node.childNodes.length >= 1 ) {
			node.removeChild(node.firstChild);
		}
	}
}

function exitSubmenu() {
	if(ifClicked) {
		ifClicked = false;
		//stopped = true;
		clearInterval(interval);
		deleteSubImg();
		document.getElementById('sub').src='buttons/lbmore.png';
		document.getElementById('submenu').style.visibility='hidden';
		document.getElementById('extras').style.visibility = 'hidden';
		document.getElementById('submenu').style.height='0px';
		document.getElementById('submenu').style.width='0px';
		document.getElementById('extras').style.height='0px';
		document.getElementById('extras').style.width='0px';
	}
	else {
		
	}
}

var spreadSize=0;

//Move the menu down
function moveDown() {
	//if(!stopped) {
		spreadSize = document.getElementById('submenu').style.height.split('px')[0]/1;
		if((spreadSize) < 345)
		{
			document.getElementById('submenu').style.height = (((spreadSize) + spreadDist) + 'px');
			//setTimeout("moveDown()",15);
		}
		else {
			document.getElementById('submenu').style.height = "350px";
			clearInterval(interval);
			intervalSet("spreadOut()");
		}
	//}
	//else {}
}

//Spreads the menu out
function spreadOut() {
	//if(!stopped) {
		spreadSize = document.getElementById('submenu').style.width.split('px')[0]/1;
		if(spreadSize < 405)
		{
			document.getElementById('submenu').style.width = ((spreadSize + spreadDist) + 'px');
			//setTimeout('spreadOut()',15);
		}
		else
		if((spreadSize) == 405) {
			clearInterval(interval);
			document.getElementById('extras').style.visibility = 'visible';
		}
	//}
	//else{}
}

var spreadDist = 0;
function ie8test() {
	spreadDist = navigator.appVersion.indexOf("compatible; MSIE 8.0;") > -1 ? 15 : 5;
	//alert(spreadDist);
}

function intervalSet(funct) {
	interval = setInterval(funct, 15);
	//alert(interval);
}
