/* KLIK EDV GmbH Javascript library 20060223 */

function k_update_img_input (_img_input_id, _img_img_id, _img_original_img_value)
{
	if ($(_img_input_id).value != "")
	{
		$(_img_img_id).src = $(_img_input_id).value;
	}
	else {
		$(_img_img_id).src = _img_original_img_value;
	}
}

function k_update_bg_input (_img_input_id, _img_img_id, _img_original_img_value)
{
	if ($(_img_input_id).value != "")
	{
		$(_img_img_id).style.backgroundImage = "url(" + $(_img_input_id).value + ")";
	}
	else {
		$(_img_img_id).style.backgroundImage = _img_original_img_value;
	}
}

function k_check_display_dependance (_sup_id, _sup_critical_value, _condition, _sub_id, _inline)
{
	if (_condition == true) {
		if ($(_sup_id).value != _sup_critical_value)
		{
			$(_sub_id).style.display = "none";
		}
		else {
			if (_inline == "inline") {
				$(_sub_id).style.display = "inline";
			}
			else {
				$(_sub_id).style.display = "block";
			}
		}
	}
	else {
		if ($(_sup_id).value == _sup_critical_value)
		{
			$(_sub_id).style.display = "none";
		}
		else {
			if (_inline == "inline") {
				$(_sub_id).style.display = "inline";
			}
			else {
				$(_sub_id).style.display = "block";
			}
		}
	}

}

function k_popup (target, width, height, options)
{
	if (target == "image_helper")
	{
		target = "/system?action=image_helper_show_images&onlyprivate=true";
		width = 424;
		height= 272;
		options = "scrollbars=no,resizable=no,status=no";
	}
	F1 = window.open(target,"popup","width=" + width + ",height=" + height + ",left=" + ((screen.width - width) / 2) + ",top=" + ((screen.height - height) / 2) + "," + options);
	F1.focus();
}

// 20071010 -kramer- _button_id, _form_id parameter added with old values as default //
function k_save_page_finish (_button_id, _form_id)
{
	var button_id = (_button_id != undefined) ? _button_id : "website_change_save_finish";
    $(button_id).disabled = "disabled";
    for (var i = 0; i < _non_wysiwyg_fields_xml.length; ++i)
    {
    	document.getElementsByName(_non_wysiwyg_fields_xml[i])[0].value = document.getElementsByName(_non_wysiwyg_fields_dom_name[i])[0].value;
    }
    toggle_editor(null);	
	var form_id = (_form_id != undefined) ? _form_id : "website_change_save_finish_form";
    $(form_id).submit();
}

function k_save_page_async(_form_id)
{
	$("website_change_save_async").disabled = "disabled";
	for (var i = 0; i < _non_wysiwyg_fields_xml.length; ++i)
	{
		document.getElementsByName(_non_wysiwyg_fields_xml[i])[0].value = document.getElementsByName(_non_wysiwyg_fields_dom_name[i])[0].value;
	}
	toggle_editor(null);
	var _ajaxreq = {
		method: "post",
		postBody: "wsm_save_page_finished=false&" + Form.serialize(_form_id),
		onSuccess: function(t) {
			window.setTimeout("$('website_change_save_async').disabled = '';", 5000);
		},
		on404: function(t) {
			alert("Error 404: location '" + t.statusText + "' was not found.");
		},
		onFailure: function(t) {
			alert("Error " + t.status + " -- " + t.statusText);
		}
	}
	new Ajax.Request("/website?action=change_page_content_save", _ajaxreq);
}	

function k_save_wysiwyg_back (_element_id,_html,_body)
{
	/*
	for (var i = 0; i < _wysiwyg_fields_dom_name.length; ++i)
	{
		if (_wysiwyg_fields_dom_name[i] == _element_id)
		{
			document.getElementsByName(_wysiwyg_fields_xml[i])[0].value = _html;
		}
	}	
	*/
}

function k_change_form_init ()
{
	if (_non_wysiwyg_fields_xml.length != 0)
	{
		document.getElementsByName("fields_to_update")[0].value = _non_wysiwyg_fields_xml.join(",") + ",";
	}
	document.getElementsByName("fields_to_update")[0].value += _wysiwyg_fields_xml.join(",");
}	

//--- TINYMCE SPECIFIC FUNCTIONS --//
function k_tinymce_init ( _css_styles, _toolbar_1, _toolbar_2, _toolbar_3, _handle_event_callback, _init_instance_callback, _toolbar_location, _default_blockformats)
{
	//var _wysiwyg_fields_string = _wysiwyg_fields_dom_name.join(",");
	
	tinyMCE.init({
		language : "de",
		mode : "none",
//		mode : "exact",
//		elements : _wysiwyg_fields_string,
		button_tile_map : true,
		plugins : "KLIKTemplate,table,advhr,advimage,advlink,paste,media,layer,searchreplace,print,style,contextmenu,noneditable,inlinepopups",
		theme : "advanced",
		theme_advanced_layout_manager : "SimpleLayout",
		theme_advanced_toolbar_location : (_toolbar_location != undefined) ? _toolbar_location : "external",
		theme_advanced_buttons1 : (_toolbar_1 != undefined) ? _toolbar_1 : "code,separator,print,separator,cut,copy,paste,pastetext,pasteword,selectall,separator,undo,redo,separator,search,replace,spacer,spacer,spacer,spacer,spacer,spacer,spacer,spacer,spacer,spacer,spacer,styleselect,separator,table,advhr,charmap,separator,visualaid,removeformat,cleanup,separator,newdocument", 
		theme_advanced_buttons2 : (_toolbar_2 != undefined) ? _toolbar_2 : "bold,italic,underline,strikethrough,separator,sub,sup,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,bullist,numlist,separator,outdent,indent,separator,forecolor,backcolor,separator,styleprops,spacer,spacer,spacer,spacer,spacer,spacer,spacer,spacer,spacer,spacer,link,unlink,anchor,separator,image,separator,media",
		theme_advanced_buttons3 : (_toolbar_3 != undefined) ? _toolbar_3 : "",
		theme_advanced_toolbar_align : "center",
		theme_advanced_styles : (_css_styles != undefined) ? _css_styles : "&nbsp;",
		theme_advanced_blockformats : (_default_blockformats != undefined) ? _default_blockformats : "p,div,h1,h2,h3,h4,h5,h6,div,blockquote,dt,dd,code,samp",
		theme_advanced_path : "false",
		content_css : "/ecics/styles/styles.css",
		convert_fonts_to_spans : true,
		remove_linebreaks : false,
		convert_urls : false,
		dialog_type : "window",
		accessibility_warnings : true,
		custom_undo_redo_levels : 30,
		inline_styles : true,
		doctype : "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>",
		paste_create_paragraphs : false,
		paste_create_linebreaks : false,
		paste_use_dialog : false,
		paste_auto_cleanup_on_paste : true,
		paste_convert_middot_lists : false,
		paste_unindented_list_class : "unindentedList",
		paste_convert_headers_to_strong : true,
		init_instance_callback : (_init_instance_callback != undefined) ? _init_instance_callback : "",
		setupcontent_callback: "k_inherit_id_for_css",
		handle_event_callback : (_handle_event_callback != undefined) ? _handle_event_callback : "",
		file_browser_callback : "k_file_manager",
		//save_callback: "k_save_wysiwyg_back"
		noneditable_noneditable_class : "noneditable",
		extended_valid_elements : "div[id|class|style|title"
					+"|dir<ltr?rtl|lang|xml::lang|onclick|ondblclick|onmousedown"
					+"|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|onkeydown|onkeyup]" // anstatt -div 
	});
} 

function k_inherit_id_for_css (editor, body, doc) {	
	// copy the id of the div around tinymce area
	var _inherited_id = $(editor).parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.id;
	// as class to the body
	body.className = _inherited_id;
	//  and the iframe of the tinymce area
	$(editor).className = _inherited_id;
	return;
}

var k_src_field = null;
var k_src_window = null;

function k_file_manager (field_name, url, type, win) {
	// feld fuer url-rueckgabe merken
	k_src_field = field_name || null;
	k_src_window = win || window || null;
	// variable fuer auswahl der navi im template [a:filemanager;b:imagemanager;c:Sitemap;d:editor;e:textarea]
	var dlg_type = "";
	var loadurl = "";
	
	if (type == "file")
	{
		//win._showLinksManager();	
		dlg_type = "abc";
		if (url.substring(0,8) == "/images/")
			loadurl = "/system?action=image_helper_show_images&onlyprivate=true";
		else if (url.substring(0,11) == "/resources/")
			loadurl = "/system?action=resource_helper_show_resources&onlyprivate=true";
		else
			loadurl = "/website?action=show_pagelist&wsm_list_stylesheet=website_linkable_list&wsm_list_root=1&wsm_list_include_root=true";
			
		Shadowbox.open({
			title:      'Dateimanager',
			type:       'iframe',
			content:    loadurl+'&dlg_type='+dlg_type+'&current_url='+url,
			height:     1500,
			width:      900
		});
	}
	else if (type == "image")
	{
		//win._showImgManager();	
		dlg_type = "b";
		Shadowbox.open({
			title:      'Bildermanager',
			type:       'iframe',
			content:    '/system?action=image_helper_show_images&onlyprivate=true&dlg_type='+dlg_type+'&current_url='+url,
			height:     1500,
			width:      900
		});
	}
	else if (type == "media")
	{
		//win._showFilesManager();	
		dlg_type = "a";
		Shadowbox.open({
			title:      'Medienmanager',
			type:       'iframe',
			content:    '/system?action=resource_helper_show_resources&onlyprivate=true&dlg_type='+dlg_type,
			height:     1500,
			width:      900
		});
	}
}

// callback functions vom sdialog
function k_SetUrlImg (image_path, image_width, image_height, image_descr)
{
	if (k_src_window == null)
		k_src_window = window;
	if (k_src_field) {
		k_src_window.document.getElementById(k_src_field).value = image_path;
		if (k_src_window.document.getElementById("alt"))
			k_src_window.document.getElementById("alt").value = image_descr;
	}
	if (k_src_window.ImageDialog)
		k_src_window.ImageDialog.showPreviewImage(image_path);
	k_src_field = null;
	k_src_window = null;
}
function k_SetUrlFile (file_path, target)
{
	if (k_src_window == null)
		k_src_window = window;
	if (k_src_field) {
		k_src_window.document.getElementById(k_src_field).value = file_path;
	} 
	k_src_field = null;
	k_src_window = null;
}
function k_SetUrlLink (link_path, page_id)
{
	if (k_src_window == null)
		k_src_window = window;
	if (k_src_field) {
		k_src_window.document.getElementById(k_src_field).value = link_path;
	} 
	k_src_field = null;
	k_src_window = null;
}


function k_toggle_toolbars (selectedInstance)
{
	/*
	for (var i = 0; i < _wysiwyg_fields_dom_name.length; ++i)
	{
		if (tinyMCE.instances["mce_editor_" + i] == selectedInstance)
		{
			$("mce_editor_" + i + "_toolbar").style.display = "block";
		}
		else {
			if($("mce_editor_" + i + "_toolbar") != undefined)
			{
				$("mce_editor_" + i + "_toolbar").style.display = "none";
			}
		}
	}
	*/
}

var k_current_editor = null;
var k_current_xml_field = null;

function toggle_editor(id, xml_field)
{
	//alert("toggle_editor wurde aufgerufen! [" + id +"][" + xml_field +"]");

	// toolbar entfernen, wenn eine aktiv:
	var tinymce_ext_toolbar_placeholder = document.getElementById('tinymce_ext_toolbar_placeholder');
	if(tinymce_ext_toolbar_placeholder.firstChild != null)
	{
		tinymce_ext_toolbar_placeholder.removeChild(tinymce_ext_toolbar_placeholder.firstChild);
	}

	// wenn ein editor aktiv ist, den inhalt in das form-feld zurückspeichern und den editor entfernen:
	if (tinyMCE.getInstanceById(k_current_editor) != null)
	{
		//alert("Editor wird deaktiviert und value wird zurückgeschrieben!\n\n" +"[" + k_current_editor +"][" + k_current_xml_field +"]\n\n" + tinyMCE.activeEditor.getContent());
		$(k_current_xml_field).value = tinyMCE.activeEditor.getContent();
		//alert("Feld-Content hinterher:\n\n" + $(k_current_xml_field).value);
		tinyMCE.execCommand('mceRemoveControl', false, k_current_editor);
	}

	// das angegebene feld durch den editor ersetzten:
	if (id != null && tinyMCE.getInstanceById(id) == null)
	{
		//alert("Editor wird aktiviert!");
		tinyMCE.execCommand('mceAddControl', false, id);
	}

	// das aktuelle editor-feld und form-feld für nächten aufruf (und ende/speichern) merken:
	k_current_editor = id;
	k_current_xml_field = xml_field;
}

function toggle_html_editor(id, xml_field)
{
	var width = 500;
	var height = 400;
	var options = "scrollbars=no,resizable=no,status=no";
	F1 = window.open("/ecics/central/js/codeeditor.html","popup","width=" + width + ",height=" + height + ",left=" + ((screen.width - width) / 2) + ",top=" + ((screen.height - height) / 2) + "," + options);
	F1.focus();
	code = $(id).innerHTML;
	F1.setCode(code);
}

function k_count_chars (content, spaces )
{
	//alert("k_count_chars->content=" + content);
	
    content = content.replace(/<(.+?)>/g, '');//remove html
    content = content.replace(/(&nbsp;)+/g, ' ');//replace &nbsp; with space
    content = content.replace(/\s+/g, ' ');//replace multiple spaces
    content = content.replace(/&(.*?);/g, '1');//convert entities to single character
    var total = 0;
    if(!spaces)
    {
        content = content.replace( ' ', '', 'g' );
    }
    total = content.length;
    return total;	
}

function k_check_chars(content) {
	var k_content = null;
    if (content) {
        k_content = content;
    }
    else {
        if (tinyMCE.selectedInstance) { 
			if(status && status == 'online')
				return true;
            k_content = tinyMCE.selectedInstance.getBody().innerHTML;
        }
    }
   	if (k_content)
   	{    
    	var k_chars_spaces = k_count_chars( k_content, true );    
    	var k_max_chars = $("max_chars_in_articles").value;
    	if (k_chars_spaces > k_max_chars && k_max_chars != 0) {
     	   $("max_chars_warning_box").style.display = "block";
     	   $("too_much_chars").innerHTML = k_chars_spaces - k_max_chars;
     	   return false;
    	}	   
    	else {
    	   $("max_chars_warning_box").style.display = "none";
     	   return true;
    	}
    }
}

function k_check_chars_on_event(e) {
    if (e.type == 'keyup') {
        return k_check_chars();
    }
    return true;
}

function k_check_chars_on_save()
{
    if (tinyMCE.selectedInstance) { 
		if (tinyMCE.selectedInstance.destroyed == 1)
			var k_content = $(tinyMCE.activeEditor.id).innerHTML;
		else
        	var k_content = tinyMCE.selectedInstance.getBody().innerHTML;
        var k_chars_spaces = k_count_chars( k_content, true );    
        var k_max_chars = $("max_chars_in_articles").value;
        if (k_chars_spaces > k_max_chars && k_max_chars != 0) {
            return confirm('Ihr Text überschreitet die Grenze von ' + k_max_chars + ' Zeichen!\n\nBitte kürzen Sie Ihren Text um ' + (k_chars_spaces - k_max_chars) + ' Zeichen.\n\nWollen Sie den zu langen Text dennoch speichern?');       
        }
        return true;
    }
	return true;
}

function k_check_chars_on_startup(inst) {
    return k_check_chars();
}


// added saur 20070217, changed 20090622

var tt = null;
if (navigator.userAgent.toLowerCase().indexOf('msie 7') > -1) var isIE7 = true;

function k_showTT(id, opener) {
	var x = $(opener).offsetLeft;
	var y = $(opener).offsetTop;	
	tt = document.getElementById(id);
	tt.style.display = "block";
	tt.style.left = x + "px";
	tt.style.top 	= y + "px";	
}

function k_hideTT(e, id) {
	if (tt != null) {
		//var tt = document.getElementById(id);
		var mx = (document.all) ? window.event.x + document.body.scrollLeft : e.pageX;
		var my = (document.all) ? window.event.y + document.body.scrollTop  : e.pageY;
		var dt = tt.offsetTop;
		if (isIE7) dt = dt + 1;
		var dr = tt.offsetLeft + tt.offsetWidth;
		var db = tt.offsetTop + tt.offsetHeight;
		var dl = tt.offsetLeft;
		if (isIE7) dl = dl + 1;
		if ((mx <= dl || mx >= dr) || (my <= dt || my >= db)) {
			if (tt.id != id) document.getElementById(id).style.display = "none";
			tt.style.display = "none";
		}	
	}
}
// end saur
