//window.onload = init;

function empty_cal(obj) {
	obj.value = "";
}

function Werteliste () {
	var querystring = location.search;
	if (querystring == '') return;
	var wertestring = querystring.slice(1);
	var paare = wertestring.split("&");
	var paar, name, wert;
	for (var i = 0; i < paare.length; i++) {
		paar = paare[i].split("=");
		name = paar[0];
		wert = paar[1];
		name = unescape(name).replace("+", " ");
		wert = unescape(wert).replace("+", " ");
		this[name] = wert;
	}
}


window.addEvent('domready', function() {
	if($('apply')) {
		$('apply').addEvent('click', function() {
			var path = location.href.split("?")[0];
			var b = path.replace(/\\/g,'/').replace(  /.*\//, '' );
			var liste = new Werteliste();
			$('editform').set("action", b+"?show=" + liste['show'].split("_")[0] + "_" + liste['show'].split("_")[1] + "_" + liste['show'].split("_")[2] + "_detail&action=saveedit&data=" + liste['data']);
			$('editform').submit();
			//alert("yay");
		});
	}
});

tinyMCE.init({
	theme : "advanced",
	plugins : "advimage,paste,fullscreen,table,inlinepopups,contextmenu,style,layer,searchreplace,preview",
	language : "de",
	theme_advanced_toolbar_location : "top",
	theme_advanced_toolbar_align : "left",
	theme_advanced_statusbar_location : "bottom",
	theme_advanced_resizing : false,
	theme_advanced_buttons1: "cut,copy,paste,pastetext,pasteword,|,undo,redo,|,search,replace,|,preview,code,fullscreen",
	theme_advanced_buttons2: "bold,italic,underline,strikethrough,removeformat,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,outdent,indent,blockquote,|,sub,sup,|,formatselect",
	theme_advanced_buttons3: "link,unlink,image,|,tablecontrols,|,charmap,hr,insertlayer,moveforeward,movebackward,absolute,styleprops",
	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",
	//content_css: "frontend/index.css",
	extended_valid_elements : "iframe[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name|style]",
	skin : "o2k7",
	skin_variant : "silver"
});

function init() {
	validate_all();
}

window.addEvent('domready', function (){
	init();
	
	$$('.multiselect').each(function(multiselect){
    	new MTMultiWidget({'datasrc': multiselect});
	});
	
	$$('img.bewertung').each(function(obj){
    	obj.GFX = "data/system/lib/form/images/ico_stars_::i::_of_3.png";
    	obj.VALUE = obj.get("src").match(/data\/system\/lib\/form\/images\/ico_stars_(.*)_of_3.png/)[1];
    	obj.setStyle("cursor", "pointer");
    	obj.addEvents({
    		"mouseenter": function(event) {
    			obj.onGfx = 1;
    		},

    		"mouseleave": function(event) {
    			obj.onGfx = 0;
    			obj.set("src", obj.GFX.replace("::i::", obj.VALUE));
    		},

    		"mousemove": function(event) {
    			if(obj.onGfx == 1) {
    				obj.mousePosX = event.client.x-obj.getPosition().x;
    				obj.mousePosY = event.client.y-obj.getPosition().y;

    				if(obj.mousePosX < 5) {
    					obj.set("src", obj.GFX.replace("::i::", 0));
    				} else if(obj.mousePosX < 15) {
    					obj.set("src", obj.GFX.replace("::i::", 1));
    				} else if(obj.mousePosX < 30) {
    					obj.set("src", obj.GFX.replace("::i::", 2));
    				} else if(obj.mousePosX < 47) {
    					obj.set("src", obj.GFX.replace("::i::", 3));
    				}
    			}
    		},

    		"click": function(event) {
    			obj.mousePosX = event.client.x-obj.getPosition().x;
				obj.mousePosY = event.client.y-obj.getPosition().y;

				if(obj.mousePosX < 5) {
					obj.VALUE = 0;
				} else if(obj.mousePosX < 15) {
					obj.VALUE = 1;
				} else if(obj.mousePosX < 30) {
					obj.VALUE = 2;
				} else if(obj.mousePosX < 47) {
					obj.VALUE = 3;
				}

				//alert(document.location + "&action=save&"+this.get("ID")+"="+obj.VALUE);
				document.location = document.location + "&action=save&"+this.get("ID")+"="+obj.VALUE;
    		}
    	});
    });

});

/* 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>Die 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) {
				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() {

				if($('upload-complete')) {
					var tmpLink = window.location.href.split("?");
					var tmpLink2 = tmpLink[1].split("&");
					var link = tmpLink[0];
					for(var i=0, c=0; i<tmpLink2.length;i++) {
						if(tmpLink2[i].split("=")[0] != "action" || tmpLink2[i].split("=")[1] != "save") {
							if(c==0) {
								link += "?";
								c++;
							} else {
								link += "&";
							}
							link += tmpLink2[i].split("=")[0] + "=" + tmpLink2[i].split("=")[1];
						}
					}
					$('upload-complete').set('html', '<br/><b><a href="'+link+'" onClick="javascript:window.location.replace(\''+link+'\');return 0;">Upload abschlie&szlig;en</a></b>');
				}
				//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;
		if(document.getElementById("apply")) document.getElementById("apply").src = save_button.replace("sichern", "apply");
		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();
}


