// BetterInnerHTML v1.15 - by Craig Buckler, http://www.optimalworks.net/
function bhi(_1,_2,_3){function Load(_4){var _5;if(typeof DOMParser!="undefined"){_5=(new DOMParser()).parseFromString(_4,"application/xml");}else{var _6=["MSXML2.DOMDocument","MSXML.DOMDocument","Microsoft.XMLDOM"];for(var i=0;i<_6.length&&!_5;i++){try{_5=new ActiveXObject(_6[i]);_5.loadXML(_4);}catch(e){}}}return _5;}function Copy(_8,_9,_a){if(typeof _a=="undefined"){_a=1;}if(_a>1){if(_9.nodeType==1){var _b=document.createElement(_9.nodeName);for(var a=0,attr=_9.attributes.length;a<attr;a++){var _d=_9.attributes[a].name,aValue=_9.attributes[a].value,evt=(_d.substr(0,2)=="on");if(!evt){switch(_d){case "class":_b.className=aValue;break;case "for":_b.htmlFor=aValue;break;default:_b.setAttribute(_d,aValue);}}}_8=_8.appendChild(_b);if(evt){_8[_d]=function(){eval(aValue);};}}else{if(_9.nodeType==3){var _e=(_9.nodeValue?_9.nodeValue:"");var _f=_e.replace(/^\s*|\s*$/g,"");if(_f.length<7||(_f.indexOf("<!--")!=0&&_f.indexOf("-->")!=(_f.length-3))){_8.appendChild(document.createTextNode(_e));}}}}for(var i=0,j=_9.childNodes.length;i<j;i++){Copy(_8,_9.childNodes[i],_a+1);}}_2="<root>"+_2+"</root>";var _11=Load(_2);if(_1&&_11){if(_3!=false){while(_1.lastChild){_1.removeChild(_1.lastChild);}}Copy(_1,_11.documentElement);};}


/**
 * @author Christian Flanagan
 * Date: 2.1.09
 * Functions for retrieving Picasa Web Album data and 
 * contents for the RMSA Website Photo Gallery
 */


// Preload rollover graphic for buttons
var o_btns = new Image();
o_btns.src = "images/glry_btn_over_bkgd.gif";

// Preload enabled graphic for buttons
var e_btns = new Image();
e_btns.src = "images/glry_btn_bkgd.gif";

// Preload preloader graphics
var prld1 = new Image();
prld1.src = "images/preloader1.gif";
var prld2 = new Image();
prld2.src = "images/preloader2.gif";
var prld3 = new Image();
prld3.src = "images/preloader3.gif";

// Preload close button
var closeBtn = new Image();
closeBtn.src = "images/glry_closeBtn.gif";

// Preload dialog titlebar background
var closeBtn = new Image();
closeBtn.src = "images/glry_dialog_titlebar_bkgd.gif";

//Holds album data for currently selected album
var album = new Array();

//Holds the currently selected album ID
var albumId = "";

//Holds the currently selected album description
var albumDescription = "";

//Holds the currently selected photo ID
var photoId = "";

//Holds the currently selected photo title
var photoTitle = "";

//Holds the currently selected photo tags (Keywords)
var photoKeywords = "";

//Holds a reference to the last user-selected thumbnail wrapper
var currentSelection;

//Holds a reference to the last user-selected thumbnail image
var currentImage;

//Form Type Selection
var formType = "";

//Current Server Time and Date
var today = "";

//Anything that's needed to initialize the gallery goes here.
function init(){
    var addAlbumBtn = document.getElementById('addAlbum');
	var searchBtn =  document.getElementById('search');
	if(addAlbumBtn) {
		enableDisabledBtn('addAlbum');
	}
	if(searchBtn) {
		enableDisabledBtn('search');
	}
}

//Enable disabled buttons
function enableDisabledBtn (id) {
	//console.log("ID Passed "+id);
	var btn = document.getElementById(id);
	if (btn) {
		//Change background image
		btn.style.backgroundImage = "url(images/glry_btn_bkgd.gif)";
		//Respond to mouse gestures
		btn.onmouseover = function(){
			this.style.cursor = "pointer";
			this.style.backgroundImage = "url(images/glry_btn_over_bkgd.gif)";
			this.style.color = "#f00";
		}
		btn.onmouseout = function(){
			this.style.cursor = "default";
			this.style.backgroundImage = "url(images/glry_btn_bkgd.gif)";
			this.style.color = "#fff";
		}
		
		if (id == "addComment") {
			//Respond to click
			btn.onclick = function(){
				getTimeDate();
			}
		}
		else {
			//Respond to click
			btn.onclick = function(){
				getForm(this.id);
			}
		}
	}
}

//Ajax send request moves data between PHP/Picasa interface and JavaScript
function sendRequest(url, callback, postData){
    var req = createXMLHTTPObject();
    if (!req) 
        return;
    var method = (postData) ? "POST" : "GET";
    req.open(method, url, true);
    req.setRequestHeader('User-Agent', 'XMLHTTP/1.0');
    if (postData) 
        req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    req.onreadystatechange = function(){
        if (req.readyState != 4) 
            return;
        if (req.status != 200 && req.status != 304) {
            alert('HTTP error ' + req.status);
            return;
        }
        callback(req);
    }
    if (req.readyState == 4) 
        return;
    req.send(null);
}

//XML HTTP Object generator
function createXMLHTTPObject(){
    var xmlhttp = false;
    for (var i = 0; i < XMLHttpFactories.length; i++) {
        try {
            xmlhttp = XMLHttpFactories[i]();
        } 
        catch (e) {
            continue;
        }
        break;
    }
    return xmlhttp;
}

//Array of XMLHttpRequest Objects
var XMLHttpFactories = [function(){
    return new XMLHttpRequest()
}, function(){
    return new ActiveXObject("Msxml2.XMLHTTP")
}, function(){
    return new ActiveXObject("Msxml3.XMLHTTP")
}, function(){
    return new ActiveXObject("Microsoft.XMLHTTP")
}
];

//Returns a set of option tags for the album combo box
function getAlbumList(){
	// Place preloader graphic
	var menuArea = document.getElementById('glry_select');
	var preloader = '<img id="preloader1" src="images/preloader1.gif" width="200" height="25" />';
	bhi(menuArea, preloader, true);
	// Request Album List
    var url = "albumList.php";
    sendRequest(url, processAlbumList, false);
}

//Listens for a change event from the Album combo box
function albumSelectionListener(){
    if (album.length > 0) {
        album = [];
    }
    var albumMenu = document.getElementById('albumList');
    albumMenu.onchange = function(){
        var selectedAlbum = this.options[this.selectedIndex];
        if (selectedAlbum.value) {
			//Get value of selected combo box item
			var temp = selectedAlbum.value;
			//Split Album ID from Number of Photos in Album
			var temp = temp.split("|");
			albumId = temp[0];
			var count = temp[1];
			albumDescription = temp[2];
			var date = temp[3];
			//Request photos from album
            var url = "photoList.php?albumID=" + albumId;
            sendRequest(url, processPhotoList, false);
        }
		if(selectedAlbum.text) {
			var title = document.getElementById('glry_title');
			//Set Album Photo Count Display
			bhi(title, albumDescription + '<span class="totalNum">( Total Photos: ' + count + '  )</span>', true);
		}
		enableDisabledBtn('addPhoto');
		// Place preloader graphic
		var tnArea = document.getElementById('glry_tn');
		var preloader = '<img id="preloader2" src="images/preloader2.gif" width="48" height="48" />';
		bhi(tnArea, preloader, true);
    }
}

//Inserts the option list into the Album menu combo box
function processAlbumList(req){
	var albumMenu = document.getElementById('glry_select');
	var albumList = "";
    if (req.responseText == "Not found") {
        albumList = "<option selected='selected'>No Albums Found</option>";
    } else {
        albumList = req.responseText;
    }
	bhi(albumMenu, albumList, true);
    albumMenu.selectedIndex = 0;
	albumSelectionListener();
}

//Inserts the thumbnail list into the web page
function processPhotoList(req){
	var thumbnails = document.getElementById('glry_tn');
    var tnImages = "";
    if ( req.responseText == "Not found" ) {
		tnImages = "<p>No Images Found</p>";
		bhi(thumbnails, tnImages, true);
    } else {
        //console.log(req.responseText);
		album = eval(req.responseText);
        for ( i in album ) {
			tnImages += '<div class="imgWrapper"><div><img id="tn_' + i + '" src="' + album[i].thumbnailURL + '" width="' + album[i].thumbnailWidth + '" height="' + album[i].thumbnailHeight + '" /></div></div>';
        }
		bhi(thumbnails, tnImages, true);
        thumbnailSelectionListener();
    }
}

//Listens for a click event on a thumbnail
function thumbnailSelectionListener(){
    var thumbnail = document.getElementById('glry_tn');
    var thumbnails = thumbnail.getElementsByTagName('img');
    for ( i in thumbnails ) {
        thumbnails[i].onclick = function () {
            // Display selected image
			displayPhoto(this.id);
			currentImage = this;
        }
    }
	var imgWrappers = thumbnail.getElementsByTagName('div');
	for ( i in imgWrappers) {
		imgWrappers[i].onclick = function () {
			if(currentSelection) {
				currentSelection.style.backgroundColor = '#666';
			}
			this.style.backgroundColor = '#FFC125';
			this.style.cursor = "default";
			currentSelection = this;
		}
		imgWrappers[i].onmouseover = function () {
			if (currentSelection != this) {
				this.style.backgroundColor = '#C33';
				this.style.cursor = "pointer";
			}
		}
		imgWrappers[i].onmouseout = function () {
			if(currentSelection != this) {
				this.style.backgroundColor = '#666';
			} else {
				this.style.backgroundColor = '#FFC125';
			}
			this.style.cursor = "default";
		}
	}
}

//Get URL for Photo
function displayPhoto ( pid ) {
	//Get object to update
    var displayArea = document.getElementById('glry_display');
	var dataArea = document.getElementById('glry_imgData');
	var keywords = document.getElementById('glry_keywords');
	
    //Gather and insert image into display area
	var temp = pid.split('_');
    var indx = temp[1];
	photoId = album[indx].photoID;
	var idName = (album[indx].photoHeight == 576) ? "lrgImageVert" : "lrgImageHorz";
    var img_tag = '<img id="'+idName+'" src="' + album[indx].photoURL + '" width="' + album[indx].photoWidth + '" height="' + album[indx].photoHeight + '" />';
    bhi(displayArea, img_tag, true);
	
	//Gather and insert photo data
	if ( album[indx].photoSummary ) {
		photoTitle = '<div id="photoSummary">'+album[indx].photoSummary+'</div>';
	} else {
		photoTitle = '<div id="photoSummary">No description available</div>';
	}
	bhi(dataArea, photoTitle, true);
	
	//Display any keywords related to the image
	if ( album[indx].photoTags ) {
		photoTags = '<span>Keywords: '+album[indx].photoTags+'</span>';
	} else {
		photoTags = '<span>No tags available</span>';
	}
	bhi(keywords,photoTags,true);
	//Activate the edit photo and add comments buttons
	enableDisabledBtn('editPhoto');
	enableDisabledBtn('addComment');
	//Get comments from Picasa
	getComments(photoId,albumId);
}

//Get Photo Comments
function getComments (pid,aid) {
	var url = "commentList.php?albumID="+aid+"&photoID="+pid;
    sendRequest(url, processCommentList, false);
}

function processCommentList (req) {
	var temp = req.responseText;
	temp = temp.split("|");
	var numOfComments = temp[0];
	var commentList = temp[1];
	
	//Get object
	var commentsCount = document.getElementById('glry_commentCount');
	bhi(commentsCount, "( Comments: "+numOfComments+" )", true);
	//Get object 
	var comments = document.getElementById('glry_comments');
	bhi(comments, commentList, true);
}

function getTimeDate() {
	var url = "getServerTimeDate.php";
	sendRequest(url, processTimeDateRequest, false);
}

// Process the request to commentForm.php
function processTimeDateRequest (req) {
    if ( req.responseText != "Not found" ) {
		today = req.responseText;
		getForm("addComment");
    }
}

// Process User Input forms (One for each UI button)
function getForm (type) {
	var htmlText = "";
	switch (type) {
		/* Search form for future development
		case "search":
			htmlText += '<div id="glry_form">';
			htmlText += '<div id="glry_formTitleBar"><div class="formTitle">Search</div><img id="closeButton" src="images/glry_closeBtn.gif" width="14" height="14" /></div>';
			htmlText += '<div id="glry_formBody">';
			htmlText += '<fieldset>';
			htmlText += '<legend>&#160;&#160;Complete the Search form and then click <span class="emphasis">Search</span>&#160;&#160;</legend>';
			htmlText += '<p>Search looks for keywords associated with a photo that match the text you enter into the input field below.</p>';
			htmlText += '<form id="searchForm" method="post" action="search.php" enctype="multipart/form-data">';
			htmlText += '<p><label for="search">Keyword:</label><br />';
			htmlText += '<input id="search" name="search" type="text" size="60" /></p>';
			htmlText += '<input id="submit" name="submit" type="submit" value="Search" />';
			htmlText += '</form>';
			htmlText += '</fieldset>';
			htmlText += '</div>';
			htmlText += '</div>';
		break;
		*/
		case "addComment":
			htmlText += '<div id="glry_form">';
			htmlText += '<div id="glry_formTitleBar"><div class="formTitle">Add a Comment</div><img id="closeButton" src="images/glry_closeBtn.gif" width="14" height="14" /></div>';
			htmlText += '<div id="glry_formBody">';
			htmlText += '<fieldset>';
			htmlText += '<legend>&#160;&#160;Complete the Comment form and then click <span class="emphasis">Submit</span>&#160;&#160;</legend>';
			htmlText += '<p>You are adding a comment to the currently selected photo.</p><br />';
			htmlText += '<p>Your user name will appear along with your comment. Please keep your comments fun, constructive, informative, or interesting.</p>';
			htmlText += '<form id="commentForm">';
			htmlText += '<p><label for="tags">Comment: </label><br/>';
			htmlText += '<textarea id="commentText" class="comment" name="comment"></textarea></p><br/><br/>';
			htmlText += '<input name="albumId" id="albumId" type="hidden" value="' + albumId + '" />';
			htmlText += '<input name="photoId" id="photoId" type="hidden" value="' + photoId + '" />';
			htmlText += '<input name="userName" id="userName" type="hidden" value="' + userName + '" />';
			htmlText += '<input name="dateStamp" id="dateStamp" type="hidden" value="' + today + '" />';
			htmlText += '<input id="submitComment" type="button" value="Submit" onclick="submitForm(this.id)" />';
			htmlText += '</form>';
			htmlText += '</fieldset>';
			htmlText += '</div>';
			htmlText += '</div>';
		break;
		case "addAlbum":
			htmlText += '<div id="glry_form">';
			htmlText += '<div id="glry_formTitleBar"><div class="formTitle">Create a New Album</div><img id="closeButton" src="images/glry_closeBtn.gif" width="14" height="14" /></div>';
			htmlText += '<div id="glry_formBody">';
			htmlText += '<fieldset>';
			htmlText += '<legend>&#160;&#160;Complete the New Album form and then click <span class="emphasis">Create</span>&#160;&#160;</legend>';
			htmlText += '<p>To create an album, you must include a title and a short description.</p>';
			htmlText += '<form id="addAlbumForm" method="post" action="createAlbum.php" enctype="multipart/form-data">';
			htmlText += '<p><label for="albumName">Title:</label><br />';
			htmlText += '<input id="albumName" name="albumName" type="text" size="25" /></p>';
			htmlText += '<p><label for="albumSummary">Short Description: (e.g. Festival Name, Location, and Date)</label><br/>';
			htmlText += '<input id="albumSummary" name="albumSummary" type="text" size="80" /><br/>';
			htmlText += '(Example: Wyoming Celtic Festival - Gillette, WY - June 27, 2009)</p><br/><br/>';
			htmlText += '<input id="submit" name="submit" type="submit" value="Create" />';
			htmlText += '</form>';
			htmlText += '</fieldset>';
			htmlText += '</div>';
			htmlText += '</div>';
		break;
		case "addPhoto":
			htmlText += '<div id="glry_form">';
			htmlText += '<div id="glry_formTitleBar"><div class="formTitle">Add Photos to the '+albumDescription+' Album</div><img id="closeButton" src="images/glry_closeBtn.gif" width="14" height="14" /></div>';
			htmlText += '<div id="glry_formBody">';
			htmlText += '<fieldset>';
			htmlText += '<legend>&#160;&#160;Complete the Upload Photos form and then click <span class="emphasis">Upload</span>&#160;&#160;</legend>';
			htmlText += '<p>You are adding photos to the '+albumDescription+' album. If you want to add photos to a different album, click the Close button, selected a different album from the drop-down menu, and click the Add Photo button again. To create a new album, <a href="javascript:getForm(\'addAlbum\');">Click Here</a></p><br />';
			htmlText += '<p>To upload a new photo to an album, you must include a title and at least one key word tags.</p>';
			htmlText += '<form id="addPhotoForm" method="post" action="addPhoto.php" enctype="multipart/form-data">';
			htmlText += '<p><label for="photoFile">File to upload: </label><br/>';
			htmlText += '<input id="photoFile" name="photoFile" type="file" /><br/>';
			htmlText += '(Click <span class="emphasis">Browse</span> and select a photo from your computer\'s hard drive.)</p>';
			htmlText += '<p><label for="title">Title: </label><br/>';
			htmlText += '<input id="title" name="title" type="text" size="60" /><br/>';
			htmlText += '(Give the photo a short, clear and consice title.)</p>';
			htmlText += '<p><label for="tags">Tags: </label><br/>';
			htmlText += '<input id="tags" name="tags" type="text" size="60" /><br/>';
			htmlText += '(Add a few keywords. Keywords are used by the seach engine.<br/>Separate keywords with a comma.)</p><br/><br/>';
			htmlText += '<input id="albumId" name="albumId" type="hidden" value="'+albumId+'" />';
			htmlText += '<input id="submit" name="submit" type="submit" value="Upload" />';
			htmlText += '</form>';
			htmlText += '</fieldset>';
			htmlText += '</div>';
			htmlText += '</div>';
		break;
		case "editPhoto":
			htmlText += '<div id="glry_form">';
			htmlText += '<div id="glry_formTitleBar"><div class="formTitle">Edit Photo Data</div><img id="closeButton" src="images/glry_closeBtn.gif" width="14" height="14" /></div>';
			htmlText += '<div id="glry_formBody">';
			htmlText += '<fieldset>';
			htmlText += '<legend>&#160;&#160;Make chages to the forms data and then click <span class="emphasis">Submit</span>&#160;&#160;</legend>';
			htmlText += '<p>You are changing the descriptive and tag metadata for the curretnly selected photo. If you want to edit a different photo\'s data, close the dialog box, select a different photo and click Edit Photo again.</p>';
			htmlText += '<p>You can change a photo\'s title or tags or add more tags. Tags are search keywords, such as a state name, person\'s name, festival name, year the photo was taken, etc.</p>';
			htmlText += '<form id="editPhotoForm" method="post" action="editPhoto.php" enctype="multipart/form-data">';
			htmlText += '<p><label for="title">New Title: </label><br/>';
			htmlText += '<input name="title" id="title" type="text" size="60" /></p>';
			htmlText += '<p><label for="tags">New Tags: </label><br/>';
			htmlText += '<input id="tags" name="tags" type="text" size="60" /></p><br/><br/>';
			htmlText += '<input id="photoId" name="photoId" type="hidden" value="'+photoId+'" />';
			htmlText += '<input id="albumId" name="albumId" type="hidden" value="'+albumId+'" />';
			htmlText += '<input id="submit" name="submit" type="submit" value="Submit" />';
			htmlText += '</form>';
			htmlText += '</fieldset>';
			htmlText += '</div>';
			htmlText += '</div>';
		break;
	}
	//Update the display area
	var display = document.getElementById('glry_display');
	bhi(display,htmlText,true);
	//Make the close button on the dialog box functional
	setCloseBtn(display);
	//Populate fields with existing photo meta data
	if (type == 'editPhoto') {
		var editForm = document.getElementById('editPhotoForm');
		editForm.title.value = photoTitle;
		editForm.tags.value = photoTags;
	}
}

//Handle form submissions
function submitForm(id) {
	var url = "";
	switch (id) {
		case "submitComment":
			var formData = document.getElementById('commentForm');
			var dataFields = formData.getElementsByTagName('input');
			var commentText = document.getElementById('commentText').value;
			url += "addComment.php?comment="+commentText;
			url += "&albumId="+dataFields.albumId.value;
			url += "&photoId="+dataFields.photoId.value;
			url += "&userName="+dataFields.userName.value;
			url += "&timeDate="+dataFields.dateStamp.value;
			sendRequest(url,updateForm,false);
		break;
		case "submitAlbum":
			
		break;
		case "submitPhoto":
			
		break;
		case "submitPhotoEdit":
			
		break;
	}
}

function updateForm (req) {
	var formBody = document.getElementById('glry_formBody');
	bhi(formBody,req.responseText,true);
}

//Functionality for form Close button
function setCloseBtn ( display ) {
	//Activate the Close button
	var btn = document.getElementById('closeButton');
	var clearHTML = '<div></div>';
	//manage cursor
	btn.onmouseover = function () {
		this.style.cursor = "pointer";
	}
	btn.onmouseout = function () {
		this.style.cursor = "default";
	}
	//On click, remove the form.
	btn.onclick = function () {
		this.style.cursor = "default";
		displayPhoto(currentImage.id);
	}
}

//List of functions to call when the web page loads
function addLoadEvent ( func ) {
    var oldonload = window.onload;
    if ( typeof window.onload != 'function' ) {
        window.onload = func;
    }
    else {
        window.onload = function () {
            oldonload();
            func();
        }
    }
}

addLoadEvent(init);
addLoadEvent(getAlbumList);
