/**************************
THUMB DISPLAY VARIABLES
***************************/
var MY_PIX = "mypix";
var THUMB_VIEW = "thumbview";
var ACCEPTED = "accepted";
var PENDING = "pending";

var perPage = 20;
var currentPage = 0;
var startIndex = 0;
var perPageArr = [20, 40, 80];

var pendingTotalCount = 0;
var acceptedTotalCount = 0;
var mypixTotalCount = 0;
var thumbviewTotalCount = 0;

var _refreshContents = null;
var _getPhotos = null;
var _showThumbVidOverlay = null;
var _getTotal = null;
var _thumbMunger = function (thumb, pic, img) {
	img.onclick = function(){ launchMugShotPopup(pic.ID); };
};
var _acceptDivMunger = null;
var _rightDivMunger = null;
var _middleDivNamer = function () {return "thumbCaptionMiddle";};

var context;
var updateTimer = 100000;
var thumbDelay = 250;

var locked = false;
var changeCursorArray = new Array();

var selectionArray = new Array();
var cutArray = new Array();
var lastSelectionIndex = 0;

function setRefreshContentsMethod(f) {
    _refreshContents = f;
}

function setThumbMunger(f) {
    _thumbMunger = f;
}

function setAcceptDivMunger(f) {
    _acceptDivMunger = f;
}

function setRightDivMunger(f) {
    _rightDivMunger = f;
}

function setGetPhotosMethod(f) {
    _getPhotos = f;
}

function setShowThumbVidOverlayMethod(f) {
	_showThumbVidOverlay = f;
}

function setGetTotalMethod(f) {
    _getTotal = f;
}

function setMiddleDivNamer(f) {
    _middleDivNamer = f;
}

function getMiddleDivName() {
    return _middleDivNamer();
}

function checkBounds(current, numPages){
	// check that we aren't out of bounds, changing length
	if(current + 1 > numPages && numPages > 0){
		current = numPages - 1;
	}
	return current;
}

function createPrefOnClick(val){
	return function(){
		updateperPage(val);
		initPrefs();
		scroll(0,0);
	};
}

function setID(id, cellblock, position, evtobj){
    checkSelection(id, evtobj);

    if (context == ACCEPTED) {
   	var copy = getElement("copy");
   	var cut = getElement("cut");
   	var paste = getElement("paste");
   	var del = getElement("del");
   	var vis = getElement("visible");
   	var notVis = getElement("notVisible");
   	var right = getElement("rotRight");
   	var left = getElement("rotLeft");
   	if( id && id != -1){
   		copy.style.display="block";
   		cut.style.display="block";
   		paste.style.display="block";
   		del.style.display="block";
   		vis.style.display="block";
   		notVis.style.display="block";
   		right.style.display="block";
   		left.style.display="block";
   		copy.onclick = function(){copyThumb(selectionArray); return false;};
   		cut.onclick = function(){cutThumb(selectionArray); return false;};
   		paste.onclick = function(){pasteThumb(cellblock, position); return false;};
   		del.onclick = createRightClickDeleteHandler(selectionArray);
   		vis.onclick = createRightClickSetVisibleHandler(selectionArray, true);
   		notVis.onclick = createRightClickSetVisibleHandler(selectionArray, false);
   		right.onclick = function(){rotateRight(selectionArray); return false;};
   		left.onclick = function(){rotateLeft(selectionArray); return false;};
	}else if (id && id == -1){
   		copy.style.display="none";
   		cut.style.display="none";
   		paste.style.display="block";
   		del.style.display="none";
   		vis.style.display="none";
   		notVis.style.display="none";
   		right.style.display="none";
   		left.style.display="none";
   		copy.onclick = function(){};
   		cut.onclick = function(){};	
   		paste.onclick = function(){pasteThumb(cellblock, position); return false;};
   		del.onclick = function(){};	
   		vis.onclick = function(){};
   		notVis.onclick = function(){};	
   		right.onclick = function(){};
   		left.onclick = function(){};
   	}else{
   		copy.style.display="none";
   		cut.style.display="none";
   		paste.style.display="none";
   		del.style.display="none";
   		vis.style.display="none";
   		notVis.style.display="none";
   		right.style.display="none";
   		left.style.display="none";
   		copy.onclick = function(){};
   		cut.onclick = function(){};	
   		paste.onclick = function(){};	
   		del.onclick = function(){};	
   		vis.onclick = function(){};
   		notVis.onclick = function(){};	
   		right.onclick = function(){};
   		left.onclick = function(){};
   	}
    } else {
   	var aprv = getElement("aprv");
   	var del = getElement("del");
   	if( id ){
   		aprv.style.display="block";
		del.style.display="block";
   		aprv.onclick = function(){approveMultiple(selectionArray); return false;};
   		del.onclick = createRightClickDeleteHandler(selectionArray);
   	}else{
   		aprv.style.display="none";
   		del.style.display="none";
   		aprv.onclick = function(){};	
   		del.onclick = function(){};	
   	}
    }
}

function checkSelection(id, evtobj) {
	if (locked == true) {
		return;
	}
    if (inSelection(id)) {
        return;
    }
    clearAllSelections();
    setSelection(id);
}

function copyThumb(selectionArray) {
if(selectionArray.length > 0) {
	var action = copyPasteController.copyMultiple;
    var args = [selectionArray];
    doDwrActionWithLocking(action, args);
	} else {
		alert('No selection to copy');
	}
}	



function cutThumb(selectionArray) {
	if(selectionArray.length > 0) {
		clearAllCuts();
		for(var i=0 ; i<selectionArray.length ; i++){
			setCut(selectionArray[i]);
		}
		var action = copyPasteController.cutMultiple;
        var args = [selectionArray];
        doDwrActionWithLocking(action, args);
	} else {
		alert('No selection to cut');
	}
}

function pasteThumb(cellblock, position){
    var action = copyPasteController.pasteMultiple;
    var args = [cellblock, position];
    var cb = function(data) {
			clearAllSelections(); 
			clearAllCuts();
            refreshContents();
			refreshThumbs();
			};
    doDwrActionWithLocking(action, args, cb);
}

function doDwrActionWithLocking(action, args, callback) {
    lockUp();
    var dwrParams = {};
    dwrParams.callback = function() {
        if (callback != null) {
            callback();
        }
        unLock();
    }
    dwrParams.errorHandler = function(errorString, exception) {
        alert("There was an error handling your request.");
        unLock();
    }

    if (args.length == 1) {
        action(args[0], dwrParams);
    } else if (args.length == 2) {
        action(args[0], args[1], dwrParams);
    } else if (args.length == 3) {
        action(args[0], args[1], args[2],dwrParams);
    } 
}

function deleteHandler(selectionArray){

	if(selectionArray.length == 0) {
		alert('No selection to delete');
		return;
	}
	var numPhotos = selectionArray.length;
	var confirmMsg = "";
	if(numPhotos==1) {
		confirmMsg = "Are you sure you want to delete this photo?"
	}
	else {
		confirmMsg = "Are you sure you want to delete these " + selectionArray.length + " photos?"
	}
	var con = confirm(confirmMsg);
	if(con){	
		var action = cellBlockController.deleteMultipleMugShots;
        var args = [selectionArray];
        var cb = function(data){
					clearAllSelections();	
					refreshContents();
					refreshThumbs();
                };
        doDwrActionWithLocking(action, args, cb);
    }
}

function visibleHandler(selectionArray, visibility){

	if(selectionArray.length == 0) {
		alert('No selection to make (un)viewable');
		return;
	}

	var action = cellBlockController.setMultipleVisible;
    var args = [selectionArray, visibility];
    var cb = function(data){
				setSelected(selectionArray, visibility);
				clearAllSelections();								
			};
    doDwrActionWithLocking(action, args, cb);
}

function rotateRight(selectionArray){
	if(selectionArray.length > 0) {
        var action = cellBlockController.rotateMultipleMugShotsRight;
        var args = [selectionArray];
		var cb = function(data){
				clearAllSelections();	
				refreshContents();
				refreshThumbs();
            };
        doDwrActionWithLocking(action, args, cb);
	} else {
		alert('No selection to rotate');
	}
}

function approveMultiple(selectionArray){
	if(selectionArray.length > 0) {
        var action = cellBlockController.approveMultipleSubmittedMugShot;
        var args = [selectionArray];
        var cb = function(data){
				clearAllSelections();	
				refreshContents();
				refreshThumbs();
			};
        doDwrActionWithLocking(action, args, cb);
	} else {
		alert('No selection to approve.');
	}
}


function rotateLeft(selectionArray){
	if(selectionArray.length > 0) {
		var action = cellBlockController.rotateMultipleMugShotsLeft;
        var args = [selectionArray];
        var cb = function(data){
				clearAllSelections();	
				refreshContents();
				refreshThumbs();
			}
		doDwrActionWithLocking(action, args, cb);
	} else {
		alert('No selection to rotate');
	}
}

function setSelected(selectionArray, visibility){
	var xbox;
	for(var i=0 ; i<selectionArray.length ; i++){
		xbox = getElement("xb" + selectionArray[i]);
		xbox.checked = visibility;
	}
}

function lockUp(){
	locked = true;	
	document.oncontextmenu = function(){ return false; }
	document.body.style.cursor = "wait";
	
	for(var i=0; i<changeCursorArray.length; i++){
		changeCursorArray[i].style.cursor = "wait";
	}
	
	var inputs = document.getElementsByTagName("input");
	for(var i=0; i<inputs.length; i++){
		if(inputs[i].getAttribute("type")=="checkbox"){
			inputs[i].disabled = true;
		}
	}
}

function unLock(){
	locked = false;
	document.body.style.cursor = "default";

	for(var i=0; i<changeCursorArray.length; i++){
		changeCursorArray[i].style.cursor = "pointer";
	}
	
	var inputs = document.getElementsByTagName("input");
	for(var i=0; i<inputs.length; i++){
		if(inputs[i].getAttribute("type")=="checkbox"){
			inputs[i].disabled = false;
		}
	}
}

function getEventObj(evt) {
    return (window.event ? event : evt);
}

function getEventTarget(evt) {
    return (window.event ? event.srcElement : evt.target);
} 

function mungeThumbImage(thumb, pic, img, index) {
    if (_thumbMunger == null) {
        return;
    }
    _thumbMunger(thumb, pic, img, index);
}

function mungeAcceptDiv(accept, pic) {
    if (_acceptDivMunger == null) {
        return;
    }
    _acceptDivMunger(accept, pic);
}

function mungeRightDiv(right, pic) {
    if (_rightDivMunger == null) {
        return;
    }
    _rightDivMunger(right, pic);
}

function createThumb(pic, index){
	var thumb = photoDiv(pic.ID);
	var thumbFrameDiv = _div(null, "thumbFrameDiv");
	var thumbWrap0 = _div(null, "thumbWrap0");
	var thumbWrap1 = _div(null, "thumbWrap1");
	var img = getThumbImage(pic.ID, pic.MOD);

    mungeThumbImage(thumb, pic, img, index);
	createThumbHover(img, pic.USER, pic.CAPTION);
	img.className = "thumbView";
	img.setAttribute("mugid",pic.ID);

	var cap = _div(null, "thumbCaption");
	var left = _div(null, "thumbCaptionLeft");
	cap.appendChild(left);
	var middle = _div(null, getMiddleDivName());

	cap.appendChild(middle);
	var right = _div(null,"thumbCaptionRight");
	cap.appendChild(right);

	thumb.appendChild(thumbFrameDiv);
	thumbFrameDiv.appendChild(thumbWrap0);
	thumbWrap0.appendChild(thumbWrap1);
	thumbWrap1.appendChild(img);
	
	if (pic.IS_VIDEO) {
		showThumbVidOverlay(pic, thumbWrap1, index);
	}
	
	thumb.appendChild(cap);
	var accept = _div("accept");
	left.appendChild(accept);
    mungeAcceptDiv(accept, pic);
	middle.appendChild(textNode(pic.DATE));

	if(pic.FRAME != null){
		var frame = textNode(pic.FRAME);
		middle.appendChild(_br());
		middle.appendChild(frame);	
	}
    
    mungeRightDiv(right, pic);

	changeCursorArray.push(img);	
	
	return thumb;
}

function createThumbHover(div, user, caption){
	var hover = "";
	if(user != null && context != MY_PIX){
		hover += user + ": ";
	}
	if(caption != null){
		hover += caption;	
	}
	if(hover != ""){
		div.onmouseover = function(){ overlib(hover, DELAY, thumbDelay); };	
		div.onmouseout = function(){ nd(); };
	}
}

function findPhoto(photos, photo) {
	for (var i = 0; i < photos.length; i++) {
		var current = photos[i];
		if (current.ID == photo.ID) {
			return i;
		}
	}
	return null;
}

function getNumPages(){
    return Math.ceil(getTotal() / perPage);
}

function getPhotoDiv(idd){
	return photoCache[idd];
}

function createPageChangeCallback(){
	var func = function(a, index) {
		a.onclick = function () {
			currentPage = parseInt(index / perPage);
			refreshContents();
			refreshThumbs();
			selectionArray = [];
			lastSelectionIndex = 0;
			scroll(0,0);
		}
	}
	return func;
}

function launchMugShotPopup(id){
	var url = "popups/mugShot.htm?id="+id;
	var fs = window.open(url,  "thumb", "width=" + 640  + ",height=" + 575  + ",,scrollbars=yes,resizable=yes,toolbar=no,status=no,top=0,left=0");
	fs.focus();
}


function photoDiv(idd){
	var div = _div(null, "thumbImgCont");
	photoCache[idd] = div;
	return div;
}

function initTabs(){
	var tab = getPending();
	killChildren(tab);
	
	if( context == MY_PIX){
		var txt = textNode("MY PIX (" + getTotal() + ")");
		tab.appendChild(txt);
		tab.id = "tabPendingBold";
		return;
	}
	
	if( context == THUMB_VIEW){
		var txt = textNode("Total (" + getTotal() + ")");
		tab.appendChild(txt);
		tab.id = "tabPendingBold";
		return;
	}
	
	// If not returned yet, needs an onclick
	tab.onclick = function(){changeContext(PENDING);};
	
	var txt = textNode("Pending (" + pendingTotalCount + ")");
	if( context == PENDING){
		tab.id = "tabPendingBold";
	}
	else{
		tab.id = "tabPending";
	}
	tab.appendChild(txt);
	
	tab = getAccepted();
	tab.onclick = function(){changeContext(ACCEPTED);};
	killChildren(tab);
	txt = textNode("Accepted (" + acceptedTotalCount + ")");
	if( context == ACCEPTED){
		tab.id = "tabAcceptedBold";
	}
	else{
		tab.id = "tabAccepted";
	}
	tab.appendChild(txt);
	
}

function initPrefs() {
	var prefs = getElement("prefs");
	killChildren(prefs);
	prefs.appendChild(textNode("Per page: "));
	
	for( x in perPageArr ){
		var val;
		if(perPageArr[x] == perPage){
			val = _div("prefOptionBold");	
		}
		else{
			val = _div("prefOption");	
		}
		val.appendChild(textNode(perPageArr[x]));
		val.onclick = createPrefOnClick(perPageArr[x]);

		prefs.appendChild(val);
	}
}

function initTopPages() {
	var total = getTotal();
	var numPages = getNumPages();
	
	currentPage = checkBounds(currentPage, numPages);
	var topPages = getElement("topPages");
	killChildren(topPages);
	
	var callback = createPageChangeCallback();

	createPrevious(topPages, currentPage, numPages, perPage, callback);
	createPageNumbers(topPages, currentPage, numPages, perPage, callback);
	createNext(topPages, currentPage, total, numPages, perPage, callback);
}

function initScreen() {
	var portal = getElement("portal");
	killChildren(portal);

    var pagePhotos = getPhotos();
    var changeCursorArray = new Array();	
	var photoCache = {};
    if (pagePhotos && pagePhotos.length > 0){
    		for(var i = 0; i < pagePhotos.length; i++){
                var pic = pagePhotos[i];
                var photo = createThumb(pic, i);
                portal.appendChild(photo);
                iehackery(pic, context);
   		}
   } 
   else {
       portal.appendChild(textNode("This folder is empty."));
	   	if (context == ACCEPTED){
			portal.oncontextmenu = showmenuie5;
			portal.setAttribute("MUGID", -1);
			portal.setAttribute("CELLBLOCKID", cellBlockId);
			portal.setAttribute("POSITION", 0);
   		} 
   		else {
			portal.oncontextmenu = null;	
		}
    }
   
	for (var i = 0; i < selectionArray.length; i++) {
		setHilite(selectionArray[i]);
	}
	for (var i = 0; i < cutArray.length; i++) {
		setCutStyle(cutArray[i]);
	}
   
}


function initBottomPages() {
	var total = getTotal();
	var numPages = getNumPages();

	currentPage = checkBounds(currentPage, numPages);
	
	var bottomPages = getElement("bottomPages");
	killChildren(bottomPages);
	
	// set callback
	var callback = createPageChangeCallback();

	createPrevious(bottomPages, currentPage, total, perPage, callback);
	createPageNumbers(bottomPages, currentPage, numPages, perPage, callback);
	createNext(bottomPages, currentPage, total, numPages, perPage, callback);
}

function updateperPage(newCount){
	perPage = newCount;
	currentPage = 0;
	refreshContents();
	refreshThumbs();
}

function refreshThumbs(){
	initTabs();
	initPrefs();
	initTopPages();
	initScreen();
	initBottomPages();
}



function showThumbPane() {
	refreshContents();
	refreshThumbs();
}

function refreshContents(){
    if (_refreshContents == null) {
        alert("Page not initialized");
    } else {
        _refreshContents();
    }
}

function setHilite(id) {
	var allDivs = document.getElementsByTagName("div"); 
	for (var i = 0; i < allDivs.length; i++) 
	{ 
		if (allDivs[i].getAttribute("mugid") == id) { 
			allDivs[i].className="thumbImgContHilite";
		} 
	}
}

function clearHilite(id) {
	var allDivs = document.getElementsByTagName("div"); 
	for (var i = 0; i < allDivs.length; i++) 
	{ 
		if (allDivs[i].getAttribute("mugid") == id) { 
			allDivs[i].className="thumbImgCont";
		} 
	}
}

function clearAllHilites() {
	var allDivs = document.getElementsByTagName("div"); 
	for (var i = 0; i < allDivs.length; i++) 
	{ 
		if (allDivs[i].className == "thumbImgContHilite") { 
			allDivs[i].className="thumbImgCont";
		} 
	}
}

function setSelection(id) {
	setHilite(id);
	selectionArray.splice(selectionArray.length,0,id);
}

function clearSelection(id) {
	var idxToDel;
	clearHilite(id);
	for (var i = 0; i < selectionArray.length; i++) {
		if ( selectionArray[i] == id ) {
			idxToDel = i;
			break;
		}
	}
	selectionArray.splice(idxToDel,1);
}

function clearAllSelections() {
	selectionArray.length = 0;
	clearAllHilites();
}

function toggleSelection(event, id, index) {
    var shift = event.shiftKey;
    var ctrl  = event.ctrlKey;
    
    if (!ctrl) {
        clearAllSelections();
    }

    if (!shift) {
        if (inSelection(id)) {
            clearSelection(id);
        }
        else {
            setSelection(id);
        }
        lastSelectionIndex = index;
    }
    else {
        selectAll(Math.min(index, lastSelectionIndex), Math.max(index, lastSelectionIndex));
    }
}

function selectAll(min, max) {
    var photos = getPhotos();
    
    for (var i = min; i <= max; ++i) {
        var photo = photos[i];
        if ( ! inSelection(photo.ID) ) {
            setSelection(photo.ID);
        }
    }
}

function inSelection(id) {
	for (var i = 0; i < selectionArray.length; i++) {
		if ( selectionArray[i] == id ) {
			return true;
		}
	}
    return false;
}

function getTotal(){
    if (_getTotal == null) {
        alert("Page not initialized");
    } else {
        return _getTotal();
    }
}

function getPhotos() {
    if (_getPhotos == null) {
        alert("Page not initialized");
    } else {
        return _getPhotos();
    }
}

function showThumbVidOverlay(pic, thumbWrap1, index) {
	if (_showThumbVidOverlay == null) {
		alert("Page not initialized");
	} else {
		return _showThumbVidOverlay(pic, thumbWrap1, index);
	}
}

function createDeleteHandler(id){
	return function() {
		if(locked==true) {
			return;
		}
		if(	!inSelection(id)){
			clearAllSelections();
			setSelection(id);
		}
		deleteHandler(selectionArray);
	}
}

function createRightClickDeleteHandler(selectionArray){
	return function() {
		deleteHandler(selectionArray);
	}
}

function getVisibility(id){
	var checkbox = getElement("xb" + id);
	return checkbox.checked;
}

function createSetVisibleHandler(id){
	return function() {
		if(	!inSelection(id)){
			clearAllSelections();
			setSelection(id);
		}
		visibleHandler(selectionArray, getVisibility(id));
	}
}

function createRightClickSetVisibleHandler(selectionArray, visibility){
	return function() {
		visibleHandler(selectionArray, visibility);
	}
}

function setCutStyle(id) {
	var allImgs = document.getElementById("portal").getElementsByTagName("img"); 
	for (var i = 0; i < allImgs.length; i++) 
	{ 
		if (allImgs[i].getAttribute("mugid") == id) { 
			allImgs[i].className="cutThumbView";
		} 
	}
}

function clearCutStyle(id) {
	var allImgs = document.getElementById("portal").getElementsByTagName("img"); 
	for (var i = 0; i < allImgs.length; i++) 
	{ 
		if (allImgs[i].getAttribute("mugid") == id) { 
			allImgs[i].className="thumbView";
		} 
	}
}

function clearAllCutStyles() {
	var allImgs = document.getElementById("portal").getElementsByTagName("img"); 
	for (var i = 0; i < allImgs.length; i++) 
	{ 
		if (allImgs[i].className == "cutThumbView") { 
			allImgs[i].className="thumbView";
		} 
	}
}

function setCut(id) {
	setCutStyle(id);
	cutArray.splice(cutArray.length,0,id);
}

function clearCut(id) {
	var idxToDel;
	clearCutStyle(id);
	for (var i = 0; i < cutArray.length; i++) {
		if ( cutArray[i] == id ) {
			idxToDel = i;
			break;
		}
	}
	cutArray.splice(idxToDel,1);
}

function clearAllCuts() {
	cutArray.length = 0;
	clearAllCutStyles();
}