//
// Autrado JavaScript-Funktionen
//

var objBody;

// Allgemeine Funktion für Popup
function MM_openBrWindow(theURL, winName, features) {
	var newwindow = window.open(theURL, winName, features);
	newwindow.focus();
}


// Popup: Autrado-Galerie-Auswahl
function autradogalerie(field, galerie) {
	var newwindow = window.open('autradogaleriepopup.php?galerie='+galerie+'&field='+field, 'autradogalerie', 'width=630, height=620, scrollbars=yes');
	newwindow.focus();
}

// Popup: CSV-Importassistent
function csvimport(p_title, p_table, p_args) {
	var l_params = "";

	for(l_arg in p_args) {
		l_params += "&" + encodeURI(l_arg) + "=" + encodeURI(p_args[l_arg]);
	}

	GB_showFullScreen(p_title, '../../csvimport.php?table='+p_table+l_params);
}

// Popup: CSV-Exportassistent
function csvexport(p_title, p_type, p_ids) {
	GB_showFullScreen(p_title, '../../csvexport.php?type='+encodeURI(p_type)+'&ids='+encodeURI(Object.toJSON(p_ids)));
}

// Checkall
function checkall(name, status) {
	$$('*[name^="'+name+'"]').each(function(p_e) {
		if(p_e.disabled || p_e.style.visibility == 'hidden') return;
		if(status) {
			if(!p_e.checked) p_e.click();
		} else {
			if(p_e.checked) p_e.click();
		}
	});
}

function checkall_id(name, status) {
	var e = null;
	var i = 0;
	do {
		e = document.getElementById(name + "_" + i);
		if ( e && !e.disabled && e.style.visibility != 'hidden' ) {
			if (status==1) {
				if (!e.checked) e.checked = true;
			} else {
				if (e.checked) e.checked = false;
			}
		}
		i++;
	} while (e);
}


// Alle aktivieren mit automatischer Umschaltung auf alle deaktivieren
function checkall_id_toggle(name, enabled) {
	checkall_id(name, enabled);
}


// OnMouseOver Navigation links
function hl(id, color){
	document.getElementById('nav'+id).style.backgroundColor = color;
}


// Versteckten Text aufklappen
function toggledisplay(p_id, p_indicator) {
	// Icons aus Verzeichnis bilder
	var l_hide_gif = verzeichnis_bilder + 'toggle_div_show.gif',
			l_show_gif = verzeichnis_bilder + 'toggle_div_hide.gif';

	var l_obj = $(p_id), l_pic = document.getElementsByName(p_indicator)[0]
  	if(l_obj && l_pic) {
  		// zielobjekt ein- / ausblenden
 		l_obj.setStyle({
 			display: ( (l_obj.getStyle('display')=='none') ? 'block' : 'none' )
 		});

  		// bild wechseln
 		l_pic.src = ( (l_obj.getStyle('display')=='none') ? l_show_gif : l_hide_gif );
  	}
}


// Eingabefeld beim erstmaligen Aktivieren leeren
function onfocus_empty(field) {
	if ( field.value == field.defaultValue ) {
		field.value = '';
	}
}


// Beim Verlassen des leeren Eingabefelds den Defaultinhalt wiederhersteller
function onfocus_empty_blur(field) {
	if ( field.value == '' ) {
		field.value = field.defaultValue;
	}
}


// Ein Datumsfeld auf das aktuelle Datum setzen
function setdate_today(field) {
	var zeit = new Date();
	var jahr = zeit.getFullYear();
	var monat = zeit.getMonth() + 1;
	var tag = zeit.getDate();
	field.value = tag + "." + monat + "." + jahr;
}


// Alles auswaehlen in Farbmatrix
function farbmatrix_selectall(p_ce, p_id, p_cor) {
	var l_list = document.getElementsByTagName('input');
	if(l_list) {
		for(var l_i = 0; l_i < l_list.length; l_i++) {
			var l_e = l_list[l_i];

			if(l_e.type != "checkbox") continue;

			var l_r = p_cor
				// used for rows
				? "^checkbox_farbkombinationen\\[" + p_id + "_"
				// used for columns
				: "^checkbox_farbkombinationen\\[(.*?)_" + p_id + "\\]";

			if(l_e.name.match(l_r) && !l_e.readonly && !l_e.disabled) {
				l_e.checked = p_ce;
			}
		}
	}
}


/**
 * Selectall-Controls für Farbmatrix neu berechnen
 * p_id = row/column ID
 * p_cor = column or row
 * p_cfa = check for all (damit wir die Control zur Selektion aller neu berechnet)
 */
function farbmatrix_recheck(p_id, p_cor, p_cfa)
{
	var l_selected		= 0,
		l_unselected	= 0,
		l_allselected	= 0,
		l_allunselected = 0;

	var l_list = document.getElementsByTagName('input');
	if(l_list) {
		for(var l_i = 0; l_i < l_list.length; l_i++) {
			var l_e = l_list[l_i];

			if(l_e.type != "checkbox") continue;

			// check for col/row
			var l_r = p_cor
				// used for rows
				? "^checkbox_farbkombinationen\\[" + p_id + "_"
				// used for columns
				: "^checkbox_farbkombinationen\\[(.*?)_" + p_id + "\\]";

			if(l_e.name.match(l_r)) {
				if(l_e.checked) {
					l_selected++;
				} else {
					l_unselected++;
				}
			}

			// check for all
			if(p_cfa) {
				l_r = "^checkbox_farbkombinationen\\[";

				if(l_e.name.match(l_r)) {
					if(l_e.checked) {
						l_allselected++;
					} else {
						l_allunselected++;
					}
				}
			}
		}
	}


	// SELECTALL-Checkbox für Spalte oder Zeile anhaken
	selectall_change(
		(
			p_cor
			? $("selectallColumn_" + p_id)
			: $("selectallRow_" + p_id)
		),
		(l_selected > l_unselected),
		""
	);

	if(p_cfa) {
		// SELECTALL-Checkbox für alle anhaken
		selectall_change(
			$("selectallAll"),
			(l_allselected > l_allunselected),
			""
		);
	}
}


/**
 * Genereller Handler für selectall-Controls
 * p_callback ist eine JavaScript-Funktion, die nach
 * Klick auf die Control aufgerufen wird und %state%
 * beinhalten kann, was on-the-fly durch den aktuellen
 * Status ersetzt wird.
 */
function selectall_change(p_checkbox, p_state, p_callback)
{
	p_checkbox.checked = p_state;
	if(p_callback != "") {
		p_callback = p_callback.replace(/%state%/g, p_state ? 'true' : 'false');
		eval(p_callback);
	}
}


/**
 * Genereller Handler für selectall-Controls
 * Geht davon aus, dass alle Spalten (cellIndex) im Header die gleichen
 * sind wie in den Datenreihen, also keine Colspan 
 */
function selectall_column(chk_box, deacttitle, acttitle){
	var colidx=get_corrected_cellIndex(chk_box.parentNode)
	var state=chk_box.checked;
	chk_box.title=state ? deacttitle : acttitle;
	var rows=$(chk_box).up('tbody').getElementsBySelector('tr')	
	for(var i=1; i<rows.length;i++){
		var t_chkbox=null;
		if(!rows[i].cells[colidx])continue;
		var chkboxes=rows[i].cells[colidx].getElementsByTagName("INPUT");
		for(var j=0; j<chkboxes.length; j++) if(chkboxes[j].type=="checkbox")t_chkbox=chkboxes[j];
		if(t_chkbox){
			t_chkbox.checked=state;
			if(t_chkbox.onclick)t_chkbox.onclick()
		}
	}
}


function get_corrected_cellIndex(cel){
	var r=cel.parentNode;
	var i=0;
	var celcnt=0;
	while(r.cells[i] && r.cells[i]!=cel){
		if(r.cells[i].colSpan>1) celcnt+=r.cells[i].colSpan;
		else celcnt++
		i++;
	}
	return celcnt;
}






// Überprüft, ob eine JavaScript-Funktion vorhanden ist
function function_exists( function_name ) {
    if (typeof function_name == 'string'){
        return (typeof window[function_name] == 'function');
    } else{
        return (function_name instanceof Function);
    }
}

// Helperfunktion zum Ermitteln von Elementinhalten

// Suche nach einem bestimmten DOM-Element in einem bestimmten Formular
function get_element_by_form(p_e, p_f)
{
	var l_e = document.getElementsByName(p_e);
	if(l_e) {
		for(c_i = 0; c_i < l_e.length; c_i++) {
			var l_ce = l_e[c_i];

			if(l_ce.form && l_ce.form.name == p_f) {
				return l_ce;
			}
		}
	}

	return null;
}

// Rückgabe eines gewählten RADIO-Elements
function radio_get(p_ename)
{
	var l_e = document.getElementsByName(p_ename);
	if(l_e && l_e.length > 0) {
		for(c_i = 0; c_i < l_e.length; c_i++) {
			if(l_e[c_i].checked) {
				return l_e;
			}
		}
	}

	return null;
}

// Rückgabe von gewähltem SELECT-Element
function select_get(p_ename, p_form)
{
	var l_e = get_element_by_form(p_ename, p_form);
	if(l_e) {
		return l_e.options[l_e.selectedIndex].value;
	}

	return null;
}

// Rückgabe von INPUT(TEXT)-Inhalt
function text_get(p_ename, p_form)
{
	var l_e = get_element_by_form(p_ename, p_form);
	if(l_e) {
		return l_e.value;
	}

	return null;
}

// Rückgabe von INPUT(CHECKBOX)-Status als 0 / 1
function checkbox_get(p_ename, p_form)
{
	var l_e = get_element_by_form(p_ename, p_form);
	if(l_e) {
		return l_e.checked ? 1 : 0;
	}

	return null;
}


// Zeichenzaehler
function update_chars(name, maxlength) {
	var l_area = document.getElementsByName(name)[0];
	var l_cf = document.getElementById(name + '_chars');
	if (l_area && l_cf) {
		if (l_area.value.length > maxlength) {
			l_area.value = l_area.value.substring(0, maxlength);
			l_area.style.backgroundColor = '#FFCCCC';
		} else {
			l_cf.value = maxlength - l_area.value.length;
			l_area.style.backgroundColor = '#FFFFFF';
		}
	}
}


// Toggler (verwendet in Inhalte&Design / Jobverfolgung)
function toggler(p_name, p_flipicon) {
	for(l_i = 0; ; l_i++) {
		var l_e = document.getElementById('toggler__' + p_name + '__' + l_i);
		if(l_e) {
			l_e.style.display = (l_e.style.display == '') ? 'none' : '';
		} else break;
	}

	if(p_flipicon) {
		var l_eimg = document.getElementById(p_name + '_icon');
		if(l_eimg) {
			var l_imgmatch = /^(.*)toggle_div_(.*)\.gif$/;
			l_imgmatch.exec(l_eimg.src);
			l_eimg.src = (
				(RegExp.$2 == 'show')
				? RegExp.$1 + 'toggle_div_hide.gif'
				: RegExp.$1 + 'toggle_div_show.gif'
			);
		}
	}
}


// Collapser-Klasse für DbTableAdmin
function collapser() {
	// Default-values
	this.bgcol_expanded = '#FFFFFF';
	this.bgcol_collapsed = '#CCCCCC';
	this.width_collaped = '20px';
	this.buffer = [];
	var l_agent = navigator.userAgent.toLowerCase();
	this.is_ie = (( l_agent.indexOf("msie")  != -1 ) && ( l_agent.indexOf("opera") == -1 ));
	this.use_cookies = false;
	this.cookie_days = 3;
}

collapser.prototype.init = function()
{
	if(arguments.length > 0 && arguments.length & 1) {
		alert('collapser::init: invalid count of arguments!');
		return false;
	}

	var l_key = "";
	for(var l_i = 0; l_i < arguments.length; l_i++) {
		if(l_i & 1) {
			// value
			eval("this." + l_key + "='" + arguments[l_i] + "'");
		} else {
			// key
			l_key = arguments[l_i];
		}
	}

	return true;
}

collapser.prototype.onmouseover = function(p_e)
{
	if(p_e) {
		p_e.style.backgroundColor = this.bgcol_collapsed;
		p_e.style.cursor = 'pointer';
	}
}

collapser.prototype.onmouseout = function(p_e)
{
	if(p_e) {
		p_e.style.backgroundColor = this.bgcol_expanded;
		p_e.style.cursor = '';
	}
}

collapser.prototype.cookie_write = function(p_names, p_vals, p_days)
{
	var l_expires = "";

	if(p_days) {
		var l_date = new Date();
		l_date.setTime(l_date.getTime() + (p_days * 24 * 60 * 60 * 1000));
		l_expires = "expires=" + l_date.toGMTString();
	}

	var l_cs = "data=";
	for(var i = 0; i < p_names.length; i++) {
		l_cs += p_names[i] + "=" + p_vals[i] + ",";
	}

	l_cs += l_expires;

	document.cookie = l_cs;
}

collapser.prototype.cookie_read = function(p_name)
{
	var l_rx = new RegExp(p_name + "=(.*?),");

	l_rx.exec(document.cookie);

	return RegExp.$1;
}


collapser.prototype.load_from_cookie = function(p_table)
{
	var l_tbl = document.getElementById(p_table);
	if(l_tbl) {
		var l_i,
			l_row = l_tbl.rows[0],
			l_tocollapse = [];

		if(l_row) {
			// iteriere ueber alle spalten
			for(l_i = 0; l_i < l_row.cells.length; l_i++) {
				var l_td = l_tbl.rows[0].cells[l_i];

				if(this.cookie_read('column' + l_i) == 1) {
					l_tocollapse.push(l_td);
					l_tocollapse.push(l_i);
				}
			}
		}

		if(l_tocollapse.length > 0) {
			for(l_i = 0; l_i < l_tocollapse.length; l_i+=2) {
				this.onclick(l_tocollapse[l_i], l_tocollapse[l_i+1]);
			}
		}
	}
}

collapser.prototype.save_cookie = function(p_e)
{
	var l_tbl = p_e.parentNode.parentNode.parentNode,
		l_row = l_tbl.rows[0],
		l_names = [], l_vals = []; // daten fuer cookie

	// erste zeile (wir benoetigen die th's)
	if(l_row) {
		for(l_i = 0; l_i < l_row.cells.length; l_i++) {
			var l_td = l_tbl.rows[0].cells[l_i];

			l_names.push('column' + l_i);

			// eingeklappte zeilen haben name=collapsed
			// 1 = eingeklappt, 0 = ausgeklappt
			if(l_td.name == 'collapsed') {
				l_vals.push(1);
			} else {
				l_vals.push(0);
			}
		}

		// ok, in cookie speichern
		this.cookie_write(l_names, l_vals, this.cookie_days);
	}
}

collapser.prototype.onclick = function(p_e, p_index)
{
	var l_tbl = p_e.parentNode.parentNode.parentNode,
		l_rc = l_tbl.rows.length;
	for(l_i = 0; l_i < l_rc; l_i++) {
		l_td = l_tbl.rows[l_i].cells[p_index];
		if(!this.buffer[p_index]) this.buffer[p_index] = [];
		if(l_td.name != 'collapsed') {
			// "backup" TD contents
			this.buffer[p_index][l_i] = l_td.innerHTML;
			this.buffer[p_index].cell_count = l_rc;
			if(l_i == 0) {
				// für table head
				l_td.style.backgroundColor = this.bgcol_expanded;
				l_td.rowSpan = l_tbl.rows.length;
				// strip HTML
				var l_str = l_td.innerHTML.replace(/\<(.*?)\>/gi, ""), l_new = "";
				if(this.is_ie) {
					// rotate Text im IE
					l_td.innerHTML = l_str;
					l_td.style.writingMode = 'tb-rl';
				} else {
					// "vertikalen" Text erstellen
					for(var l_j = 0; l_j < l_str.length; l_j++) {
						l_new += l_str.substr(l_j,1) + "<br />";
					}
					l_td.innerHTML = l_new;
				}
				// Breite anpassen und Kennzeichnung im TH setzen
				l_td.style.width = this.width_collaped;
				l_td.name = 'collapsed';
			} else {
				l_td.innerHTML = '';
				l_td.style.display = 'none';
			}
		} else {
			// Cell-Wiederherstellung im seperaten Loop
			for(l_j = 0; l_j < this.buffer[p_index].length; l_j++) {
				var l_cell = l_tbl.rows[l_j].cells[p_index];

				if(l_j == 0) {
					if(this.is_ie) {
						l_td.style.writingMode = '';
					}
					l_cell.rowSpan = 1;
				}

				l_cell.innerHTML = this.buffer[p_index][l_j];
				l_cell.style.display = '';
			}
			l_td.name = null;
			break;
		}
	}

	this.save_cookie(p_e);

	return;
}

function ask_user(p_question, p_link)
{
	if(confirm(p_question)) {
		window.location.href = p_link;
	}
}

function select_select(p_e, p_v)
{
	if(!p_e || !p_e.options) return;

	for (var i=0; i<p_e.options.length; i++) {
		p_e.options[i].selected = (p_e.options[i].value == p_v);
	}
}

// Disabled-Emulation für SELECT Options auf dem IE
function select_emulate_disabled(p_e)
{
	if(!p_e || !p_e.options) return false;

	var deactivated = false;

 	for (var i=0, option; option = p_e.options[i]; i++) {
        if (option.disabled) {
			option.style.color = "#CCCCCC";
		}else{
			option.style.color = "#000000";
		}

		if(option.selected && option.disabled){
			option.selected=false;
			if(navigator.userAgent.toLowerCase().indexOf("msie") != -1) {
				p_e.selectedIndex = -1;
			}

			deactivated = true;
        }
	}

	// Wenn etwas deaktiviert wurde, sollten im IE weitere
	// Vorgänge abgebrochen werden!
	return deactivated;
}

// Support function for Splash Screen!
var g_opacity = 0.0;

function _splash_setopacity(p_e, p_val)
{
	if(navigator.userAgent.toLowerCase().indexOf("msie") != -1) {
		// lame ie
		p_e.style.filter = 'alpha(opacity=' + (p_val * 100.0) + ')';
	} else {
		// gecko etc.
		p_e.style.opacity = p_val;
	}
}

function _splash_fadeout(p_id)
{
	var e = document.getElementById(p_id);
	if(e) {
		g_opacity -= 0.05;

		// set opacity
		_splash_setopacity(e, g_opacity);

		if(g_opacity <= 0.0) {
			// hide and free document
			e.style.display = 'none';

			var wl = document.getElementById('splashwl');
			if(wl) {
				wl.style.display = 'none';
			}

			return;
		}

		window.setTimeout("_splash_fadeout('" + p_id + "')", 40);
	}
}

function lock(p_str)
{
	var e = Builder.node('div', {
		style: 'display: none; position: fixed; z-index: 65536; top: 50%; left: 50%; width: 500px; height: 70px; margin: -50px auto auto -250px; border: 1px solid #666; background-color: #fff; text-align: center; padding: 10px;'
	}, [
		Builder.node('img', {
			src: 'bilder/lightbox-loading.gif'
		}),
		Builder.node('p', {
			style: 'font-weight: bold; font-size: 1.1em;'
		}, p_str)
	]);

	$('container').appendChild(e);

	Effect.Appear(e, { duration: 1.5 });
}

function splash_fadein(p_id, p_firstrun, p_withfadeout)
{
	var e = document.getElementById(p_id);
	if(e) {
		if(p_firstrun) {
			// unhide and lock document element on first run
			e.style.display = 'block';
			e.style.cursor = 'pointer';
			e.onclick = function() {
				_splash_fadeout(p_id);
			}

			var wl = document.getElementById('splashwl');
			if(wl) {
				wl.style.display = 'block';
				if(navigator.userAgent.toLowerCase().indexOf("msie") != -1) {
					wl.style.width = objBody.clientWidth + 'px';
					wl.style.height = objBody.clientHeight + 'px';
				} else {
					wl.style.width = window.innerWidth + 'px';
					wl.style.height = window.innerHeight + 'px';;
				}
			}
		}

		g_opacity += 0.05;

		// set opacity
		_splash_setopacity(e, g_opacity);

		if(g_opacity >= 1.0) {
			if(p_withfadeout) {
				window.setTimeout("_splash_fadeout('" + p_id + "')", 1500);
			}
			return;
		}

		window.setTimeout("splash_fadein('" + p_id + "', false, " + (p_withfadeout?'true':'false') + ")", 70);
	}
}

function number_format( number, decimals, dec_point, thousands_sep ) {
    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point == undefined ? "." : dec_point;
    var t = thousands_sep == undefined ? "," : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;

    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

function form_check( p_formname, p_checks, p_errors ) {
	var l_formokay = true;

	for(l_field in p_checks) {
		var l_ret = '';

		var l_e = get_element_by_form(l_field, p_formname);
		if(!l_e) return false;

		var l_val = trim(Form.Element.getValue(l_e));

		p_checks[l_field].each(function(p_check) {
			switch(p_check) {
			case "not_empty":
				if(l_val.blank()) {
					l_ret = p_check;
					throw $break;
				}
				break;
			case "valid_email":
				if(!l_val.match(/<?([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)>?$/i)) {
					l_ret = p_check;
					throw $break;
				}
				break;
			}
		});

		if(l_ret != '') {
			alert(p_errors[l_ret]);

			Form.Element.activate(l_e);
			Form.Element.focus(l_e);

			l_e.setStyle({backgroundColor: '#FFD4D4'});

			l_formokay = false;

			break;
		} else {
			l_e.setStyle({backgroundColor: ''});
		}
	}

	return l_formokay;
}

var g_navoben_current = null;

// Navigation (de)aktivieren
function navoben_handle(p_menu) {
	var l_e;

	// Für zur Zeit aktive Navigation wird folgender Block angewendet
	if(g_navoben_current) {
		// Obernavigationspunkt deaktivieren
		l_e  = $('naventry_'+g_navoben_current);
		if(l_e) {
			l_e.className = '';
			l_e.down().className = "";
		}

		// Alte Navigation ausblenden
		l_e = $('navcontainer_'+g_navoben_current);
		if(l_e) {
			l_e.setStyle({display: 'none'});
		}
	}

	// Obernavigationspunkt aktivieren
	l_e = $('naventry_'+p_menu);
	if(l_e) {
		l_e.className = 'akt';
		l_e.down().className = 'akt';
	}

	// Neue Navigation anzeigen
	l_e = $('navcontainer_'+p_menu);
	if(l_e) {
		l_e.setStyle({display: 'block'});
	}

	g_navoben_current = p_menu;
}


function window_create(p_event, p_title, p_content, p_args) {
	var l_args = Object.extend({
		className:      'windows',
		resizable:      false,
		closable:       true,
		minimizable:    true,
		maximizable:    true,
		draggable:      false,
		title:          p_title,
		left:           Event.pointerX(p_event),
		top:            Event.pointerY(p_event),
		destroyOnClose: true,
		closeIfExists:  false,
		zIndex:         65500,
		effectOptions: {
			duration: 0.3
		},
		openOnRightBottomCorner: false,
		openOnRightCorner:       false,
		showWindowOnCreation:    true
	}, p_args || {});

	if(l_args.openOnRightBottomCorner) {
		l_args.left = l_args.left - l_args.width;
		l_args.top  = l_args.top - l_args.height;
	}
	if(l_args.openOnRightCorner) {
		l_args.left = l_args.left - l_args.width;
	}

	var l_win = Windows.getWindow(p_args.id);
	if(l_win != null && l_args.closeIfExists) {
		l_win.close();
	}

	if(Windows.getWindow(p_args.id) == null) {
		var l_win = new Window(l_args);

		l_win.setHTMLContent(p_content);

		if(l_args.showWindowOnCreation) {
			l_win.show();
		}
	}
}

function detailtip_show(p_event, p_id, p_content, p_args) {
	if(!window['tt_'+p_id]) {
		if($(p_id) == null) {
			var l_e = Builder.node('span', {id: p_id, display: 'none'});
			$('alles').appendChild(l_e);
		}

		window['tt_'+p_id] = new Tooltip($(p_id), Object.extend({
			backgroundColor: '#fff',
			handleOnClick: false,
			content: p_content,
			maxWidth: 400
		}, p_args || {}));

		window['tt_'+p_id].toggle(p_event);
	}
}

function detailtip_close(p_event, p_id) {
	if(window['tt_'+p_id]) {
		window['tt_'+p_id].toggle(p_event);
		window['tt_'+p_id] = null;
	}
}


// Wird auf Browsern benötigt, die nicht ECMAScript 3 entsprechen
if(!Array.prototype.push) {
	function array_push() {
		for(var i=0;i<arguments.length;i++){
			this[this.length]=arguments[i]
		};
		return this.length;
	}
	Array.prototype.push = array_push;
}

// Die Values aller aktivierten Checkboxen des Formulars raussuchen
function get_checked_csa(clist) {
	var b = [];
	for (var i = 0; i < clist.length; i++) {
		if (clist[i].checked) {
			b.push(clist[i].value);
		}
	}
	return b.join(",");
}

function trim(p_s) {
	return p_s.replace (/^\s+/, '').replace (/\s+$/, '');
}

function html_entity_decode(str) {
    try {
		var  tarea=document.createElement('textarea');
		tarea.innerHTML = str; return tarea.value;
		tarea.parentNode.removeChild(tarea);
	} catch(e) {
		//for IE add <div id="htmlconverter" style="display:none;"></div> to the page
		document.getElementById("htmlconverter").innerHTML = '<textarea id="innerConverter">' + str + '</textarea>';
		var content = document.getElementById("innerConverter").value;
		document.getElementById("htmlconverter").innerHTML = "";
		return content;
	}
}

function bv_rating_mousemove(p_fahrzeug, p_element, p_event) {
	var l_x = (Event.pointerX(p_event) - 5) - Element.viewportOffset(p_element).left;

	l_x -= 2;
	l_x += 11 - (l_x % 11);
	l_x += 2;

	if(l_x > 70) l_x = 70;

	console.log('mousemove ' + l_x);

	p_element.previous().setStyle({width: l_x + 'px'});
}

function bv_rating_mouseout(p_fahrzeug, p_element, p_event) {
	l_value = parseInt($('bv_rating_'+p_fahrzeug).value);
	if(!l_value) {
		var l_width = 0;
	} else {
		var l_width = ((7 - l_value) * 11) + 2;
	}

	if(l_width > 70) l_width = 70;

	p_element.previous().setStyle({width: l_width + 'px'});
}

function bv_rating_click(p_fahrzeug, p_element, p_event) {
	var l_value, l_x = Event.pointerX(p_event) - Element.viewportOffset(p_element).left;

	l_x -= 2;
	l_x += 11 - (l_x % 11);

	l_value = l_x / 11;
	if(l_value > 6) l_value = 6;
	l_value = 7 - l_value;

	l_x += 2;

	$('bv_rating_'+p_fahrzeug).value = l_value;
}

function preislistendesigner_open(p_title) {
	GB_showFullScreen(p_title, '../../preislistendesigner.php');
}

function emm_designer_open(p_title) {
	GB_showFullScreen(p_title, '../../emm_designer.php');
}

window.fal_loaded = function() {
	$$('.fal div.content').each(function(p_content) {
		Event.observe(p_content, 'click', function(p_event) {
			this.down('input').checked = true;
			new Effect.toggle(this.up('li.a').down('div.i'), 'slide');
			this.style.opacity = 1.0;
			$$('.fal div.content').each(function(p_e) { p_e.style.color = ''; });
			this.style.color = "#"+window.colorlinks;
			$$('.fal div.i input').each(function(p_radio) {
				p_radio.checked = false;
			});
			var l_i = this.up().getElementsBySelector('div.i li.i input');
			if(l_i.length == 1) {
				l_i[0].checked = true;
				l_i[0].click();
			}
			$$('.fal div.i').each(function(p_div) {
				if(p_div.visible()) {
					p_div.previous('div.content').down('div.left').down('input').checked = false;
					p_div.up('li.a').style.opacity = 0.9;
					new Effect.SlideUp(p_div);
				}
			});
		});
	});
	$$('.fal li.i').each(function(p_li) {
		Event.observe(p_li, 'click', function(p_event) {
			this.down('input').checked = true;
			this.down('input').click();
			$$('.fal li.i').each(function(p_e) {
				if(p_e.previous('.colorStore').value != '') {
					p_e.style.color = "#"+p_e.previous('.colorStore').value;
				} else {
					p_e.style.color = '';
				}
			});
			this.style.color = "#"+window.colorlinks;
			if(!Prototype.Browser.IE) Event.stop(p_event);
		});
	});
};

function register_prefilled_input(p_element, p_prefilled_text, p_value) {
	document.observe('dom:loaded', function() {
		p_element.observe('focus', function() {
			if($F(this) == p_prefilled_text) {
				this.value = '';
				this.writeAttribute('style', '');
			}
		});
		p_element.observe('blur', function() {
			if($F(this) == '') {
				p_element.value = p_prefilled_text;
				p_element.setStyle({
					color:     '#ccc',
					fontStyle: 'italic'
				});
				p_element.next('input').value = '';
			}
		});
		var l_keyin_handler = function() {
			p_element.next('input').value = $F(p_element);
		}
	
		p_element.observe('keyup', l_keyin_handler);
		p_element.observe('paste', l_keyin_handler);
		p_element.observe('input', l_keyin_handler);
		
		p_element.value = p_value;
		
		if($F(p_element) == '') {
			p_element.value = p_prefilled_text;
			p_element.setStyle({
				color:     '#ccc',
				fontStyle: 'italic'
			});
			
			p_element.next('input').value = '';
		} else {
			p_element.next('input').value = $F(p_element);	
		}
	});
}

function register_calendars() {
	var reg_cal = function() {
        $$('.calendarview').each(function(p_e) {
            Calendar.setup({dateField: p_e, triggerElement: p_e.next('img.calendar_trigger')});	
        });
    };

    document.observe('dom:loaded', reg_cal);
	document.observe('cal:fire', reg_cal);
}

// ---------------------------------------------------------------------------------------------------------------------------------------------------------
// !!!!! EIGENE JAVASCRIPT-ROUTINEN BITTE NICHT UNTERHALB DIESES ABSCHNITTS INTEGRIEREN !!!!!
// ---------------------------------------------------------------------------------------------------------------------------------------------------------
// Liste mit Jobs, die nach DOM-Initialisierung auszuführen sind
var g_dominit_jobs = [];

// Splash anzeigen? Wird innerhalb von head.php evtl. überschrieben!
var g_splash = false;

// Initialisierungsroutine die gestartet wird, wenn das DOM vollständig geladen ist
function on_dominit() {
	// Nur einmal ausführen ...
	if(arguments.callee.done) return;
	arguments.callee.done = true;

	// CSS-CompatMode vom IE unterstützen
	if(document.all && !window.opera){
		objBody =
			(window.document.compatMode == "CSS1Compat")
			? window.document.documentElement
			: window.document.body || null;
	} else {
		objBody = document.documentElement;
	}


	// Jobs ausführen
	for(var l_i = 0; l_i < g_dominit_jobs.length; l_i++) {
		eval(g_dominit_jobs[l_i]);
	}

	// Transparente PNGs für IE6 ermöglichen
	var l_agent = navigator.userAgent.toLowerCase();
	var l_isie  = (( l_agent.indexOf("msie")  != -1 ) && ( l_agent.indexOf("opera") == -1 ));
	if(l_isie) {
		for (var l_i = 0; l_i < document.images.length; l_i++) {
			var l_img = document.images[l_i];
			if(l_img.src.search(/_at\.png$/) != -1) {
				l_img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + l_img.src + "', enabled=true)";
				l_img.src = 'bilder/spacer.gif';
			}
		}
	}

	// Splashscreen einblenden
	if(g_splash) {
		splash_fadein('splash', true, true);
	}
}
if(document.addEventListener) document.addEventListener("DOMContentLoaded", on_dominit, false);
window.onload = on_dominit;

// Firebug-Console Support
var debugging = true;
if (typeof console == "undefined") {
	var console = { log: function() {} };
} else if (!debugging || typeof console.log == "undefined") {
	console.log = function() {};
}

