//window.onload = init;
window.addEvent('load', init);

tinyMCE.init({
	theme : "advanced",
	plugins : "advimage,paste,fullscreen,table",
	//language : "de",
	theme_advanced_toolbar_location : "top",
	theme_advanced_buttons2: "cut,copy,pastetext,undo,redo,|,bold,italic,underline,strikethrough,removeformat,formatselect,|,charmap,bullist,numlist,outdent,indent",
	theme_advanced_buttons1: "link,unlink,image,|,tablecontrols,|,code,fullscreen",
	theme_advanced_buttons3: "",
	theme_advanced_blockformats : "p,h1,h2,h3",
	mode : "specific_textareas",
	editor_selector : "memory_system_form_editor",
	external_image_list_url : "../data/system/lib/form/imagelist.php"

});

function init() {
	validate_all();
	gallery(null);
}

window.addEvent('domready', function (){
    $$('.multiselect').each(function(multiselect){
       new MTMultiWidget({'datasrc': multiselect});
   });
       
});


function gallery(obj) {
	//alert(obj.value);
	if($('PluginTemplate')) {
		if($('PluginTemplate').value == "plugins/bildergalerie.tpl") {
			if($('plugin_selector')) {
				$('plugin_selector').setStyle("display", "");
			}
		} else {
			if($('plugin_selector')) {
				$('plugin_selector').setStyle("display", "none");
			}
		}
	}
}

/* FancyUpload Showcase
*
* @license		MIT License
* @author		Harald Kirschner <mail [at] digitarald [dot] de>
* @copyright	Authors
*/

window.addEvent('domready', function() { // wait for the content

	// our uploader instance
	if($('upload-status') != null) {
		var ext = $('upload-ext').value;
		var up = new FancyUpload2($('upload-status'), $('upload-list'), { // options object
			// we console.log infos, remove that in production!!
			//verbose: true,
	
			// url is read from the form, so you just have to change one place
			url: $('upload-script').value,
	
			// path to the SWF file
			path: '../data/system/lib/fancyupload2/Swiff.Uploader.swf',
	
			// remove that line to select all files, or edit it, add more items
			typeFilter: $('upload-ext').value,
	
			// this is our browse button, *target* is overlayed with the Flash movie
			target: 'upload-browse',
	
			// graceful degradation, onLoad is only called if all went well with Flash
			onLoad: function() {
				//$('upload-status').removeClass('hide'); // we show the actual UI
				$('upload-status').setStyle('display', 'block');
				if($('upload-fallback')) $('upload-fallback').destroy(); // ... and hide the plain form
				
				// We relay the interactions with the overlayed flash to the link
				this.target.addEvents({
					click: function() {
						return false;
					},
					mouseenter: function() {
						this.addClass('hover');
					},
					mouseleave: function() {
						this.removeClass('hover');
						this.blur();
					},
					mousedown: function() {
						this.focus();
					}
				});
	
				// Interactions for the 2 other buttons
	
				$('upload-clear').addEvent('click', function() {
					up.remove(); // remove all files
					return false;
				});
	
				$('upload-upload').addEvent('click', function() {
					up.start(); // start upload
					return false;
				});
			},
	
			// 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>Datei wurde hochgeladen.</strong>');
				} else {
					file.element.addClass('file-failed');
					file.info.set('html', '<strong>Es ist ein Fehler aufgetreten:</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) {
				//alert(window.location.pathname.replace("/index.php", "/").replace("/memory", "")+'data/system/lib/fancyupload2/Swiff.Uploader.swf');
				switch (error) {
					case 'hidden': // works after enabling the movie and clicking refresh
						$('upload-status').destroy();
						//alert('Das Upload-Script (Flash) wurde von Ihrem Browser geblockt.');
						break;
					case 'blocked': // This no *full* fail, it works after the user clicks the button
						//alert('Das Upload-Script (Flash) wurde von Ihrem Browser geblockt.');
						break;
					case 'empty': // Oh oh, wrong path
						//alert('Eine benötigte Datei konnte nicht geladen werden.');
						$('upload-status').destroy();
						break;
					case 'flash': // no flash 9+ :(
						$('upload-status').destroy();
						//alert('Um das interaktive Uploadscript benutzen zu können wird der aktuelle Flash-Player benötigt!');
						break;
				}
			},
			
			onComplete: function() {
				
				//window.location.reload();
			}
	
		});
	}
});



/***********************************************************************
 * Validation 
 ***********************************************************************/
var active_save_button = "";
var inactive_save_button = "";

function validate_all() {
	if(document.getElementById("form_submit") != null) {
		if(active_save_button == "") { 
			active_save_button = document.getElementById("form_submit").src;
			var f = active_save_button.split(".");
			for(var i=0; i<f.length-1; i++) {
				if(i>0) {
					inactive_save_button += ".";
				}
				inactive_save_button += f[i];
			}
			inactive_save_button += "_inactive." + f[f.length-1];
		}
		
		var fields = document.getElementsByName("required[]");
		
		var save_button = active_save_button;
		var valid = true;
		
		for(var i=0; i<fields.length;i++) {
			var obj = document.getElementById(fields[i].value);
			var ret = validate(obj);
			if(ret == false) {
				save_button = inactive_save_button;
				valid = false;
			}
		}
		document.getElementById("form_submit").src = save_button;
		return valid;
	} else {
		return false;
	}
}

function validate(obj) {
	//obj.className += " invalid";
	if(obj.value == "") {
		obj.className = "memory_system_form_text invalid";
		return false;
	} else {
		obj.className = "memory_system_form_text";
		return true;
	}
}

function trySubmit() {
	return validate_all();
}




