// galleries.js copyright 2010 Walter Bowie All rights reserved.

// Galleries
// needed support files:
// directories_get.php
// images_get.php
// gallery_functions.php

// 1. on page load, galleries_get is called , which calls directories_get.php , which returns a javascript style array which is evaluated to create a global array "galleries"
//     the div of id "gallery_list" is populated with links in galleries_got . the links can be styled with #gallery_list a:link {} , etc.
// 2. the first gallery is then loaded with gallery_load , which calls images_get.php , which returns a javascript style array , which is stored in the global array "images"
// 3. images are loaded one at a time from the list, displaying the first one as soon as it is loaded in the img with the id "photo" 

// if we don't want directories, just one image gallery , call image_gallery_load(dir) from the page 

var xmlHttp; // for AJAX, global
var xmlHttp2; // for txt transfers
var timerID = 0;// timer for image loading, this works a lot better when it is a number rather than a string, global
var galleries; // array of directories , global
var gallery_current = 0; // the current gallery , global
var images; // array of current images in gallery , global
var path_top; // the top level directory passed to us , global
var thumb_num = 0; // counter for index of thumb that we are loading, global
var thumb_selected = 0;// the currently selected image, global
var hasText = true;
var areWebsites = false;
var areVideos = false;
var callerPath = "";
var videoSkin ="Corona_Skin_2"; // this is the default if not specified from the calling page
var videoPlayer = "FLVPlayer_Progressive.swf";

// this function loads a list of directories on the server within the specified path that will act as image galleries
// This function should be called at page load
// initialses "galleries" with an array of directory names
// it also initializes path_top , which is the path that the galleries are contained within 
function galleries_get(pathAllGalleries,pathThisGallery)
{ 
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null){ alert ("Browser does not support HTTP Request"); return; }
// we have to know where the calling page is located relative to us, i.e. portfolio/galleries.js , in which case locationGalleryFunctions should be 'portfolio'
callerPath = pathAllGalleries;
if(callerPath != "")callerPath += "/";
// store this location, which is the subdirectory where the gallery is
path_top = pathThisGallery + "/"; // add the slash so if there is only one gallery via image_gallery_load , we wont end up with a leading slash
// this php will pass back a javascript style new Array() that we will evaluate to populate galleries
var url= callerPath + "directories_get.php";
url=url+"?path="+pathThisGallery;
xmlHttp.onreadystatechange=galleries_got; 

xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}

// when we get back a response , we convert it into an actual javascript array with eval and store it into "galleries"
function galleries_got() 
{ 
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 { 
 // we are getting a response in the form "new Array("one","two");" , evaluate it to create a javascript array
 //document.getElementById("website_box").innerHTML=xmlHttp.responseText;
 galleries = eval( xmlHttp.responseText );
 
 var inner = "<ul id=\"gallery_ul\">";
 // loop through all of the directory names
 for(var i = 0; i < galleries.length; i++){
	 // remove underscores in the dislayed name if they exist
	 var no_underscore = galleries[i].replace( new RegExp( "_", "g" ), " " );
	 // we may want ampersands in the display for the cute wedding crowd, put AMP in the filename to substitute
	 var want_ampersand = no_underscore.replace( new RegExp( "AMP", "g" ), " & " );
	 // build one long string of links that will be put into innerHTML
	 inner += "<li><a id=\"gallery_" + i + "\" href=\"javascript:gallery_load(" + i + ")\">" + want_ampersand + "<\/a><\/li>";
 }
 inner += "</ul>";
 // put the links into the div
 document.getElementById("gallery_list").innerHTML=inner;
 // if we have a ?name=xxx , make that the current gallery
 var name = getURLArg("name");
 //alert(name);
 if( name != null){
	 var index = 0;
	 for(var i = 0; i < galleries.length; i++){
		 if(galleries[i] == name)index = i; 
	 }
	 gallery_select(index);
	 gallery_load(index);
 }
 else {
     // if there are more than 1 directory , select
     if(galleries.length > 1){ gallery_select(0);}
     // if there is at least one gallery , load it
     if(galleries.length > 0){ gallery_load(0); }
 }
 
 } 
}
// this function gets a named parameter of a url address, so that we can go to a specific directory
function getURLArg(key_str) {
	if(window.location.search) {
		var query = window.location.search.substr(1);
		var pairs = query.split("&");
		for(var i = 0; i < pairs.length; i++) {
			var pair = pairs[i].split("=");
			if(unescape(pair[0]) == key_str)
				return unescape(pair[1]);
		}
	}
	return null;
}
function gallery_select(index){
	// desect old selected thumb
	document.getElementById("gallery_" + gallery_current).className = "";
	// select new thumb
	document.getElementById("gallery_" + index).className = "on";
	//document.getElementById("thumb_" + index).setAttribute('className' , 'thumb_nail_image_on');
	// store the number
	//gallery_cuurent = index;
}

// when we don't want a list of galleries, we use this function that fakes a directory list and only displays one directory
function image_gallery_load(pathAllGalleries,dir)
{ 
 path_top = "";
 // we have to know where the calling page is located relative to us, i.e.    portfolio/galleries.js , in which case locationGalleryFunctions should be 'portfolio'
 callerPath = pathAllGalleries;
 if(callerPath != "")callerPath += "/";

 galleries = new Array();
 galleries[0] = dir;
 gallery_current = 0;
 gallery_load(0);
}

//
function gallery_load(index)
{ 
 // if there are more than 1 directory , select
 if(galleries.length > 1){ gallery_select(index);}
gallery_current=index;
var path = path_top + galleries[index];
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null){ alert ("Browser does not support HTTP Request");return;}
var url= callerPath + "images_get.php"
url=url+"?path="+path
xmlHttp.onreadystatechange=gallery_loaded
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}

function gallery_loaded() 
{ 
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 { 
     //alert(xmlHttp.responseText);
	 //document.getElementById("website_box").innerHTML=xmlHttp.responseText;
	 images = eval( xmlHttp.responseText );
	 //trace();
	 if(images.length > 0){
		 // display thumbs
		 var inner = "<ul class=\"thumb_nail\" id=\'thumb_list\'>";
		 //inner += create_thumb(0);
		 inner += "</ul>";
		 document.getElementById("gallery_thumbs").innerHTML=inner;
		 //gallery_change_image(path_top  + galleries[gallery_current] + "/" + images[0]);
		 thumb_num = 0;
		 thumb_selected=0;
		 busy_on(); 
		 load_thumbs();
		 
	 } 
 }
}


// brings up a busy icon over the image when a gallery is loading its first image
function busy_on(){
	var e = document.getElementById("busy");
	 e.style.visibility = "visible";

}
// makes the busy icon disappear
function busy_off(){
	var e = document.getElementById("busy");
	 e.style.visibility = "hidden";

}

// creates a thumb link based on the index and attaches it to the "thumb_list" div
function create_thumb(image_index){
	var path = callerPath + path_top + galleries[gallery_current];
		var li = document.createElement("li");
		var a = document.createElement("a");
		if(areVideos){a.href = "javascript:gallery_change_video(" + image_index + ")";}
		else { a.href = "javascript:gallery_change_image(" + image_index + ")"; }
		a.className = "test";
		var img = document.createElement("img");
		img.className = "thumb_nail_image";
		img.src = path + "/" + images[image_index];
		img.id = "thumb_" + image_index;
		a.appendChild(img);
		li.appendChild(a);
		document.getElementById("thumb_list").appendChild(li);
}

// creates a thumb then triggers a function to check on loading status
// program flow bounces back and forth between load_thumbs() and check_image() until all of the images are loaded
function load_thumbs(){
		// we'll set the off_screen-img width to 0 as a flag to know when it has loaded fully ( the .complete does not mean we have a width and height yet)
		//document.off_screen_img.width = "";
        create_thumb(thumb_num);
			// even when the image has loaded completely, the height and width attributes may not be valid, we will load it into the off_screen_img and check size
    //var img = callerPath + path_top + galleries[gallery_current] + "/" + images[thumb_num];
    // this loads the image into a div that is never displayed so we can check it's native size
    //document.getElementById("off_screen_img").src = img;
	    timerID = setInterval('check_image()', 100); // if this is too small, image object may not be fully initialized
}

function check_image() {
	var id = "thumb_" + thumb_num; 

  if (document.getElementById(id).complete) {



	//if(document.off_screen_img.width != ""){
	    // stop the timer
	    clearInterval(timerID);
        // special case if this is the first one because the gallery was just loaded , turn off the busy icon , load the image into display area , select thumb
	    if(thumb_num == 0){ 
	        busy_off(); 
		    if(areVideos){gallery_change_video(0);}
		    else {gallery_change_image(0);}
		    thumb_select(0);
		}
	    if(thumb_num == 1){ if(!areVideos)gallery_change_image(0);} // sometimes, the image displayed keeps the size attributes of the old image, this ensures that the first image was loaded fully
	    if(thumb_num < images.length-1){ // -1 because we increment in the loop
			thumb_num++;
	        load_thumbs();
	    } // if thumb_num
	//} // if loaded into off_screen_img
   } // complete
} 



// turns the opacity on full for the image thumb being displayed , depends on thumb_selected to store the current one
// thumb_selected has to be reset when a new gallery is loaded to avoid javascript getElementById error
function thumb_select(index){
	// desect old selected thumb
	document.getElementById("thumb_" + thumb_selected).className = "thumb_nail_image";
	// select new thumb
	document.getElementById("thumb_" + index).className = "thumb_nail_image_on";
	//document.getElementById("thumb_" + index).setAttribute('className' , 'thumb_nail_image_on');
	// store the number
	thumb_selected = index;
}
// use this function to output to divs for testing / troubleshooting 
function trace(){
	//document.getElementById("xmlHttp").innerHTML = xmlHttp;
	document.getElementById("out2").innerHTML = timerID;
	document.getElementById("out3").innerHTML = galleries[0];
}

// this loads the image off screen to examine size, then scales it to fit into the display area (photo_display div) 
function gallery_change_image(image_index) {
  var img = callerPath + path_top + galleries[gallery_current] + "/" + images[image_index];
  // this loads the image into a div that is never displayed so we can check it's native size
  document.getElementById("off_screen_img").src = img;
  //document.getElementById("output").innerHTML = document.off_screen_img.width;
  var width = document.off_screen_img.width;
  var height = document.off_screen_img.height;
  //document.getElementById("text_box").innerHTML="width= " + width + "height= " + height;
  var aspect =  height / width;
  // get the width and height of container so we can calculate scaled size
  var box_width = document.getElementById("photo_display").clientWidth;
  var box_height = document.getElementById("photo_display").clientHeight;
  var box_aspect =  box_height / box_width;
  //document.getElementById("output").innerHTML = "width=" + width;
  var photo =  document.getElementById("photo");
  
	  if(width > height) { // we will display it horizontaly
		  if(box_aspect >= aspect){
			  scaled_height = Math.floor((height / width) * box_width);
			  photo.src = img;
			  photo.width = box_width;
			  photo.height = scaled_height;
			  //document.getElementById("website_box").innerHTML="w>h box_aspect >= aspect";
		  }
		  else {
			  scaled_width = Math.floor((width / height) * box_height);
			  photo.src = img;
			  photo.width = scaled_width;
			  photo.height = box_height;
			  //document.getElementById("website_box").innerHTML="w>h aspect > box_aspect";
		  }
	  }
	  // height > width
	  else { // we will display it vertically
		  if(aspect >= box_aspect){
			  scaled_width = Math.floor((width / height) * box_height);
			  photo.src = img;
			  photo.width = scaled_width;
			  photo.height = box_height;
			  //document.getElementById("website_box").innerHTML="h>w box_aspect >= aspect";
		  }
		  else {
			  scaled_height = Math.floor((height / width) * box_height);
			  photo.src = img;
			  photo.width = box_width;
			  photo.height = scaled_height;
			  //document.getElementById("website_box").innerHTML="h>w aspect > box_aspect";
		  }
	  }
  
  // select icon
  thumb_select(image_index);
  //document.getElementById("text_box").innerHTML="hi";
  if(hasText){
	  // convert image name to name with .txt extension
	  //var dotIndex = img.lastIndexOf(".");
	  var txtName = strip_extension(path_top + galleries[gallery_current] + "/" + images[image_index]);
	  txtName += ".txt";
	  //document.getElementById("text_box").innerHTML="hi";
	  text_get(txtName);
	  
  }
  if(areWebsites){
	  // convert image name to name with .txt extension
      var name = strip_extension(images[image_index]);
	  var url= "<a href=\"http://" + name + "\" target=\"_blank\">Visit site</a>";
	  document.getElementById("website_box").innerHTML=url;
  }
}

function gallery_change_video(image_index) {
var img = callerPath + path_top + galleries[gallery_current] + "/" + images[image_index];
document.getElementById("off_screen_img").src = img;
var path = callerPath + path_top + galleries[gallery_current] + "/";
var width = document.off_screen_img.width;
var height = document.off_screen_img.height;

var streamName = strip_extension(images[image_index]) + ".flv";

// you can set the path for the skinName and the .flv file, 
// the path of the video file is relative to the plater file
skinName = path + videoSkin;
player = path + videoPlayer;
//skinName ="portfolio/videos/Clear_Skin_2";
//player = "portfolio/videos/FLVPlayer_Progressive.swf";


var flashObject = "<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0\" id=\"FLVPlayer\" width=\"" + width + "\" height=\"" + height + "\"><param name=\"id\" value=\"FLVPlayer\" /><param name=\"width\" value=\"" + width + "\" /><param name=\"height\" value=\"" + height + "\" /><param name=\"salign\" value=\"lt\" /><param name=\"quality\" value=\"high\" /><param name=\"scale\" value=\"noscale\" /><param name=\"flashvars\" value=\"&MM_ComponentVersion=1&skinName=" + skinName + "&streamName="  +  streamName + "&autoPlay=true&autoRewind=false\" /><param name=\"src\" value=\"" + player + "\" /><embed type=\"application/x-shockwave-flash\" id=\"FLVPlayer\" width=\"" + width + "\" height=\"" + height + "\" salign=\"lt\" quality=\"high\" scale=\"noscale\" flashvars=\"&MM_ComponentVersion=1&skinName=" + skinName + "&streamName=" + streamName + "&autoPlay=true&autoRewind=false\" src=\"" + player + "\"></embed></object>";

document.getElementById("photo_display").innerHTML=flashObject;

  thumb_select(image_index);
  if(hasText){
	  // convert image name to name with .txt extension
	  //var dotIndex = img.lastIndexOf(".");
	  var txtName = strip_extension(path_top + galleries[gallery_current] + "/" + images[image_index]);
	  txtName += ".txt";
	  text_get(txtName);
	  //document.getElementById("text_box").innerHTML=txtName;
  }
}

function text_get(filename)
{ 
// USES a new xmlHttp2 because thumbs could still be loading!!!
xmlHttp2=GetXmlHttpObject();
if (xmlHttp2==null){ alert ("Browser does not support HTTP Request"); return; }

// this php will pass back the text that is contained in the file
var url= callerPath + "text_get.php?filename="+filename;
xmlHttp2.onreadystatechange=text_got; 
xmlHttp2.open("GET",url,true);
xmlHttp2.send(null);
}

function text_got() 
{ 
if (xmlHttp2.readyState==4 || xmlHttp2.readyState=="complete")
 { 
 document.getElementById("text_box").innerHTML=xmlHttp2.responseText;
 }
}

function strip_extension(filename){
	var dotIndex = filename.lastIndexOf(".");
	return(filename.slice(0,dotIndex));
}

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;
}

