/**
 * @author Phil
 */
window.addEvent('domready', function() { // wait for the content

if ($chk($('select-0'))) {
// One Roar instance for our notofications, positioned in the top-right corner of our demo.
	var log = new Roar({
		container: $('user-profile'),
		position: 'topRight',
		duration: 5000
	});
 
	var link = $('select-0');
	var linkIdle = link.get('html');
 
	function linkUpdate() {
		if (!swf.uploading) return;
		var size = Swiff.Uploader.formatUnit(swf.size, 'b');
		link.set('html', '<span class="small">' + swf.percentLoaded + '% of ' + size + '</span>');
	}
 
	// Uploader instance
	var swf = new Swiff.Uploader({
		path: '/scripts/uploader/source/Swiff.Uploader.swf',
		url: '/scripts/convert/upload-profile-photo.php?id='+link.get('href').replace(/#/,''),
		//url: '/scripts/uploader/server/script.php',
		verbose: true,
		queued: false,
		multiple: false,
		target: link,
		instantStart: true,
		fieldName: 'photoupload',
		typeFilter: {
			'Images (*.jpg, *.jpeg, *.gif, *.png)': '*.jpg; *.jpeg; *.gif; *.png'
		},
		fileSizeMax: 2 * 1024 * 1024,
		onSelectSuccess: function(files) {
			if (Browser.Platform.linux) window.alert('Warning: Due to a misbehaviour of Adobe Flash Player on Linux,\nthe browser will probably freeze during the upload process.\nSince you are prepared now, the upload will start right away ...');
			log.alert('Starting Upload', 'Uploading <em>' + files[0].name + '</em> (' + Swiff.Uploader.formatUnit(files[0].size, 'b') + ')');
			this.setEnabled(false);
		},
		onSelectFail: function(files) {
			log.alert('<em>' + files[0].name + '</em> was not added!', 'Please select an image smaller than 2 Mb. (Error: #' + files[0].validationError + ')');
		},
		appendCookieData: true,
		onQueue: linkUpdate,
		onFileComplete: function(file) {
			var status = JSON.decode(file.response.text, true).status;
			if (status=='0') {
				log.alert('Failed Upload', '<strong>An error occured:</strong> ' + JSON.decode(file.response.text, true).error
);
			} else {
				//var md5 = JSON.decode(file.response.text, true).hash; // secure decode
				var image = JSON.decode(file.response.text, true).image;
				//var width = JSON.decode(file.response.text, true).width; // secure decode
				log.alert('Successful Upload', 'The photo <em>' + this.fileList[0].name + '</em> has been successfully uploaded');
				//log.alert('Successful Upload', file.response.error);
				var container = $('user-photo');
				var myImage = new Asset.image(image, {
					id: 'userProfilePhoto',
					onload: function() {
						var img = container.getElement('img');
						img.destroy();
						this.inject(container, 'top');
					}

				});
				container.highlight();
			}
			file.remove();
			this.setEnabled(true);
		},
		/*onFileComplete: function(file) {
 
			// We *don't* save the uploaded images, we only take the md5 value and create a monsterid ;)
			if (file.response.error) {
				log.alert('Failed Upload', 'Uploading <em>' + this.fileList[0].name + '</em> failed, please try again. (Error: #' + this.fileList[0].response.code + ' ' + this.fileList[0].response.error + ')');
			} else {
				//var md5 = JSON.decode(file.response.text, true).hash; // secure decode
 
				//log.alert('Successful Upload', 'an MD5 hash was created from <em>' + this.fileList[0].name + '</em>: <code>' + md5 + '</code>.<br />gravatar.com generated a fancy and unique monsterid for it, since we did not save the image.');
 
				var img = $('user-photo');
				//img.setStyle('background-image', img.getStyle('background-image').replace(/\w{32}/, md5));
				img.highlight();
			}
 
			file.remove();
			this.setEnabled(true);
		},*/
		onComplete: function() {
			link.set('html', linkIdle);
		},
		onFail: function(error) {
			link.set('href', '/profile?view=upload-photo&id='+link.get('href').replace(/#/,''));
			link.removeEvents();
			link.addEvent('click', function() {
				window.location.href = this.get('href');
			});
			$$('.swiff-uploader-box').destroy();
		}
	});
 
	// Button state
	link.addEvents({
		click: function() {
			return false;
		},
		mouseenter: function() {
			this.addClass('hover');
			swf.reposition();
		},
		mouseleave: function() {
			this.removeClass('hover');
			this.blur();
		},
		mousedown: function() {
			this.focus();
		}
	});
}
	// our uploader instance 
if ($chk($('form-demo'))) {
	var up = new FancyUpload2($('demo-status'), $('demo-list'), { // options object
		// we console.log infos, remove that in production!!
		verbose: true,
		queued: false,
		multiple: false,
		instantStart: true,
		fileSizeMax: 2 * 1024 * 1024,
		
		// url is read from the form, so you just have to change one place
		url: $('form-demo').action,
		fieldName: 'photoupload',
		
		// path to the SWF file
		path: '/scripts/uploader/source/Swiff.Uploader.swf',
		
		// remove that line to select all files, or edit it, add more items
		typeFilter: {
			'Videos (*.jpg, *.jpeg, *.jpe, *.gif, *.png, *.bmp)': '*.jpg; *.jpeg; *.jpe; *.gif; *.png; *.bmp'
		},
		
		// this is our browse button, *target* is overlayed with the Flash movie
		target: 'demo-browse',
		
		// graceful degradation, onLoad is only called if all went well with Flash
		onLoad: function(){
			$('demo-status').removeClass('hide'); // we show the actual UI
			$('demo-fallback').destroy(); // ... and hide the plain form
			// We relay the interactions with the overlayed flash to the link
			$('demo-browse').addEvents({
				click: function(){
					return false;
				},
				mouseenter: function(){
					this.addClass('hover');
				},
				mouseleave: function(){
					this.removeClass('hover');
					this.blur();
				},
				mousedown: function(){
					this.focus();
				}
			});
			
			
		},
		
		// Edit the following lines, it is your custom event handling
		
		/**
		 * Is called when files were not added, "files" is an array of invalid File classes.
		 * 
		 * This example creates a list of error elements directly in the file list, which
		 * hide on click.
		 */ 
		onSelectFail: function(files) {
			files.each(function(file) {
				new Element('li', {
					'class': 'validation-error',
					html: file.validationErrorMessage || file.validationError,
					title: MooTools.lang.get('FancyUpload', 'removeTitle'),
					events: {
						click: function() {
							this.destroy();
						}
					}
				}).inject(this.list, 'top');
			}, this);
		},
		
		/**
		 * This one was directly in FancyUpload2 before, the event makes it
		 * easier for you, to add your own response handling (you probably want
		 * to send something else than JSON or different items).
		 */
		onFileSuccess: function(file, response) {
			var json = new Hash(JSON.decode(response, true) || {});
			
			if (json.get('status') == '1') {
				file.element.addClass('file-success');
				file.info.set('html', '<strong>Image was uploaded successfully</strong>');
				myURI = new URI(window.location);
				myURI.set('query', 'view=edit&id='+json.get('id'));
				myURI.go();
			} else {
				file.element.addClass('file-failed');
				file.info.set('html', '<strong>An error occured:</strong> ' + (json.get('error') ? (json.get('error') + ' #' + json.get('code')) : response));
			}
		},
		
		/**
		 * onFail is called when the Flash movie got bashed by some browser plugin
		 * like Adblock or Flashblock.
		 */
		onFail: function(error) {
			switch (error) {
				case 'hidden': // works after enabling the movie and clicking refresh
					alert('To enable the embedded uploader, unblock it in your browser and refresh (see Adblock).');
					break;
				case 'blocked': // This no *full* fail, it works after the user clicks the button
					alert('To enable the embedded uploader, enable the blocked Flash movie (see Flashblock).');
					break;
				case 'empty': // Oh oh, wrong path
					alert('A required file was not found, please be patient and we fix this.');
					break;
				case 'flash': // no flash 9+ :(
					if ($chk($('demo-noflash'))) {
						$('demo-noflash').setProperty('value', 'true');
					}
					alert('To enable the embedded uploader, install the latest Adobe Flash plugin.')
			}
		}
		
	});
}
});
