/////////////////////////////////
// Main functionality of the browser page, with all the functions for the tags, thumbs, and picture navigation
//
// @ Marcelino Martins
//

// Global variables
var moveLeftTimeout = null;
var photosArray = []; // An array of Photo objects
var tagsHash = []; // The key is the tag name, the value is an array of photoArray indices
var tagsWidthHash = []; // The key is the tag name, the value is the width of the thumbs container
var preloadedThumbsNum = 0;
var preloadedImagesArray= [];
var currentTag = "";
var currentPhoto = null;
var currentPhotoInKeyword = -1; //means 'you can only press the 'next' button
var thumbsMarginRight = 6;
var scrollIncrement = 3;
var thumbsContainerWidth;
var currentLeftInt;

// Can't read the entire XML with a single xmlhttp request, need to break it into smaller requests
// Variable keeps trackc of where we are
var startIndex=1;
var maxResults = 50;

// All calls to this function but last will simply process one chuk of the xml (one xmlhttp request)
// Last call will actually proceed with the construction of the thumbs area and the rest of page
function processPhotosXML()
{
	// We can skip root and go directly to entry
	//var domFeed = xmlloader_xmlhttp.responseXML.getElementsByTagName("feed")[0];
	var domEntryCol = xmlloader_xmlDocument().getElementsByTagName("entry");
	var imageObj;

	var photosNum = domEntryCol.length;

	var photoIndex = 0;

	for(i=0; i<photosNum; i++)
	{
		var photoIndex = startIndex-1+i;

		var domEntry = domEntryCol[i];
		var domGphotoId = xmlloader_getElementsByTagCompat(domEntry, "http://schemas.google.com/photos/2007", "gphoto", "id")[0].firstChild;
		var domMediaGroup = xmlloader_getElementsByTagCompat(domEntry, "http://search.yahoo.com/mrss/", "media", "group")[0];
		var domFilename = xmlloader_getElementsByTagCompat(domMediaGroup, "http://search.yahoo.com/mrss/", "media", "title")[0].firstChild.nodeValue;
		var domKeywordsText = xmlloader_getElementsByTagCompat(domMediaGroup, "http://search.yahoo.com/mrss/", "media", "keywords")[0].firstChild;
		var domCaptionText = xmlloader_getElementsByTagCompat(domMediaGroup, "http://search.yahoo.com/mrss/", "media", "description")[0].firstChild;
		var keywordsArray = [];
		var domThumbnailCol = xmlloader_getElementsByTagCompat(domMediaGroup, "http://search.yahoo.com/mrss/", "media", "thumbnail");
		var domSmallerThumb = domThumbnailCol[0];
		var domContent = xmlloader_getElementsByTagCompat(domMediaGroup, "http://search.yahoo.com/mrss/", "media", "content")[0];
		var thumbWidth = parseInt(domSmallerThumb.getAttributeNode("width").value);
		var thumbHeight = parseInt(domSmallerThumb.getAttributeNode("height").value);
		var photoURL = domContent.getAttributeNode("url").value;
		var thumbURL = domSmallerThumb.getAttributeNode("url").value; // + "?qqq=" + Math.random()*100000;
		var smallPhotoURL = domThumbnailCol[1].getAttributeNode("url").value;

		var picId = "nopicid";
		if (domGphotoId!=null)
		{
			picId = domGphotoId.nodeValue;
		}

		var captionStr = "";
		if (domCaptionText!=null)
		{
			captionStr = domCaptionText.nodeValue;
		}

		if (domKeywordsText!=null)
		{
			var keywordsStr = domKeywordsText.nodeValue;
			keywordsArray = keywordsStr.split(", ");
		}
		else
		{
			alert("This photo doesn't have any tag: " + domFilename);
			continue;
		}

		var photoObj = new Photo(domFilename, picId, keywordsArray, photoURL, smallPhotoURL, thumbURL, thumbWidth, thumbHeight, captionStr);
		photosArray[photoIndex] = photoObj;

		for(j=0; j<keywordsArray.length; j++)
		{
			var tagStr = keywordsArray[j];
			insertPhotoInTags(tagStr, photoIndex);

			var photoPositionInTag = tagsHash[tagStr].length - 1;

			// Show the thumbs for the start tag so that the user doesn't stare at a blan space while everything loads
			// Delay showing the thumbs for the other pics to improve performance
			if (tagStr == currentTag)
			{
				insertThumb(tagStr, photoIndex, photoPositionInTag);
			}
		}
		//insertPhotoInTags("all", photoIndex);
	}

	// Detected whether peocessPhotosXML was called enough times (and startIndex incremented enough time) for 
	// the whole XML to be requested. When startIndex is beyhond the end of the XML the returned XML is still a valid
	// one but withou photo entries (photosNum==0)
	if (photosNum!=0)
	{
		startIndex += maxResults;
		xmlloader_loadXMLDoc("http://picasaweb.google.com/data/feed/api/user/marcelino.martins/albumid/" + picasaWebAlbumID + "?thumbsize=72,576&randomizer=9999&imgmax=800&start-index=" + startIndex + "&max-results=" + maxResults, photosXMLLoaded);
	}
	else
	{
		// HACK: force IE to refresh DIV, otherwise thumbs wll spillover on the right side
		document.getElementById("container_of_containers").style.width="100%";
		// This gives an opportunity for the browser to actually render everything before things start to get programatically clicked on
		setTimeout("afterPhotosXMLParsed()", 10);
	}
}

function processTagsXML()
{
	// We can skip root and go directly to entry
	//var domFeed = xmlloader_xmlhttp.responseXML.getElementsByTagName("feed")[0];
	var domEntryCol = xmlloader_xmlDocument().getElementsByTagName("entry");

	var tagsNum = domEntryCol.length;

	for(i=0; i<tagsNum; i++)
	{
		var titleCol = domEntryCol[i].getElementsByTagName("title"); //there should be only one
		var tagStr = titleCol[0].firstChild.nodeValue;
		tagsHash[tagStr]= new Array();
	}

	renderTags();

    // Associative arrays (hashes) have no element positions (no first element) in JavaScript, so we have to do this trick
    var firstTag = "";
    for (firstTag in tagsHash)
    {
        break;
    }

	// The initialKeyword and the initialPhotoFilename are globalVariables set in the body of the main page
	if (initialKeyword == "" || 
        tagsHash[initialKeyword]==null) //invalid value
		initialKeyword = firstTag;

	showThumbs(initialKeyword); // because no thumbs have been loaded yet this will just--in terms of the container--change the visibility of the container 

	xmlloader_loadXMLDoc("http://picasaweb.google.com/data/feed/api/user/marcelino.martins/albumid/" + picasaWebAlbumID + "?thumbsize=72,576&randomizer=9999&imgmax=800&start-index=1&max-results=" + maxResults, photosXMLLoaded);
}


// Click on initial tag, load initial photo etc, as controlled by the varaibles initialized in the default.asp page
function afterPhotosXMLParsed()
{
	resize_eh();

	// Show initial photo, if needed be
	if (initialKeyword!='top:20' || initialPhotoFilename!='')
	{
		var initialPhotoPosition = photoPositionFromFilename(initialKeyword, initialPhotoFilename);
		showPhoto(tagsHash[initialKeyword][initialPhotoPosition], initialPhotoPosition);
	}
}

function photoPositionFromFilename(keyword, filename)
{
	if (filename=='')
		return 0;

	for(var i=0; i< tagsHash[keyword].length; i++)
	{
		if (photosArray[tagsHash[keyword][i]].getFilename() == filename)
			return i;
	}

	return 0;
}

function constructThumbnailImage(thumbURL, thumbWidth, thumbHeight)
{
	imageObj = new Image();
	imageObj.src = thumbURL;
	imageObj.style.borderStyle="none";
	imageObj.style.marginRight= thumbsMarginRight + "px";
	imageObj.style.borderStyle="none";
	imageObj.style.width= thumbWidth + "px";
	imageObj.style.height= thumbHeight + "px";
	// center vertically
	var marginTop = (72 - thumbHeight)/2;
	imageObj.style.marginTop = marginTop + "px";
	imageObj.style.marginBottom = marginTop + "px";

	return imageObj;
}

function insertPhotoInTags(tagStr, photoIndex)
{
	if (tagsHash[tagStr]==null)
	{
		tagsHash[tagStr]= new Array();
	}
	var photosArray = tagsHash[tagStr];
	photosArray.push(photoIndex);
}

function renderTags()
{
	document.getElementById("keywords_label").innerHTML = "Keywords:";

	var unsortedTags = [];
	for(var tagStr in tagsHash)
	{
		unsortedTags.push(tagStr);
	}
	var sortedTags = unsortedTags.sort();
	for(var i in sortedTags)
	{
		renderTag(sortedTags[i], i==(sortedTags.length-1));
	}
}

function renderTag(tagStr, isLastTag)
{
	htmlTnContainer = document.getElementById("tags_container");
	htmlTagElement = document.createElement("a");
	htmlTagElement.setAttribute("href", "javascript:showThumbs('" + tagStr + "')");
	htmlTagElement.className="taglink";
	htmlTagElement.innerHTML = tagStr.replace(/:/g, " ");
	htmlTagElement.id = "tag_link_" + tagStr;
	htmlTnContainer.appendChild(htmlTagElement);

	if (!isLastTag)
	{
		var htmlSpan = document.createElement("span");
		htmlSpan.style.color = "#6699FF";
		htmlSpan.innerHTML = ", ";
		htmlTnContainer.appendChild(htmlSpan);
	}
	
	// Create an area for the thumbs of this tag
	var htmlContainer = document.createElement("div");
	// htmlContainer.style.whiteSpace="nowrap";
	htmlContainer.style.position="relative";
	htmlContainer.style.left="0px";
	htmlContainer.style.paddingBottom="0px";
	htmlContainer.style.display="none";
	htmlContainer.style.width = "0px"; //better than the default, which is ""
	// htmlContainer.style.border="solid 1px yellow";
	htmlContainer.id = "thumbnails_container_" + tagStr;

	document.getElementById("container_of_containers").appendChild(htmlContainer);

	tagsWidthHash[tagStr] = 0;
}

function inserTagsThumbs(tagStr)
{
	var tagPhotosArray = tagsHash[tagStr];

	for(var photoIndex in tagPhotosArray)
	{
		insertThumb(tagStr, tagPhotosArray[photoIndex], photoIndex);
	}
}

function insertThumb(tagStr, photoIndex, photoTagPos)
{
	var photoObj = photosArray[photoIndex];
	htmlTnContainer = document.getElementById("thumbnails_container_" + tagStr);
	htmlHyper = document.createElement("a");
	htmlHyper.setAttribute("href", "javascript:showPhoto(" + photoIndex + ", " + photoTagPos + ")");
	var imageObj = constructThumbnailImage(photoObj.getThumbURL(), photoObj.getThumbWidth(), photoObj.getThumbHeight());
	htmlHyper.appendChild(imageObj);
	htmlTnContainer.appendChild(htmlHyper);

	// Update the width of the container to account for one more thumb
	tagsWidthHash[tagStr] = tagsWidthHash[tagStr] + photoObj.getThumbWidth() + thumbsMarginRight;
	htmlTnContainer.style.width = tagsWidthHash[tagStr] + "px";

	if (tagStr == currentTag)
	{
		resize_eh();
	}
}

function showThumbs(tagStr)
{
	// Highlight clicked link
	document.getElementById("tag_link_" + tagStr).style.fontWeight="bold";
	document.getElementById("tag_link_" + tagStr).style.fontSize="12pt";

	if (currentTag!="" && tagStr!=currentTag)
	{
		var currentThumbsContainer = document.getElementById("thumbnails_container_" + currentTag);
		currentThumbsContainer.style.display = "none";
		currentThumbsContainer.style.left="0px";
		var currentThumbLink = document.getElementById("tag_link_" + currentTag);
		currentThumbLink.style.fontWeight="normal";
		currentThumbLink.style.fontSize="10pt";
	}

	var newThumbsContainer = document.getElementById("thumbnails_container_" + tagStr);

	if (newThumbsContainer.firstChild==null)
	{
		inserTagsThumbs(tagStr);
	}

	newThumbsContainer.style.display = "block";
	currentTag = tagStr;
	setCurrentPhotoInKeyword(-1); // if arrow to right is pressed, display first pic in tag

	// The browser automatically scrolls the container back all the way to the start 
	document.getElementById("left").style.display = "none";
	currentLeftInt = 0;

	recomputeRightArrowState();            
}

function setCurrentPhotoInKeyword(indexVal)
{
	var lastPhotoInKeyword = tagsHash[currentTag].length -1;
	// Only switch picture if there is really a transition in the conditions
	// Switch ON the 'previous' button
	if (currentPhotoInKeyword<1 && indexVal>=1)
	{
		document.getElementById("previous_button").src="/brazilpictures/images/previous.gif";
		document.getElementById("previous_button").disabled=false;
	}
	// Switch OFF the 'previous' button
	if (currentPhotoInKeyword>=1 && indexVal<1)
	{
		document.getElementById("previous_button").src="/brazilpictures/images/previous_deactivated.gif";
		document.getElementById("previous_button").disabled=true;
	}
	// Switch ON the 'next' button
	if ((currentPhotoInKeyword==lastPhotoInKeyword && indexVal < lastPhotoInKeyword) || indexVal==-1)
	{
		document.getElementById("next_button").src="/brazilpictures/images/next.gif";
		document.getElementById("next_button").disabled=false;
	}
	// Switch OFF the 'next' button
	if (currentPhotoInKeyword<lastPhotoInKeyword && indexVal==lastPhotoInKeyword)
	{
		document.getElementById("next_button").src="/brazilpictures/images/next_deactivated.gif";
		document.getElementById("next_button").disabled=true;
	}

	currentPhotoInKeyword = indexVal;
}

// globalPhotoIndex is the key for photosArray
// localPhotoIndex is the key for one of the the arrays in tagsHash[x]
function showPhoto(globalPhotoIndex, localPhotoIndex)
{
	var photoObj = photosArray[globalPhotoIndex];

	var htmlPhoto = document.getElementById("photo");

	if (htmlPhoto.style.display == "none") //the page didn't open with a default picture
    {
		htmlPhoto.style.display="inline";
        document.getElementById("loading_icon").style.display="none";
    }
	if (showLargePhoto)
		htmlPhoto.src = photoObj.getPhotoURL();
	else
		htmlPhoto.src = photoObj.getSmallPhotoURL();


	currentPhoto = globalPhotoIndex;
	setCurrentPhotoInKeyword(localPhotoIndex);

	if (document.getElementById("photo_leftright_buttons").style.display == "none") //first non-cover photo to be displayed
	{
		document.getElementById("photo_leftright_buttons").style.display="block";
		document.getElementById("photo_links").style.display="block";
		document.getElementById("photo_legend").style.display="block";
	}

	updateLegend(currentPhoto);

}

function switchToSmall()
{
	showLargePhoto = false;
	showPhoto(currentPhoto, currentPhotoInKeyword);
}

function switchToLarge()
{
	showLargePhoto = true;
	showPhoto(currentPhoto, currentPhotoInKeyword);
}

function updateLegend(photoIndex)
{
	var photoObj = photosArray[photoIndex];
	var htmlObject = document.getElementById("legend_keywords");
	var keywordsText = "";
	var keywordsArray = photoObj.getKeywords()

	if (keywordsArray.length==0)
	{
		keywordsText = "Other";
	}
	else
	{
		for (var kwdIndex in keywordsArray)
		{
			keywordsText = keywordsText + keywordsArray[kwdIndex];
			if (kwdIndex < keywordsArray.length-1)
			{
				keywordsText = keywordsText + ", "
			}
		}
	}

	htmlObject.innerHTML = keywordsText;

	htmlObject = document.getElementById("legend_caption");
	var trObject = document.getElementById("caption_tr");
	if (photoObj.getCaption()=="")
	{
		trObject.style.display = "none";
	}
	else
	{
		htmlObject.innerHTML = photoObj.getCaption();
		trObject.style.display = ""; // this is better than setting "table-row" because even though "table-row" is the default in the latest brwosers, it is not supported by older browsers (IE 6)
	}

	htmlObject = document.getElementById("permalink");
	htmlObject.href = browserBaseURL + '?album=' + picasaWebAlbumID + '&keyword=' + currentTag + '&photo=' + photoObj.getFilename();

	htmlObject = document.getElementById("comments");
	htmlObject.href = "http://picasaweb.google.com/marcelino.martins/" + picasaWebAlbumName + "#"+ photoObj.getId();
}

function recomputeRightArrowState()
{
	// The '+' below comes from the fact that currentLeftInt is negative
	// We are simply comparing the real size of the thumbs strip (tagsWidthHash[currentTag])
	// To the size of the displayable area (thumbsContainerWidth) plus the hidden area to the left (-1*currentLeftInt)
	if (tagsWidthHash[currentTag] + currentLeftInt > thumbsContainerWidth)
	{
		document.getElementById("right").style.display = "block";
	}
	else
	{
		document.getElementById("right").style.display = "none";
	}
}


//////////////////   Event Handlers   /////////////////////

function photoLoaded()
{
}

function moveleft()
{
	stopMoving();
	moveLeftTimeout = setInterval("move_eh(scrollIncrement)", 1);
}

function moveright()
{
	stopMoving();
	moveLeftTimeout = setInterval("move_eh(-scrollIncrement)", 1);
}

function move_eh(jump)
{
	var currentThumbsContainer = document.getElementById("thumbnails_container_" + currentTag);
	var currentLeftStr = currentThumbsContainer.style.left
	currentLeftInt = parseInt(currentLeftStr.substr(0, currentLeftStr.indexOf("p"))); //remove 'px' suffix
	var newLeft;

	// Three possible scenarios:
	//  - The new left is so wide (a big negative number), that the last photo on the right is already visible. We 
	//    should not move the thumbs any more to the left (stop moving left).
	//  - We are scrolling the photos so much to the right that the first photo on the left is already 
	//    visible. We should not move the thumbs any more to the right (stop miving right).
	//  - The new left is still in the usable area.
	if ((tagsWidthHash[currentTag] + currentLeftInt <= thumbsContainerWidth) && jump < 0)
	{
		newLeft = currentLeftInt;
	}
	else 
	{
		if (currentLeftInt + jump > 0)
		{
			newLeft = 0;
		}
		else
		{
			newLeft = currentLeftInt + jump;
		}
	}

	currentThumbsContainer.style.left = newLeft + "px";

	if (currentLeftInt==0 && newLeft < 0)
	{
		document.getElementById("left").style.display = "block";
	}
	if (currentLeftInt<0 && newLeft == 0)
	{
		document.getElementById("left").style.display = "none";
	}
	recomputeRightArrowState();
}

function stopMoving()
{
	if (moveLeftTimeout!=null)
		clearInterval(moveLeftTimeout);
}

function resize_eh()
{
	thumbsContainerWidth = document.getElementById("container_of_containers").offsetWidth;
	recomputeRightArrowState();
}

function nextPhoto()
{
	setCurrentPhotoInKeyword(currentPhotoInKeyword + 1);
	
	showPhoto(tagsHash[currentTag][currentPhotoInKeyword], currentPhotoInKeyword);
}

function previousPhoto()
{
	setCurrentPhotoInKeyword(currentPhotoInKeyword - 1);
	
	showPhoto(tagsHash[currentTag][currentPhotoInKeyword], currentPhotoInKeyword);
}

function photosXMLLoaded()
{
	if (!xmlloader_checkValidtyOfHTTPRequest())
		return;

	// document.getElementById("loading_messages").style.display = "none";

	// The timeout lets the above HTML be rendered.
	setTimeout("processPhotosXML()", 10)
}

function tagsXMLLoaded()
{
	if (!xmlloader_checkValidtyOfHTTPRequest())
		return;

	document.getElementById("loading_messages").style.display = "none";

	// The timeout lets the above HTML be rendered.
	setTimeout("processTagsXML()", 10)
}

function start()
{
	var tagsContainer = document.getElementById("tags_container");

	xmlloader_loadXMLDoc("http://picasaweb.google.com/data/feed/api/user/marcelino.martins/albumid/" + picasaWebAlbumID + "?kind=tag&randomizer=9999", tagsXMLLoaded);

	// Caching
	var image = new Image();
	image.src = "/brazilpictures/images/next_deactivated.gif";
	var image = new Image();
	image.src = "/brazilpictures/images/previous_deactivated.gif";
}

function starttest()
{
}

