var workingInstance = 0;
var activeInstance;
var cachedPhotos = Array();
var instanceLoc = Array();
var cacheOnly = false;

document.onkeyup = KeyCheck;
function KeyCheck(e) {
	var KeyID = (window.event) ? event.keyCode : e.keyCode;
	switch(KeyID) {
	case 37:
		FetchImage('back',activeInstance,false);
		break;
	case 39:
		FetchImage('next',activeInstance,false);
		break;
	}
}

function DeletePhoto(instanceID) {
	var thisid = instanceLoc[instanceID];
	if (confirm('Are you sure you want to delete this photo?')) window.location = 'DeletePhoto.php?id=' + thisid;
	return false;
}

function FetchImage(direction, instanceID, prefetch) {
	thisid = instanceLoc[instanceID];
	if (direction == 'next') id = cachedPhotos[thisid]['next'];
	if (direction == 'back') id = cachedPhotos[thisid]['prev'];
	if (id == "" || id == 0) return false;
	workingInstance = instanceID;
	activateInstance = instanceID;
	if (prefetch === true) cacheOnly = true;
	else cacheOnly = false;
	if (isset("cachedPhotos['" + id + "']") === true && prefetch === false) {
		AssignPhoto(id);
		FetchImage('next',workingInstance,true);
		return false;
	} else {
		if (prefetch === false) show('photo[' + instanceID  + ']-loading');
		var data = 'photoid=' + id;
		new AJAXRequest('POST','ajax_getphoto.php',data,processPhotoReply);
		return false;
	}
}

function FetchImageByID(id) {
	workingInstance = activeInstance;
	if (isset("cachedPhotos['" + id + "']") === true) {
		AssignPhoto(id);
		FetchImage('next',activeInstance,true);
		return false;
	} else {
		show('photo[' + activeInstance  + ']-loading');
		var data = 'photoid=' + id;
		new AJAXRequest('POST','ajax_getphoto.php',data,processPhotoReply);
		return false;
	}
}

function processPhotoReply(myAJAX) {
	var msg;
	if (myAJAX.readyState == 4) {
		if (myAJAX.status == 200) {
			var response = myAJAX.responseText;
			if (myAJAX.responseText.length > 0) {
				msg = myAJAX.responseText.split("\n");
				id = msg[1];
				if (msg[0] != 'PhotoData') { alert('Invalid photo!'); return false; }
				cachedPhotos[id] = Array();
				cachedPhotos[id]['id'] = id;
				cachedPhotos[id]['src'] = msg[2];
				cachedPhotos[id]['num'] = msg[3];
				cachedPhotos[id]['total'] = msg[4];
				cachedPhotos[id]['fullname'] = msg[5];
				cachedPhotos[id]['next'] = msg[6];
				cachedPhotos[id]['prev'] = msg[7];
				cachedPhotos[id]['description'] = msg[8];
				cachedPhotos[id]['formatteddate'] = msg[9];
				cachedPhotos[id]['allowDel'] = msg[10];
				if (msg[11] == 'CommentData' && globalComments === true) {
					cachedPhotos[id]['iscomments'] = true;
					var comments = myAJAX.responseText.split("CommentData");
					cachedPhotos[id]['comments'] = comments[1];
				}
				if (msg[11] == 'NoCommentData' && globalComments === true) {
					cachedPhotos[id]['iscomments'] = false;
					cachedPhotos[id]['comments'] = '';
				}
				if (cacheOnly === false) {
					AssignPhoto(id);
					FetchImage('next',workingInstance,true);
				}
				else PrefetchPhoto(id);
			} else {
				alert('An invalid response was received from the server. Try again later.');
			}
		} else {
			if (myAJAX.status != '0') alert('An error occured. Try again later. HTTP Error code: ' + myAJAX.status);
		}
	}
}

function PrefetchPhoto(id) {
	new AJAXRequest('GET','/images/photos/' + cachedPhotos[id]['src'],'',false);
}

function escapeForJquery(s) {
	s=s.replace('[','\\[').replace(']','\\]').replace('-','\\-');
	return s;
}

function AssignPhoto(id) {
	var prefix = "photo[" + workingInstance + "]-";
	var photo = cachedPhotos[id];
	instanceLoc[workingInstance] = photo['id'];
	$("#"+escapeForJquery(prefix)+'setascover a').attr('href','SetAsEventCover.php?id='+photo['id']);
	document.getElementById(prefix + 'numbering').innerHTML = 'Photo '+photo['num']+' of '+photo['total'];
	document.getElementById(prefix + 'photo').src = '/images/photos/' + photo['src'];
	document.getElementById(prefix + 'description').innerHTML = photo['description'];
	document.getElementById(prefix + 'author').innerHTML = 'Added by ' + photo['fullname'] + ' on ' + photo['formatteddate'];
	if (photo['allowDel'] == 'yes') { show(prefix+'setascover'); show(prefix + 'delete'); }
	else { hide(prefix+'setascover'); hide(prefix + 'delete'); }
	if (photo['next'] == '') PhotosControl('next',0,workingInstance);
		else PhotosControl('next',1,workingInstance);
	if (photo['prev'] == '') PhotosControl('back',0,workingInstance);
		else PhotosControl('back',1,workingInstance);
	if (photo['prev'] == '' || photo['next'] == '') PhotosControl('line',0,workingInstance);
	if (photo['prev'] != '' && photo['next'] != '') PhotosControl('line',1,workingInstance);
	if (globalComments === true) {
		if (photo['iscomments'] === true) {
			document.getElementById(prefix + 'commentsbox').innerHTML = photo['comments'];
			show(prefix + 'commentsbox'); hide(prefix + 'nocomments');
		} else {
			hide(prefix + 'commentsbox'); show(prefix + 'nocomments');
		}
	}
	cleardesignAdapter();
	window.location.hash = 'photo-'+id;
}

function checkHash() {
	var state = window.location.hash.split('-');
	if (state[1] > "") {
		if (state[1] != instanceLoc[activeInstance]) FetchImageByID(state[1]);
	} else {
		window.location.hash = 'photo-'+instanceLoc[activeInstance];
	}
}

addEvent(window,'load',checkHash,false);
addEvent(window,'load',function() { setInterval(checkHash, 500); },false);

function PhotosControl(direction, status, instance) {
	if (status == 0) {
		document.getElementById('photo[' + instance + ']-' + direction).style.visibility = 'hidden';
	} else {
		document.getElementById('photo[' + instance + ']-' + direction).style.visibility = 'visible';
	}
}

function SubmitComment() {
	var msg = document.getElementById('replymsg').value;
	var photoID = instanceLoc[activeInstance];
	data = 'photoid=' + photoID + '&msg=' + encode(msg);
	hide('fillform');
	show('submittingComment');
	workingInstance = activeInstance;
	new AJAXRequest('POST','ajax_submitcomment.php',data,processCommentAdd);
}

function processCommentAdd(myAJAX) {
	var msg;
	if (myAJAX.readyState == 4) {
		if (myAJAX.status == 200) {
			var response = myAJAX.responseText;
			if (myAJAX.responseText.length > 0) {
				msg = myAJAX.responseText.split("\n");
				if (msg[0] == 'fail') {
					alert(msg[1]);
				} else {
					document.getElementById('replymsg').value = '';
					var id = instanceLoc[activeInstance];
					cachedPhotos[id]['iscomments'] = true;
					cachedPhotos[id]['comments'] = cachedPhotos[id]['comments'] + myAJAX.responseText;
					AssignPhoto(id);
				}
			} else {
				alert('An invalid response was received from the server. Try again later.');
			}
		} else {
			if (myAJAX.status != '0') alert('An error occured. Try again later. HTTP Error code: ' + myAJAX.status);
		}
		hide('submittingComment');
		show('fillform');
	}
}

