/* entry hook for upload second steps - aka constructor */
function uploadComplete(id) {
	if(id == null)
	{
		// handle 2nd step - no id
		step2handler.init();
	}
	else
	{
		if ( $('resource-edit-container-'+id) != null)
		{
			if ($('edit-cancel-' + id) != null)
			{
				$('edit-cancel-' + id).parentNode.setStyle('padding-left: 10px;');
				$('edit-cancel-' + id).setStyle('display:none');
			}

			// reposition the submit button - it needs to be in the center
			$('edit-submit-'+id).setStyle('margin-left: 200px;');

			// create an info box to notify users about the fact that the 'cancel' button is unavailable after a file has beed uploaded
			if ( $('fileSavedInfo-'+id) == null )
			{
				var infoBox = $(document.createElement('p'));
				infoBox.id = 'fileSavedInfo-'+id;
				infoBox.innerHTML = 'Uploading a file is an irreversible change - that is the reason why your changes can no longer be canceled.';

				$('edit-cancel-' + id).parentNode.insertBefore(infoBox, $('edit-submit-'+id) );
			}

			// remove the possibility to close the resource edit form by clicking on it's edit button
			if ($('edit-' + id) != null) // this only applies to list entries
			{
				$('edit-' + id).stopObserving('click');
				$('edit-' + id).observe
				(
					'click',
					function (ClickEvent)
					{
						ClickEvent.stop();
					}
				);
			}

			// remove "locked" info if present - uploading a new version unlocks a resource
			// this only applies the the viewResource template
			if ( $('unlock-option') != null)
			{
				$('unlock-option').remove();

				// add the "lock versions" option to the administrative menu
				$('admin-container-'+id).setStyle('display: block;');
				var li = $(document.createElement('li'));
				li.id = 'lock-option';

				var a  = $(document.createElement('a'));
				a.id = "singleLock-"+id;
				a.addClassName('single-lock');
				a.href = path + "/resources/addLock:" + id;
				a.innerHTML = '[lock versions]';

				var img = $(document.createElement('img'));
				img.alt = 'lock versions';
				img.src = path + '/theme/basic/images/icons/famfamfam/silk/lock_go.png?'+id;

				li.appendChild(img);
				li.appendChild(a);

				$('admin-option-list').appendChild(li);
				SingleAdminActions.init();

				$('admin-container-'+id).setStyle('display: none;');
			}

			// activate the input text area for versions descriptions (only if available)
			if ( $('meta-entryVerDescription-'+id) != null)
			{
				$('meta-entryVerDescription-'+id).disabled = false;
				$('meta-entryVerDescription-'+id).removeClassName('locked');
			}
		}
	}
}

/* handler object for flash file uploads */
var step2handler = {
	overlay: null,
	response: { 'xml': null, 'total': 0, 'current': 0},
	email: '',

	initUrlHandle: function(count) {
		// no prototype loaded - wait for 5 seconts trying every 0.5 sec - then fail
		if(typeof Prototype != 'object' && count < 10) {
			window.setTimeout(step2handler.initUrlHandle, 500, ++count);
			return;
		}

		if(typeof Prototype == 'object') {
			// for each found tab object remake it for tabs
			Event.observe(window, 'load', function() {
				$$('input.remote-url.submit').each(function(submitButton) {
					submitButton.observe('click',step2handler.handleRemoteUrlsSubmit);
				});

				$$('a.add-another.uC.action').each(function(addAnotherButton) {
					addAnotherButton.observe('click',step2handler.handleAddAnother);
				});

				$$('input.text.url').each(function(urlInput) {
					urlInput.observe('change',step2handler.handleAddUrlsPending);
				});

				$$('input.qU.remote-url.clear').each(function(formClear) {
					formClear.observe('click',function(ev) {
						$('urls-pending-upload').innerHTML = 0;
					});
				});
			});

		} else {
			alert('step2handler requires Prototype 1.6 to be loaded');
		}
	},

	init: function() {
		/* wait for helper functions load if not present (might happen on slow connections) */
		if(typeof SupportFunctions == 'undefined') {
			window.setTimeout(this.init,500);
			return;
		}

		step2handler.createLoadingOverlay();

		// AJAX: get data from uploads...
		new Ajax.Request(sitePaths.httpUrl + '/resourcesAJAX/getNewResources',{
			onFailure: step2handler.handleErrorInTransport,
			onSuccess: function(transport) {
				// get XML as DOM
				step2handler.response.xml = transport.responseXML;
				step2handler.handleNewResourcesResponse();
			}
		});
	},

	sniplets: {
		loading: function() {
			this.container = $(step2handler.overlay.appendChild(document.createElement('div')));
			this.container.addClassName('uC sF loading');         // .sF.loading class

			// set height to parents height
			this.container.setStyle({ 'height': $(this.container.parentNode).getHeight() + 'px' });

			// add remove function
			this.remove = function() { this.container.remove(); }
		},

		heading: function() {
			this.container = $(step2handler.overlay.appendChild(document.createElement("div")));
			this.container.addClassName('uC heading');

			this.h1 = $(this.container.appendChild(document.createElement("h1")))
			this.p = $(this.container.appendChild(document.createElement("p")))
		},

		finalInfo: function(message,cssClass) {
			this.container = $(step2handler.overlay.appendChild(document.createElement("div")));
			this.container.addClassName('uC status '+cssClass);

			var h2 = $(this.container.appendChild(document.createElement("h2")))
				h2.appendChild(document.createTextNode('Save status'));

			var p  = $(this.container.appendChild(document.createElement("p")))
				p.appendChild(document.createTextNode(message));

			var a  = $(this.container.appendChild(document.createElement("a")))

			if(step2handler.response.current < step2handler.response.total) {
				a.addClassName('uC next action medium');
				a.appendChild(document.createTextNode('Next resource »'));
				a.observe('click',function(ev) {
					ev.stop();
					new step2handler.sniplets.loading();

					// handle next resource...
					step2handler.handleNewResourcesResponse();
				});
			} else {
				a.addClassName('uC close action medium');
				a.appendChild(document.createTextNode('Close'));
				a.observe('click',step2handler.handleCloseRequest);
			}

		},

		innerForm: function(resourceNode) {
			/* add container */
			this.container = AdminActions.buildEditForm(resourceNode);
			this.container = $(step2handler.overlay.appendChild(this.container));
			this.container.addClassName('uC');

			/* "class" functions..  */
			this.reSetVariables = function(oldData) {
				// check wether entryAvailability was checked or not
				if(typeof oldData.entryAvailability == 'undefined')
					this.container.down('input[name="entryAvailability"]').checked = false;

				if(typeof oldData.mailAuth != 'undefined')
					this.container.down('input[name="mailAuth"]').value = oldData.mailAuth;
			}

			var entryIdNode	 = step2handler.getResourceAttribute('entryID',resourceNode);
			var entryIdValue = entryIdNode.getElementsByTagName('value')[0].firstChild.nodeValue;

			/* remake original edit  */

			// reference to edited entryID value
			this.container.down('form').entryIdValue = entryIdValue;

			var aCancel	= $(document.getElementById('edit-cancel-'+entryIdValue));
			var aSave	= $(document.getElementById('edit-submit-'+entryIdValue));

			/* replace cancel with our cancel */
			aCancel.stopObserving();
			aCancel.observe('click',step2handler.handleCloseRequest);

			/* replace submit with our submit */
			aSave.stopObserving();
			aSave.observe('click',step2handler.handleSaveRequest);

			/** if anonymous add field for email address */
			if(step2handler.isAnonymous()) {
				//  remove anonymous switch
				$$('label[for="meta-entryAvailability-'+entryIdValue+'"]').each(function(label) { label.remove(); });
				$('meta-entryAvailability-'+entryIdValue).remove();

				// add fieldset for e-mail
				if(step2handler.allowMailAuth()) {
					var fieldset = $(this.container.down('form').insertBefore(document.createElement('fieldset'),this.container.down('fieldset.content')));
						fieldset.addClassName('uC meta email');
						fieldset.innerHTML = '<h3>Please identify yourself</h3><label for="mailAuth">Your email:</label><input type="text" value="'+step2handler.email+'" id="mailAuth" name="mailAuth" class="text rounded "/><p>If your email is verified, your upload will show immediately in repository. Otherwise it will be restricted untill moderated by site administrator.</p>';
				}
			}

			// remove file uploader if present
			var entryTypeNode  = step2handler.getResourceAttribute('entryType',resourceNode);
			var entryTypeValue = entryTypeNode.getElementsByTagName('value')[0].firstChild.nodeValue;

			if(entryTypeValue == 'local') this.container.down('fieldset.content').remove();
		}
	},

	allowMailAuth: function() {
		if(step2handler.response.xml == null)
			return null;

		var anonymous = step2handler.response.xml.getElementsByTagName('allowMailAuth')[0].firstChild.nodeValue;

		if(anonymous == 'true') {
			return true;

		} else {
			return false;
		}
	},

	isAnonymous: function() {
		if(step2handler.response.xml == null)
			return null;

		var anonymous = step2handler.response.xml.getElementsByTagName('anonymous')[0].firstChild.nodeValue;

		if(anonymous == 'true') {
			return true;

		} else {
			return false;
		}
	},

	getResourceAttribute: function(attrName,resourceNode) {
		var attribute = $A(resourceNode.getElementsByTagName(attrName));

		// false when no data...
		if(attribute.size() != 1) return false;

		// return final node
		return attribute[0];
	},

	handleNewResourcesResponse: function() {
		// remove any loding, statuses, old headers etc
		$$('div.uC.sF.loading').each(function (div) { $(div).remove(); });
		$$('div.uC.status').each(function (div) { $(div).remove(); });
		$$('div.uC.heading').each(function (div) { $(div).remove(); });

		// if we have child nodes - hadle it or
		if(step2handler.response.xml != null && step2handler.response.xml.documentElement.hasChildNodes()) {
			var resources = $A(step2handler.response.xml.getElementsByTagName('resource'));
		} else {
			var resources = [];
		}

		// if we have child nodes - hadle it or
		if(resources.size() > 0) {
			// update size info
			if(step2handler.response.total == 0)
				step2handler.response.total = resources.size();

			var heading = new step2handler.sniplets.heading();
				heading.h1.appendChild(document.createTextNode('Add resource:'));
				heading.p.appendChild(document.createTextNode('Your upload has finished - please fill required information • resource '+(step2handler.response.current+1)+' of ' + resources.size()));

			/* inner form container */
			var innerForm = new step2handler.sniplets.innerForm(resources[step2handler.response.current]);

		} else {
			var innerForm = step2handler.overlay.appendChild($( document.createElement("div")));
				innerForm.addClassName("errorInfo");
				innerForm.setStyle({ 'height': $(innerForm.parentNode).getHeight() + 'px' });

			var label = innerForm.appendChild($( document.createElement("h1")));
				label.innerHTML = "An error has occured.";

			var labelSecondary = innerForm.appendChild($( document.createElement("p")));
				labelSecondary.innerHTML = 'There are no resources uploaded.';

			var cancel = $(innerForm.appendChild(document.createElement("div")));
				cancel.addClassName("button");
				cancel.innerHTML = "OK";
				cancel.observe('click',step2handler.handleCloseRequest);

			/* empty div to force IE to expand the innerForm container while accounting for 'cancel' container bottom margin */
			var spacer = innerForm.appendChild($( document.createElement("div")));
		}
	},

	handleErrorInTransport: function(transport) {
		alert('Error Obtaining uploaded rosource details');
		step2handler.handleCloseRequest();
	},

	handleCloseRequest: function(ev) {
		if(ev != null) ev.stop();

		SupportFunctions.closeOverlay();
		step2handler.overlay = null;
		step2handler.email = '';
		step2handler.response = { 'xml': null, 'total': 0, 'current': 0};
	},

	handleSaveRequest: function(ev) {
		// stop form submit...
		ev.stop();

		// get form copy
		var editForm = $(ev.element().form);

		// remove it...
		$(editForm.parentNode).remove();

		// insert waiting aniation...
		var loading = new step2handler.sniplets.loading();

		// save email if more files to come
		if(step2handler.response.total > 1 && step2handler.isAnonymous())
			step2handler.email = editForm.down('input[name="mailAuth"]').getValue();

		// make request
		new Ajax.Request(sitePaths.httpUrl + '/resourcesAJAX/saveResource:' + editForm.entryIdValue, {
			method: 'post',
			parameters: editForm.serialize(),
			onFailure: step2handler.handleErrorInTransport,
			onSuccess: function(transport) {
				var savedResourceXML    = transport.responseXML;
				var savedResourceStatus = savedResourceXML.getElementsByTagName("valid")[0].childNodes[0].nodeValue;

				var previousResourceData = editForm.serialize(true);

				// there were errors... insert new form from new result
				if(savedResourceStatus == '0') {
					// remove loading animation
					loading.remove()

					// insert form with errors
					var innerForm = new step2handler.sniplets.innerForm(savedResourceXML.getElementsByTagName("resource")[0]);
					innerForm.reSetVariables(previousResourceData);
				}

				// resorce saved w/o errors - set anonymous access if required
				if(savedResourceStatus == '1') {
					// increment resource counter
					step2handler.response.current++;

					// send anonymous availability request if needed
					if(step2handler.isAnonymous() == false && typeof previousResourceData.entryAvailability != 'undefined') {
						new Ajax.Request(sitePaths.httpUrl + '/resourcesAJAX/grantAnonymous:' + editForm.entryIdValue + ':true', {
							method: 'get',
							onFailure: step2handler.handleErrorInTransport,
							onSuccess: function(transport) {
								// remove loading...
								loading.remove();

								var error = transport.responseXML.getElementsByTagName("error")[0];

								if(error != null && typeof error != 'undefined') {
									var info = new step2handler.sniplets.finalInfo(error.firstChild.nodeValue,'info');
								} else {
									var info = new step2handler.sniplets.finalInfo('Resource saved successfully. You will need to refresh site to see it in lists.','success');
								}
							}
						});

					} else {
						loading.remove();
						var info = new step2handler.sniplets.finalInfo('Resource saved successfully','success');
					}
				}
			}
		});
	},

	createLoadingOverlay: function() {
		// scroll user to top of the page...
		window.scrollTo(0,0);

		// remove any previous overlays
		if(step2handler.overlay != null) $(step2handler.overlay).remove();

		// display an overlay
		step2handler.overlay = SupportFunctions.showOverlay();
			step2handler.overlay.addClassName('uC');			// mark for uploadComplete styles
			step2handler.overlay.addClassName('container');		// .uC.container class

		// displays loading window...
		var loading = new step2handler.sniplets.loading();
	},

	handleRemoteUrlsSubmit: function(ev) {
		// stop the submit - it'll go by ajax...
		ev.stop();

		// urls submited form
		var urlsSubmitForm = $(ev.element().form);
		var urlsToAdd = '1';

		urlsSubmitForm.select('input.url').each(function(urlInput) {
			if(typeof $(urlInput).getValue().trim == 'function') {
				var url = $(urlInput).getValue().trim();
			} else {
				var url = $(urlInput).getValue();
			}

			// skip empty URLs
			if(url.length == 0) return;

			urlsToAdd += '&urls%5B%5D=' + escape($(urlInput).getValue());
		});

		if(urlsToAdd == '1') {
			alert('No URLs to submit');
			return false;
		}

		step2handler.createLoadingOverlay();

		new Ajax.Request(sitePaths.httpUrl + '/resourcesAJAX/uploadURLs', {
			method: 'post',
			parameters: urlsToAdd,
			onFailure: step2handler.handleErrorInTransport,
			onSuccess: function(transport) { step2handler.handleCloseRequest(); step2handler.init(); }
		});
	},

	handleAddAnother: function(ev) {
		// stop the submit - it'll go by ajax...
		ev.stop();

		// urls submited form
		var urlsFieldset = $(ev.element().up('form').down('fieldset.urls'));
		var num = $$('input.text.url').size();

		// add field...
		var label = $(urlsFieldset.appendChild(document.createElement('label')));
			label.setAttribute('for','url-to-upload' + num);
			label.appendChild(document.createTextNode('Add URL:'));

		// add space between
		urlsFieldset.appendChild(document.createTextNode(' '));

		var urlInput = $(urlsFieldset.appendChild(document.createElement('input')));
			urlInput.id = 'url-to-upload' + num;
			urlInput.type = 'text';
			urlInput.setAttribute('name','urls['+num+']');
			urlInput.addClassName('url text');
			urlInput.observe('change',step2handler.handleAddUrlsPending);

		// add <br />
		urlsFieldset.appendChild(document.createElement('br'));
	},

	handleAddUrlsPending: function(ev) {
		var urlsPendingUpload = $('urls-pending-upload');

		if(urlsPendingUpload != null && typeof urlsPendingUpload != 'undefined') {
			var count = 0;

			$$('input.text.url').each(function(urlInput) {
				if(typeof $(urlInput).getValue().trim == 'function') {
					var url = $(urlInput).getValue().trim();
				} else {
					var url = $(urlInput).getValue();
				}

				if(url.length > 0) count++;
			});

			urlsPendingUpload.innerHTML = count;
		}
	}
}

/* init... */
step2handler.initUrlHandle(0);

