// JS for the Entries page

var COLUMN_NUMBER = 10;
var ENTRIES_PAGE_MAX = 50;
var currentPage = 0;
var totalPages = 0;
var currentEntriesList = [];
var currentEntryNumber = 0;
var entrantId;
var lastAction = "none";

// Handler in case we turn off this partner. We don't want to display this page or
// support this contest
// Implement '''handleInactivePartner''' if you want to inform the user of this state.
// Parameter passed in is the pid value in the java script include for photocontest.js
function handleInactivePartner(partnerId) {
	alert("Do your error handling if the partner is not active. Partnerid: " + partnerId);
}

function handleContestReady() {
	var selectedEntryId = getWindowQueryParm("selectedentryid");
	entrantId = getWindowQueryParm("eid");
	if (selectedEntryId != undefined) {
		findEntry(selectedEntryId, ENTRIES_PAGE_MAX);
	} else if (entrantId != undefined) {
		getUserEntries(entrantId, currentPage, ENTRIES_PAGE_MAX);
	} else {
		getAllEntries(currentPage, ENTRIES_PAGE_MAX);
	}
}

function getSpecificPage(page) {
	currentPage = page;
	if (entrantId != undefined) {
		getUserEntries(entrantId, currentPage, ENTRIES_PAGE_MAX);
	} else {
		getAllEntries(currentPage, ENTRIES_PAGE_MAX);
	}
}

function handleFindEntryResponse(result) {
	if (result.status == "ERROR") {
		var errors = result.errors;
		if (errors.USER_NOT_LOGGED_IN != undefined) {
			signin(site + '/enter.html');
		} else {
			handleError(errors);
		}
	} else {
		displayEntries(result, result.data.entryIndex);
	}
}


function handleGetUserEntries(result) {
	handleGetAllEntries(result);
}

function handleGetAllEntries(result) {
	if (result.status == "ERROR") {
		var errors = result.errors;
		if (errors.USER_NOT_LOGGED_IN != undefined) {
			signin(site + '/enter.html');
		} else {
			handleError(errors);
		}
	} else {
		displayEntries(result, 0);
	}
}

function displayEntries(result, selectedIndex) {
	// User info

		var length = 0;

	currentEntriesList = result.data.entries;
	if (currentEntriesList != undefined) {
		length = currentEntriesList.length;
		if (entrantId != undefined) {
			var userHtml = "";
			userHtml += "<div class=\"top_row_item\" ><h1>Photo Contest Entries by ";
			userHtml += currentEntriesList[0].firstName;
			userHtml += "</h1></div>";
			userHtml += "<div class=\"top_row_item\" >";
			userHtml += "<a href=\"http://www.addthis.com/bookmark.php?v=250&pub=winniewong\" onmouseover=\"return addthis_open(this, '', 'http://www.thelandofnodshutterfly.com/entries.html?eid=";
			userHtml += currentEntriesList[0].partnerUserId;
			userHtml += "', 'The Land of Nod Fall Photo Contest')\" onmouseout=\"addthis_close()\" onclick=\"return addthis_sendto()\">";
			userHtml += "<img src=\"http://s7.addthis.com/static/btn/sm-share-en.gif\" width=\"83\" height=\"16\" alt=\"Bookmark and Share\" style=\"border:0; position: relative; bottom: 0px; margin-left: 5px;\" />";
			userHtml += "</a><scr"+"ipt type=\"text/javascript\" src=\"http://s7.addthis.com/js/250/addthis_widget.js?pub=winniewong\"></scr"+"ipt>";
			userHtml += "</div>";
			userHtml += "<div class=\"top_row_item\" style=\"float: right;\"><a href=\"entries.html\">View Everyone's Entries</a></div>";
			document.getElementById("toprow").innerHTML = userHtml;
		}
	} else {
		currentEntriesList = [];
	}

	// var entriesHtml = "<table border='0'>";
	var entriesHtml = "";
	for (var i = 0; i < length; i++) {
		var entry = currentEntriesList[i];
		if (i % COLUMN_NUMBER == 0) {
		//  entriesHtml += "<tr>";
			entriesHtml += "<div class=\"entries_row\">";
		}
		entriesHtml += "<div class=\"entry_box\"  onMouseOver='highlightMe("+i+")' onMouseOut='unHighlightMe("+i+")'>";
		entriesHtml += "<div class=\"imageholder\" id=\"imagediv"+i+"\" style=\"background-image: url('";
		entriesHtml += entry.thumbUrl;
		entriesHtml += "');\" >";
		entriesHtml += "<a href='javascript:clickEntry(";
		entriesHtml += i;
		entriesHtml += ")' >";
			entriesHtml += "<img class=\"entryimage\" src=\"images/1x1.gif\" height=\"68\" width=\"68\" /></a></div>";
		entriesHtml += "<div class=\"entry_by\" id=\"entry_by_"+i+"\" ><a href=\"entries.html?eid="+entry.partnerUserId+"\"><span>by "+entry.firstName+"</span></a></div></div>";
		if ((i + 1) % COLUMN_NUMBER == 0) {
		//  entriesHtml += "</tr>";
			entriesHtml += "</div>";
		} else {
			entriesHtml += "";
		}
	}
	if (length > 0 && (i - 1) % COLUMN_NUMBER == 0) {
		entriesHtml += "</div>";
	}
	//entriesHtml += "</table>"
	if (length == 0) {
		entriesHtml = "There are no entries for this contest";
	}

	var paginationHtml = "";
	currentPage = result.data.page;
	totalPages = result.data.totalPages;

	// pagination is 0 based so to simplify the math logic below, make total pages 0 based.
	var totalPages0Based = totalPages - 1;

	// pagination stuff
	if (currentPage < 0) {
		currentPage = 0;
	}
	var start = currentPage - 2;
	
	if (currentPage > 0) {
	var prev = currentPage - 1;
	paginationHtml += "<a class='lon_link' href='javascript:getSpecificPage(0)'><<</a>&nbsp;<a class='lon_link' style='margin-left: 5px; margin-right: 10px;' href='javascript:getSpecificPage("+prev+")'><</a>&nbsp;";
	}
	
	if (start < 0) {
		start = 0;
	}

	var end = currentPage + 2;
	if (end > totalPages0Based) {
		end = totalPages0Based;
	}

	if (start > 0) {
		paginationHtml += "<a class='lon_link' href='javascript:getSpecificPage(0)'>1</a>&nbsp;";
		if (start > 1) {
			paginationHtml += "...&nbsp;";
		}
	}

	for (var k = start; k <= end; k++) {
		if (k != start) {
			paginationHtml += "&nbsp;";
		}
		if (k == currentPage) {
			paginationHtml += (k + 1);
		} else {
			paginationHtml += "<a class='lon_link' href='javascript:getSpecificPage(" + k + ")'>" + (k + 1) + "</a>";
		}
	}

	if (totalPages0Based > end) {
		if (totalPages0Based - 1 > end) {
			paginationHtml += "&nbsp;...";
		}
		paginationHtml += "&nbsp;<a class='lon_link' href='javascript:getSpecificPage("+ totalPages0Based + ")'>" + totalPages + "</a>";
	}
	
	if (currentPage < totalPages0Based) {
	var next = currentPage + 1;
	paginationHtml += "&nbsp;<a class='lon_link' href='javascript:getSpecificPage("+next+")'>></a>&nbsp;<a class='lon_link' style='margin-left: 10px; margin-right: 5px;' href='javascript:getSpecificPage("+totalPages0Based+")'>>></a>&nbsp;";
	}

	document.getElementById("pagination").innerHTML = paginationHtml;
	document.getElementById("entries_display_area").innerHTML = entriesHtml;
	switch(lastAction){
		case "prevPage":
			clickEntry(currentEntriesList.length -1);
			break;
		case "nextPage":
			clickEntry(0);
			break;
		default:
			clickEntry(selectedIndex);
			break;
		}
	lastAction = "none";
}

function clickEntry(entryIndex) {
	var html = "";
	var entry_name = "none";
	var vertOffset = 0;
	if (entryIndex == undefined) {
		entryIndex = 0;
	}
	
	if (currentPage == 0 && entryIndex == 0) {
		document.getElementById("previous_entry").innerHTML = "<img src=\"images/1x1.gif\"  style=\"margin: auto; top: 170px; position: relative; width: 17px; height: 20px;\"/>";
		document.getElementById("next_entry").innerHTML = "<a href=\"javascript:showNextEntry()\"><img src=\"images/button-grnarrow-rt-17x20.gif\"  style=\"margin: auto; top: 170px; position: relative;\"/></a>";
	} else {
		if (currentPage == totalPages - 1 && entryIndex == currentEntriesList.length - 1) {
			document.getElementById("previous_entry").innerHTML = "<a href=\"javascript:showPreviousEntry()\"><img src=\"images/button-grnarrow-lft-17x20.gif\"  style=\"margin: auto; top: 170px; position: relative;\"/></a>";
			document.getElementById("next_entry").innerHTML = "<img src=\"images/1x1.gif\"  style=\"margin: auto; top: 170px; position: relative; width: 17px; height: 20px;\"/>";
		} else {
			document.getElementById("previous_entry").innerHTML = "<a href=\"javascript:showPreviousEntry()\"><img src=\"images/button-grnarrow-lft-17x20.gif\"  style=\"margin: auto; top: 170px; position: relative;\"/></a>";
			document.getElementById("next_entry").innerHTML = "<a href=\"javascript:showNextEntry()\"><img src=\"images/button-grnarrow-rt-17x20.gif\"  style=\"margin: auto; top: 170px; position: relative;\"/></a>";
		}
	}
		
	if (entryIndex < currentEntriesList.length) {
		var entry = new ContestEntry(currentEntriesList[entryIndex]);
		var newDimensions = entry.getResizedDims(360,480);
		vertOffset = (360-newDimensions.height)/2;
		html = "<img src='";
		html += entry.fullUrl;
		html += "' width='";
		html += newDimensions.width;
		html += "' height='";
		html += newDimensions.height;
		html += "'/ style=\"position: relative; top: " + vertOffset + "px; \" >";
		if (currentEntryNumber < currentEntriesList.length){
			document.getElementById("imagediv"+currentEntryNumber).style.border = "#e6f3f7 1px solid";
			}
		document.getElementById("imagediv"+entryIndex).style.border = "#cad48b 1px solid";
		currentEntryNumber = entryIndex;
		entry_name = entry.title;
		//alert("Entry #"+currentEntryNumber+" is " + newDimensions.width + "x" + newDimensions.height);
	} else {
		html = "Nothing to display";
	}
	
	document.getElementById("selected_entry").innerHTML = html;
	
	if (entry_name != "none") {
		document.getElementById("selected_name").innerHTML = "<span>"+entry_name+" by "+entry.firstName+"</span>";
	} else {
		document.getElementById("selected_name").innerHTML = "<span></span>";
	}
	
}

// Generic routine to illustrate the error map
function handleError(errors) {
	if (errors.NO_ENTRIES != undefined) {
		document.getElementById("recent_entries_out").innerHTML = "There are no entries in this contest";
	} else if (errors.INVALID_CONTEST_ID != undefined) {
		document.getElementById("recent_entries_out").innerHTML = "Contest id value is not a number";
	} else if (errors.CONTEST_ID_NOT_FOUND != undefined) {
		document.getElementById("recent_entries_out").innerHTML = "Contest id could not be found";
	} else if (errors.CONTEST_NOT_ACTIVE != undefined) {
		document.getElementById("recent_entries_out").innerHTML = "This contest is no longer active";
	} else if (errors.INVALID_PARTNER_ID != undefined) {
		document.getElementById("recent_entries_out").innerHTML = "Partner id value is not a number";
	} else if (errors.PARTNER_ID_NOT_FOUND != undefined) {
		document.getElementById("recent_entries_out").innerHTML = "Partner id could not be found";
	} else {
		for (var i in errors) {
			if (errors.hasOwnProperty(i)) {
				alert("Error: " + errors[i]);
			}
		}
	}
}

// Next Image Handling
function showNextEntry(){
var mynextEntryId = 0;
if (currentEntryNumber < currentEntriesList.length -1){
	mynextEntryId = currentEntryNumber + 1;
	clickEntry(mynextEntryId);
	} else {
	// next page
	lastAction = "nextPage";
	//currentEntryNumber = 0;
	if (currentPage < totalPages - 1){
		var nextPage = currentPage + 1;
		getSpecificPage(nextPage);
	} else {
		getSpecificPage(0);
	}
	}
}           

// Previous Image Handling
function showPreviousEntry(){
var mynextEntryId = 0;
if (currentEntryNumber > 0){
	mynextEntryId = currentEntryNumber - 1;
	clickEntry(mynextEntryId);
	} else {
	// prev page
	lastAction = "prevPage";
	if (currentPage > 0){
		var prevPage = currentPage - 1;
		getSpecificPage(prevPage);
	} else {
		var lastPage = totalPages - 1;
		getSpecificPage(lastPage);
	}
	}

}

// Image Mouseover Behavior
function highlightMe(id){
	document.getElementById("imagediv"+id).style.border = "#8C1114 1px solid";
	document.getElementById("entry_by_"+id).style.display = "block";
}

function unHighlightMe(id){
	if (id == currentEntryNumber){
	document.getElementById("imagediv"+id).style.border = "#cad48b 1px solid";
	}else{
	document.getElementById("imagediv"+id).style.border = "#e6f3f7 1px solid";
	}
	document.getElementById("entry_by_"+id).style.display = "none";
}

var site = window.location.protocol + "//" + window.location.host;
var directory = [];
directory = window.location.pathname.split('/');
if (directory.length > 1){
	 for (var i=0; i < directory.length - 1; i++){
	 site += "/" + directory[i];
	 } 
}  
