
//*************************************************************************
// jQuery initialization
//*************************************************************************

// defined in html source
var servletRoot = '';
var noPng = false;

function goto(dest) {
	document.location = servletRoot+'?cmd=go&dest='+dest+'.html';
}

function page(dest) {
	document.location = servletRoot+'?cmd=go&page='+dest;
}

function action(dest) {
	document.location = servletRoot+'?cmd='+dest;
}

function markCurrent(id) {
	$(function() {
//	    $(id).css("background-color","#bfccd9;");
//	    $(id+' a').css("color","#000000");
		$(id).toggleClass("marked");
	});
}

function markChanged(id) {
	$(function() {
		$(id).toggleClass("changed");
	});
}

function replaceImage(cond,id,img) {
	$(function() {
		if($(cond).size() > 0) {
			//alert('replace '+id+' by '+img);
			$(id).attr('src',img);
		}
	});
}

function replaceImageSrc(id,img) {
	$(function() {
		$(id).attr('src',img);
	});
}

function loadcssfile(filename) {
	var fileref = document.createElement("link");
	fileref.setAttribute("rel", "stylesheet");
	fileref.setAttribute("type", "text/css");
	fileref.setAttribute("href", filename);
	document.getElementsByTagName("head")[0].appendChild(fileref);
}

function hasPngProblem() {
	var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
	var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);
	if (jQuery.browser.msie && (ie55 || ie6)) {
		return true;
	} else {
		return false;
	}
}

jQuery.fn.extend({
check: function() {
return this.each(function() {this.checked = true;});
},
uncheck: function() {
return this.each(function() {this.checked = false;});
}
});

function checkall(name) {
	$(name).check();
}

function uncheckall(name) {
	$(name).uncheck();
}

function deleteCallbackFunc(v,m) {
//	alert(v+' '+m.children("#link").val());
	if (v == true) {
		window.location.href = m.children("#link").val();
	}
}

function confirmDelete(name,link) {
	$.prompt('Wollen Sie '+name+' wirklich löschen? <input type="hidden" id="link" value="'+link+'">',
			{buttons: {Ja:true,Nein:false},
			 callback: deleteCallbackFunc,
			 prefix: 'rotary'});
}

function showPrompt(msg) {
	$.prompt(msg, {buttons: {Ok:true}, prefix: 'rotary'});
}

function schedulePrompt(msg) {
	$(function() {
		$.prompt(msg, {buttons: {Ok:true}, prefix: 'rotary'});
	});
}

function initToggler(selector,group) {
	$(function() {
	    $(selector).click(function(e){
	    	if (this.checked) {
		    	checkall(group);
		   	} else {
		    	uncheckall(group);
		   	}
	    });	
	});
}

function initTreeTable(map,parents) {
	$(function() {
    	var options = {
    		openImg: "../pictures/tv-collapsable.gif", 
    		shutImg: "../pictures/tv-expandable.gif", 
    		leafImg: "../pictures/tv-item.gif", 
    		lastOpenImg: "../pictures/tv-collapsable-last.gif", 
    		lastShutImg: "../pictures/tv-expandable-last.gif", 
    		lastLeafImg: "../pictures/tv-item-last.gif", 
    		vertLineImg: "../pictures/vertline.gif", 
    		blankImg: "../pictures/blank.gif", 
    		collapse: parents, 
    		column: 0, 
    		striped: false, 
    		highlight: false
//    		onselect: function(target){alert("You clicked "+target.html());}
    	};
    	$("#treetable").jqTreeTable(map, options);
	});
}

function initGallery(first) {
	$(function() {
		$('.gallery_unstyled').addClass('gallery'); // adds new class name to maintain degradability
		
		$('ul.gallery').galleria({
			history   : true, // activates the history object for bookmarking, back-button etc.
			clickNext : true, // helper for making the image clickable
			insert    : '#main_image', // the containing selector for our main image
			onImage   : function(image,caption,thumb) { // let's add some image effects for demonstration purposes
				
				// fade in the image & caption
				if(! ($.browser.mozilla && navigator.appVersion.indexOf("Win")!=-1) ) { // FF/Win fades large images terribly slow
					image.css('display','none').fadeIn(1000);
				}
				caption.css('display','none').fadeIn(1000);
				
				// fetch the thumbnail container
				var _li = thumb.parents('li');
				
				// fade out inactive thumbnail
				_li.siblings().children('img.selected').fadeTo(500,0.3);
				
				// fade in active thumbnail
				thumb.fadeTo('fast',1).addClass('selected');
				
				// add a title for the clickable image
				image.attr('title','Nächstes Bild >>');
			},
			onThumb : function(thumb) { // thumbnail effects goes here
				
				// fetch the thumbnail container
				var _li = thumb.parents('li');
				
				// if thumbnail is active, fade all the way.
				var _fadeTo = _li.is('.active') ? '1' : '0.3';
				
				// fade in the thumbnail when finnished loading
				thumb.css({display:'none',opacity:_fadeTo}).fadeIn(1500);
				
				// hover effects
				thumb.hover(
					function() { thumb.fadeTo('fast',1); },
					function() { _li.not('.active').children('img').fadeTo('fast',0.3); } // don't fade out if the parent is active
				)
			}
		});
		$.galleria.activate(first);
	});
}

function initMenu() {
	$(function() {
	    $(".menu,.submenu").bind("mouseover mouseout", function(e){
	    	$(this).toggleClass("over");
	    });
	    $("#main").click(function(){goto("main");});
	    $("#leitbild").click(function(){goto("leitbild");});
	    $("#vorstand").click(function(){action("listOfficers");});
	    $("#kommissionen").click(function(){action("listWorkGroups");});
	    $("#persons").click(function(){action("listPersons");});
	    $("#events").click(function(){action("showEvents");});
	    $("#clublokal").click(function(){goto("clublokal");});
	    $("#projects").click(function(){action("showProjects");});
	    $("#contact").click(function(){action("contact");});
	    $("#officialtopics").click(function(){action("listOfficialTopics");});
	    $("#links").click(function(){goto("links");});
	    $("#login").click(function(){goto("login");});
	    $("#editevents").click(function(){action("listEvents_V");});
	    $("#bulletin").click(function(){action("listBulletins_V");});
	    $("#editprojects").click(function(){action("listProjects_V");});
	    $("#topics").click(function(){action("listTopics_V");});
	    $("#editpersons").click(function(){action("listPersons_V");});
	    $("#memo").click(function(){action("memo_V");});
	    $("#config").click(function(){action("listConfigurations_V");});
	    $("#editpages").click(function(){action("listPages_V");});
	    $("#sql").click(function(){action("sql_V");});
	    $("#logout").click(function(){action("logout");});
		//$("#scrollpane").jScrollPane({scrollbarWidth:20, scrollbarMargin:10});
		if ($("#bulletinliste").size() > 0) {
			markCurrent("#bulletin");
		}
	});
}
function initMailTabs() {
	$(function() {
	    $(".tabunselected").bind("mouseover", function(e){
	    	$(this).css("background-color","#5883B2");
	    	$(this).css("color","#ffffff");
	    });
	    $(".tabunselected").bind("mouseout", function(e){
	    	$(this).css("background-color","#bfccd9");
	    	$(this).css("color","#000000");
	    });
	    $("#emailtab").click(function(){action("memo_V");});
	    $("#smstab").click(function(){action("sms_V");});
	    $("#showemailtab").click(function(){action("showMails_V");});
	    $("#groupstab").click(function(){action("listGroups_V");});
	    $("#memberstab").click(function(){action("listPersons_V");});
	    $("#configtab").click(function(){action("listConfigurations_V");});
	    $("#pagestab").click(function(){action("listPages_V");});
	    $("#filestab").click(function(){action("listUploaded_V");});
	});
}

function initGoodies() {
	$(function() {
	    $("button.rcbutton,a.rcbutton").bind("mouseover", function(e){
	    	$(this).css("background-color","#325276");
	    	$(this).css("color","#ffffff");
	    });
	    $("button.rcbutton,a.rcbutton").bind("mouseout", function(e){
	    	$(this).css("background-color","#bfccd9");
	    	$(this).css("color","#000000");
	    });
		$(".multi-file").MultiFile({
			STRING: {
				remove: "<B>L&ouml;schen</B>",
				selected: "Ausgewählt: $file",
				denied: "Unerlaubte Dateiendung $ext",
				duplicate: "Die Datei wurde bereits gewählt:\n$file"
			}
		});
		$(".tooltip").tooltip({
			delay: 0,
			showURL: false
		});
		$("div.toggler-1").toggleElements();
	});
}

function initialize () {
	initMenu();
	initGoodies();
}

//*************************************************************************
// tinyMCE support
//*************************************************************************

function initSimpleEditor(css,ids) {
	tinyMCE.init({
		theme : "advanced",
		skin : "o2k7",
//		skin_variant : "silver",
		mode : "exact",
		elements: ids,
		language : "de",
		content_css : css,
		plugins : "paste",
		theme_advanced_buttons1 : "bold,italic,underline,justifyleft,justifycenter,justifyright,justifyfull,undo,redo",
		theme_advanced_buttons2 : "bullist,numlist,outdent,indent,pastetext,pasteword,link,unlink,code",
		theme_advanced_buttons3 : "",
		theme_advanced_toolbar_location : "bottom",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "none",
		extended_valid_elements : "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]",
		plugin_insertdate_dateFormat : "%d.%m.%Y",
		plugin_insertdate_timeFormat : "%H:%M:%S",
		paste_use_dialog : false
	});
}

function initSimpleEditorWide(css,ids) {
	tinyMCE.init({
		theme : "advanced",
		skin : "o2k7",
//		skin_variant : "silver",
		mode : "exact",
		elements: ids,
		language : "de",
		content_css : css,
		plugins : "paste",
		theme_advanced_buttons1 : "bold,italic,underline,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,outdent,indent,undo,redo,pastetext,pasteword,link,unlink,code",
		theme_advanced_buttons2 : "",
		theme_advanced_buttons3 : "",
		theme_advanced_toolbar_location : "bottom",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "none",
		extended_valid_elements : "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]",
		plugin_insertdate_dateFormat : "%d.%m.%Y",
		plugin_insertdate_timeFormat : "%H:%M:%S",
		paste_use_dialog : false
	});
}

function initAdvancedEditor(css,ids) {
	tinyMCE.init({
		theme : "advanced",
		skin : "o2k7",
//		skin_variant : "silver",
		mode : "exact",
		elements: ids,
		language : "de",
		content_css : css,
		
		plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
	
		// Theme options
		theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,outdent,indent,|,styleselect,formatselect,fontselect,fontsizeselect",
		theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,undo,redo,|,blockquote,|,link,unlink,anchor,image,|,forecolor,backcolor,|,hr,sub,sup,charmap,|,cleanup,code,|,preview,|,fullscreen",
		theme_advanced_buttons3 : "tablecontrols,|,insertlayer,moveforward,movebackward,absolute,|,styleprops,|,del,ins,attribs,|,nonbreaking",
		theme_advanced_buttons4 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		plugin_insertdate_dateFormat : "%d.%m.%Y",
		plugin_insertdate_timeFormat : "%H:%M:%S",
		extended_valid_elements : "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]",
//		theme_advanced_link_targets : "_something=My somthing;_something2=My somthing2;_something3=My somthing3;",
//		external_link_list_url : "example_data/example_link_list.js",
//		external_image_list_url : "example_data/example_image_list.js",
//		flash_external_list_url : "example_data/example_flash_list.js",
//		template_external_list_url : "example_data/example_template_list.js",
		theme_advanced_resize_horizontal : false,
		theme_advanced_resizing : true,
		apply_source_formatting : true,
		spellchecker_languages : "+English=en,Danish=da,Dutch=nl,Finnish=fi,French=fr,German=de,Italian=it,Polish=pl,Portuguese=pt,Spanish=es,Swedish=sv",
		file_browser_callback : "fileBrowserCallBack",
		paste_use_dialog : false
	});
}

function initAdvancedEditor2(css,ids) {
	tinyMCE.init({
		theme : "advanced",
		skin : "o2k7",
//		skin_variant : "silver",
		mode : "exact",
		elements: ids,
		language : "de",
		content_css : css,
		plugins : "safari,spellchecker,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,pagebreak,imagemanager,filemanager",
		theme_advanced_buttons1_add_before : "save,newdocument,separator",
		theme_advanced_buttons1_add : "fontselect,fontsizeselect",
		theme_advanced_buttons2_add : "separator,insertdate,inserttime,preview,separator,forecolor,backcolor",
		theme_advanced_buttons2_add_before: "cut,copy,paste,pastetext,pasteword,separator,search,replace,separator",
		theme_advanced_buttons3_add_before : "tablecontrols,separator",
		theme_advanced_buttons3_add : "emotions,iespell,media,advhr,separator,print,separator,ltr,rtl,separator,fullscreen",
		theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,spellchecker,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		plugin_insertdate_dateFormat : "%d.%m.%Y",
		plugin_insertdate_timeFormat : "%H:%M:%S",
		extended_valid_elements : "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]",
		theme_advanced_link_targets : "_something=My somthing;_something2=My somthing2;_something3=My somthing3;",
		external_link_list_url : "example_data/example_link_list.js",
		external_image_list_url : "example_data/example_image_list.js",
		flash_external_list_url : "example_data/example_flash_list.js",
		template_external_list_url : "example_data/example_template_list.js",
		theme_advanced_resize_horizontal : false,
		theme_advanced_resizing : true,
		apply_source_formatting : true,
		spellchecker_languages : "+English=en,Danish=da,Dutch=nl,Finnish=fi,French=fr,German=de,Italian=it,Polish=pl,Portuguese=pt,Spanish=es,Swedish=sv",
		file_browser_callback : "fileBrowserCallBack",
		paste_use_dialog : false
	});
}

function fileBrowserCallBack(field_name, url, type, win) {
	var connector = "../../../filemanager/browser.html?Connector=connectors/php/connector.php";
	var enableAutoTypeSelection = true;
	
	var cType;
	tinyfck_field = field_name;
	tinyfck = win;
	
	switch (type) {
		case "image":
			cType = "Image";
			break;
		case "flash":
			cType = "Flash";
			break;
		case "file":
			cType = "File";
			break;
	}
	
	if (enableAutoTypeSelection && cType) {
		connector += "&Type=" + cType;
	}
	
	window.open(connector, "tinyfck", "modal,width=600,height=400");
}

//*************************************************************************
// form validation
//*************************************************************************

function badEmail(data) {
	if(data.length > 0) {
		var PosAt = data.indexOf( "@" );
		var PosDot = data.indexOf( ".", PosAt );
		if(!( PosAt > 0 && PosDot > PosAt) ) {
			return true;
		} else {
			return false;
		}
	}
}

function checkEmail( data, flag ) {
	if( flag || data.length > 0 ) {
		var PosAt = data.indexOf( "@" );
		var PosDot = data.indexOf( ".", PosAt );
		if(!( PosAt > 0 && PosDot > PosAt) ) {
			alert("Bitte geben Sie eine korrekte Email-Adresse ein.");
			emailOK = false;
		}
		else {
			emailOK = true;
		}
	}
}

function badDate(data) {
	var posDay = data.indexOf( "." );
	var posMonth = data.indexOf( ".", posDay+1 );
	var day = parseInt( data.substring( 0, posDay ),10 );
	var month = parseInt( data.substring( posDay+1, posMonth ),10 );
	var year = parseInt( data.substring( posMonth+1, data.length ),10 );
	
	if( isNaN(day) || isNaN(month) || isNaN(year) ||
	(year < 0) || day < 1 || day > 31 || month < 1 || month > 12 ) {
		return true;
	}
	else {
		return false;
	}
}

function checkDate( data, flag ) {
	var posDay = data.indexOf( "." );
	var posMonth = data.indexOf( ".", posDay+1 );
	var day = parseInt( data.substring( 0, posDay ) );
	var month = parseInt( data.substring( posDay+1, posMonth ) );
//	var year = parseInt( data.substring( posMonth+1, data.length ) );
	
	if( (data.length < 6 && flag) || day < 1 || day > 31 || month < 1 || month > 12 ) {
		alert("Bitte geben Sie ein korrektes Datum ein.");
		emailOK = false;
	}
	else {
		emailOK = true;
	}
}

function checkEnforced( data, text ) {
	if( data.length < 1 ) {
		alert( "Das Feld " + text + " darf nicht leer sein." );
		emailOK = false;
	}
	else {
		emailOK = true;
	}
}

function checkOK(name) {
	if( emailOK ) {
		document.forms[name].submit();
	}
	else {
		alert("Bitte überprüfen Sie Ihre Angaben nochmals...");
		emailOK = false;
	}
}

function checkForm(name) {
	var msg = "";
	var sep = "";
	var list = "";
	var i = 0;
	var j = 0;

	for(i=0; i<neededVars.length/2; i++) {
		for(j=0; j<document.forms[name].elements.length; j++) {
			if (document.forms[name].elements[j].name == neededVars[i*2] &&
		    	document.forms[name].elements[j].value == "") {
				if (list == "") {
					sep = "";
				} else {
					sep =",";
				}
				list = list+sep+neededVars[i*2+1];
			}
		}
	}
	if (list != "") {
		msg = msg+"\nBitte geben Sie folgende Felder ein:\n"+list;
	} else {
		for(i=0; i<dateVars.length/2; i++) {
			for(j=0; j<document.forms[name].elements.length; j++) {
				if (document.forms[name].elements[j].name == dateVars[i*2] &&
			    	document.forms[name].elements[j].value != "" &&
				badDate(document.forms[name].elements[j].value)) {
					if (list == "") {
						sep = "";
					} else {
						sep =",";
					}
					list = list+sep+dateVars[i*2+1];
				}
			}
		}
		if (list != "") {
			msg = msg+"\nBitte geben Sie in den folgenden \nFeldern ein korrektes Datum ein:\n"+list;
		} else {
			for(i=0; i<emailVars.length/2; i++) {
				for(j=0; j<document.forms[name].elements.length; j++) {
					if (document.forms[name].elements[j].name == emailVars[i*2] &&
				    	document.forms[name].elements[j].value != "" &&
					badEmail(document.forms[name].elements[j].value)) {
						if (list == "") {
							sep = "";
						} else {
							sep =",";
						}
						list = list+sep+emailVars[i*2+1];
					}
				}
			}
			if (list != "") {
				msg = msg+"\nBitte geben Sie in den folgenden \nFeldern eine korrekte Email-Adresse ein:\n"+list;
			}
		}
	}

	if (msg == "") {
		return true;
	} else {
//		alert(msg);
		$.prompt(msg, {buttons: {OK:true}, prefix: 'rotary'});
		return false;
	}
}
