var space = 91;
//var viewerPicWidth = 320;
//var viewerPicHeight = 240;
var viewerPicArea = 320;
var outsideMargin = 10;
var thumbPicMaxHeight = 71;
var curPos = 0;
var clickable = true;
var picClickable = true;
var lastID;

window.onload = initPage;

function initPage() {
tnAdjust();
chooseIt(0);
}

function tnAdjust() {
for (i=0; i<info.length; i++) {
imH = document.getElementById("img"+i).height;
document.getElementById("spacer"+i).height = parseInt((thumbPicMaxHeight-imH)/2);
}
}

function tnLoadCheck() {
count=0;
for (i=0; i<info.length; i++) {
 infoSplit = info[i].split(':');
 tnTemp = new Image();
 tnTemp.src = "images/gallery/thumbs/"+infoSplit[0];;
 if (tnTemp.complete) {
  count++;
 }
}
if (count < info.length) {
// alert(count+' - '+info.length);
 setTimeout("tnLoadCheck()", 500);
} else {
 document.getElementById('loadingRoll').style.display = 'none';
 document.getElementById('loadingBack').style.display = 'none';
 tnAdjust(); // Adjust the height of each spacer .gif above each newly loaded thumbnail.
 chooseIt(0);
}
}

function showBigStart() {
infoSplit = info[picID].split(':');
if (infoSplit[2] == 'no') {
 return false;
}
picTemp = new Image(); // Reset picTemp so that it "picTemp.complete" will give a reading on the newly loading picture.
picTemp.src = "images/gallery/large/"+infoSplit[0];
document.getElementById('loadingPic').style.display = 'block';
if (picTemp.complete) { // Check to see if the image is already in the browser cache.
 showBigFinish(infoSplit[1]);
} else { // Image is not in the browser cache and is in the process of loading. Call function when it has completed loading.
 picTemp.onload = function() { showBigFinish(infoSplit[1]); };
}
}

function showBigFinish(info) {
info += '<div style="text-align: right;"><a href="javascript:;" onclick="hideBig()">Back to Gallery</a></div>';
darkenPage();
screenWidth = 775;
screenHeight = f_clientHeight();
scrollPosTop = f_scrollTop();
picWidth = picTemp.width;
picHeight = picTemp.height;
picLeft = parseInt((screenWidth-picWidth)/2);
picTop = parseInt(((screenHeight-105)-picHeight)/2);
objx = document.getElementById('bigPic');
objx.src = picTemp.src;
objx.width = picWidth;
objx.height = picHeight;
objy = document.getElementById('bigPic_container');
objy.style.display = 'block';
objy.style.left = picLeft+'px';
objy.style.top = scrollPosTop+picTop+'px';
objy.style.width = picWidth+2+'px';
document.getElementById('bigPic_text').innerHTML = info;
document.getElementById('loadingPic').style.display = 'none';

obj = document.getElementById('bigPic');
var steps = time * fps;

if (typeof obj.style.opacity != 'undefined') {
 var otype = 'w3c';
} else if (typeof obj.style.MozOpacity != 'undefined') {
 otype = 'moz';
} else if (typeof obj.style.KhtmlOpacity != 'undefined') {
 otype = 'khtml';
} else if (typeof obj.filters == 'object') {
 otype = 'ie';
} else {
 otype = 'none';
}

dofade(steps, obj, 0, true, otype); // Fade in
}

function hideBig() {
document.getElementById('bigPic_container').style.display = 'none';
lightenPage();
}

function darkenPage() {
pageScreen = document.getElementById('page_screen');
pageScreen.style.height = document.body.parentNode.scrollHeight + 'px';
pageScreen.style.display = 'block';
}

function lightenPage() {
pageScreen = document.getElementById('page_screen');
pageScreen.style.display = 'none';
}

function scroll(dir) {
if (!clickable) {
 return false;
}
 if (dir == 'forward') {
  if (Math.abs(curPos)/space < totalRows-1) {
   target = curPos-space;
  } else {
   return false;
  }
 } else {
  if (Math.abs(curPos)/space > 0) {
   target = curPos+space;
  } else {
   return false;
  }
 }
 doScroll(dir, target);
}

function doScroll(dir, target) {
clickable = false;
curPos = (dir == 'forward') ? curPos-10:curPos+10;
document.getElementById('tn').style.top = curPos+'px';
if ((dir == 'forward' && curPos > target) || (dir == 'backward' && curPos < target)) {
 scrolling = setTimeout("doScroll('"+dir+"', "+target+")", 1);
} else {
 document.getElementById('tn').style.top = target+'px';
 curPos = target;
 document.getElementById('row').innerHTML = (Math.abs(curPos)/space)+1 + ' of '+totalRows;
 clickable = true;
}
}

var posx = 0;
var posy = 0;

//function doSomethingInit() {
document.onmousemove = doSomething;
//}

function doSomething(e) {

	if (!e) var e = window.event;
	if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
	}

    winSize = windowSize();
    
    centerOffset = (posx < (winSize[0]+140)/2) ? 12:-210;
	
	document.getElementById('hoverDiv').style.top = posy-25 + 'px';
	document.getElementById('hoverDiv').style.left = posx+centerOffset + 'px';
	
	//document.FormName.top.value = posy;
	//document.FormName.left.value = posx;
	// posx and posy contain the mouse position relative to the document
	// Do something with this information
}

function killSomething() {
 // Do nothing, which kills the movement of the div.
}

function hoverDiv(option, div_name, id) {
//document.onmousemove = doSomething;
obj = document.getElementById(div_name);
info_split = info[id].split(":");
document.getElementById('hoverDiv').innerHTML = info_split[1];
if (option == 'show') {
//	obj.style.top = posy-20 + 'px';
//	obj.style.left = posx+20 + 'px';
	obj.style.display = 'block';
} else {
// document.onmousemove = killSomething;
 obj.style.display = 'none';
}
}

function windowSize() {
  var myWidth = 0, myHeight = 0;
  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;
  }
//  window.alert( 'Width = ' + myWidth );
//  window.alert( 'Height = ' + myHeight );
  return [myWidth,myHeight];

}

var fps = 20;
var time = .4;
var picFrameId = 'galleryPic';
var picID;
var picTemp;

function chooseIt(id) {
if (info.length < 1) { // There are no pictures in this roll to display.
 document.getElementById('tn').innerHTML = '<div style="color: #fc0; font-weight: bold; text-align: center; padding: 30px">Pictures coming...</div>';
 document.getElementById(picFrameId).src = 'images/spacer.gif';
 return false;
}

if (picID == id || !picClickable) { // This is the current picture. No need to load/fade it again.
 return false;
}

picID = id; // set the pic ID to the global picID.
picClickable = false;

// Begin to preload the chosen picture while the current picture is faded out.
info_split = info[picID].split(":");
document.getElementById('large').innerHTML = (info_split[2] == 'yes') ? '<span style="font-weight: bold; color: green">Click the picture to see a larger version.</span>':'<span style="font-weight: bold; color: red">There is no larger picture.</span>';

picTemp = new Image(); // Reset picTemp so that it "picTemp.complete" will give a reading on the newly loading picture.
picTemp.src = "images/gallery/medium/"+info_split[0];

// Set the newly selected picture border to blue instead of yellow.
if (lastID != undefined) {
 document.getElementById('img'+lastID).className = '';
}
document.getElementById('img'+picID).className = 'tn_pic_selected';

lastID = picID; // Save newly chosen variable in the global lastID.

obj = document.getElementById(picFrameId);
var steps = time * fps;

if (typeof obj.style.opacity != 'undefined') {
 var otype = 'w3c';
} else if (typeof obj.style.MozOpacity != 'undefined') {
 otype = 'moz';
} else if (typeof obj.style.KhtmlOpacity != 'undefined') {
 otype = 'khtml';
} else if (typeof obj.filters == 'object') {
 otype = 'ie';
} else {
 otype = 'none';
}

dofade(steps, obj, 1, false, otype); // Fade out
}

function dofade(steps, obj, value, targetvisibility, otype) {
  value += (targetvisibility ? 1 : -1) / steps;
  if (targetvisibility ? value > 1 : value < 0) {
    value = targetvisibility ? 1 : 0;
  }

  setfade(obj, value, otype);

  if (targetvisibility ? value < 1 : value > 0) {
    setTimeout(function() { dofade(steps, obj, value, targetvisibility, otype); }, 1000 / fps);
  } else {
    if (targetvisibility == false) { // insert the new text and begin the fade in.
      checkLoad(steps, obj, otype);
    } else {
     // The fade out, loading, and fade in are complete.
     picClickable = true;
    }
  }
}

function insertText(steps, obj, otype) {
info_split = info[picID].split(":");
document.getElementById('frame_text').innerHTML = info_split[1];
objx = document.getElementById('galleryPic');
objx.src = picTemp.src;
objx.width = picTemp.width;
objx.height = picTemp.height;
marginLR = parseInt((viewerPicArea - objx.width) / 2) + outsideMargin;
marginTB = parseInt((viewerPicArea - objx.height) / 2) + outsideMargin;
document.getElementById('galleryPic').style.margin = marginTB+'px '+marginLR+'px';

dofade(steps, obj, 0, true, otype);
}

// Check if new picture is fully loaded yet.
function checkLoad(steps, obj, otype) {
if (picTemp.complete) {
 document.getElementById('loadingPic').style.display = 'none';
 //dofade(steps, obj, 0, true, otype);
 insertText(steps, obj, otype);
} else {
 document.getElementById('loadingPic').style.display = 'block';
 timerID = setTimeout(function() { checkLoad(steps, obj, otype); },10); 
}
}

function setfade(obj, value, otype)
{
  switch(otype)
  {
    case 'ie':
//      obj.filters.alpha.opacity = value * 100;
      obj.style.filter = 'alpha(opacity='+value * 100+')';
      break;

    case 'khtml':
      obj.style.KhtmlOpacity = value;
      break;

    case 'moz':
      obj.style.MozOpacity = (value == 1 ? 0.9999999 : value);
      break;

    default:
      obj.style.opacity = (value == 1 ? 0.9999999 : value);
  }
}

function loadRoll(rid) {
if (rid == rollID) { // This is the current roll showing. No need to load it again.
 return false;
}

req = createXMLHttpRequest();
if (!req) {
 location.href="photo_gallery.php?roll_id="+rid;
}

document.getElementById('loadingBack').style.display = 'block';
document.getElementById('loadingRoll').style.display = 'block';

url = 'ajax_process.php?action=loadroll&roll_id='+rid+'&pics_per_row='+picsPerRow;
req.open('GET', url, true);
req.onreadystatechange = handleResponse;
req.send(null);
return false;
}

function handleResponse() {
  if(req.readyState == 4){
    if (req.status == 200) {
      var response = req.responseText;
      document.getElementById('tn').style.top = '0px';
      curPos = 0;
      picID = undefined; // Reset picID.
      rollSplit = response.split('~');
      document.getElementById('tn').innerHTML = rollSplit[2];
      infoSplit = rollSplit[3].split('|');
      info = []; // IMPORTANT! This empties the array of all indexes.
      for (i=0; i<infoSplit.length; i++) {
       iaSplit = infoSplit[i].split('^');
       info[iaSplit[0]] = iaSplit[1];
      }
      document.getElementById('roll_title').innerHTML = rollSplit[1];
      lastID = undefined; // Clear out lastID
      rollID = rollSplit[0]; // Set the rollID variable to newly loaded roll ID
//      document.getElementById('loadingRoll').style.display = 'none';
//      document.getElementById('loadingBack').style.display = 'none';
//      tnAdjust(); // Adjust the height of each spacer .gif above each newly loaded thumbnail.
      totalRows = rollSplit[4];
      document.getElementById('row').innerHTML = '1 of '+rollSplit[4];
//      chooseIt(0);
      tnLoadCheck();
    }
  }
}

var req;

function createXMLHttpRequest() {
var request = false;

try {
     request = new XMLHttpRequest();
   } catch (trymicrosoft) {
     try {
       request = new ActiveXObject("Msxml2.XMLHTTP");
     } catch (othermicrosoft) {
       try {
         request = new ActiveXObject("Microsoft.XMLHTTP");
       } catch (failed) {
         request = false;
       }  
     }
   }
  return request;
}

function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function f_clientHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}
