//--- session heelp alive functions
jQuery.executeEach = function (seconds, fn) {
    var scope = {
        stop: function () {    clearTimeout(this.timer); },
        timer: setInterval(function () { fn(scope);    } , seconds)
    };
};
jQuery.prototype.disable = function () {
	if(this.hasClass('disabled'))return;
	this.addClass('disabled');
	if(this.attr("href")){
		this.attr("_href", this.attr("href"));
		this.attr("href", "javascript:");
	}
}
jQuery.prototype.enable = function () {
	if(!this.hasClass('disabled'))return;
	this.removeClass('disabled');
	if(this.attr("href")){
		this.attr("href", this.attr("_href"));
		this.removeAttr("_href");
	}
}


//--- sesssion keep alive things
var session_keepalive_inverval = 15 * 60 * 1000; //--- 15 minutes
var session_keepalive_counter = 0;
function session_keepalive() {
	$('#session_keepalive_image').each(function() {
		$(this).attr('src', basehref+'online/session_keepalive.comp?sid='+_session_id+'&forumid='+forumid+'&counter=' + session_keepalive_counter + '&rand=' + Math.random());
		setTimeout("session_keepalive()", session_keepalive_inverval);
	});
}
$(function() { setTimeout("session_keepalive()", session_keepalive_inverval); } );


//--- some layer magick
function toggleElements(mainelementid,attribute, value){
	
	var elements = $('#'+mainelementid+'['+attribute+'="'+value+'"]');
	elements.each(function() {
		$(this).toggle();
  	});
}

function toggleElement(layerid){
	$('#'+layerid).toggle();
}

function showhideLayer(layerId, show, movehorizontal, movevertical){
	var l = $('#'+layerId);
	if (show) {
		l.css("display", "block");
	} else {
		l.css("display", "none");
	}
}

//--- generic old and not that old FCS popups.
function popup(url) {window.open(basehref+url, '', 'width=350,height=350,menubar=no,scrollbars=yes,toolbars=no')}
function popup_fixed(url, name, w, h) { window.open(basehref+url, name, 'width='+w+',height='+h+',menubar=no,scrollbars=yes,toolbars=no')}
function factwindow(url) { window.open(basehref+url, "online", "height=400,width=350,directories=no,location=no,menubar=no,resizeable=yes,status=no,toolbar=no,scrollbars=yes"); }
function popsuche(url){ window.open(basehref+url,"suchergebnis_e1","width=770,height=500,menubar=no,scrollbars=yes,location=no,toolbars=no"); }
function bla() { popsuche('search/search.htm?forumid=' + forumid + '&string='+document.bl.string.value) }

var FACTTEXTLOADED = 0;

//--- language translation thing
function pmtr(wo) {
	window.open(basehref+'multilanguage/textlabel.htm?label='+wo+'&forumid='+forumid, 'labels', 'width='+550+',height='+450+',menubar=no,scrollbars=yes,toolbars=no');
	return false;
}

//--- cache images needed for the translations?
var tZr91 = new Image(); tZr91.src = basehref + 'images/translationinterfacebutton.gif';
var tZr92 = new Image(); tZr92.src = basehref + 'images/translationinterfacebutton_done.gif';
var tZr93 = new Image(); tZr93.src = basehref + 'images/translationinterfacebutton_missing.gif';

//--- the delete popup
function delete_popup(delete_eidie) {
	delete_URL = "facts/edit/delete.htm?"+delete_eidie;	
	window.open(basehref+delete_URL, "delete_window", "height=180,width=300,directories=no, location=no,resizeable=no,status=no,toolbar=no,scrollbars=no,menubar=no");
}

//--- e-mail magick
if (knillimae) {
	$(document).ready(function(){
		
		$('a').each(function(index){
			if(this.className == 'knillimae'){
				var content = this.innerHTML;
				content = content.replace(/^\[(.+?)\]at\[(.+?)\]dot\[(.+?)\]$/i, '$1@$2.$3');
				this.innerHTML = content;
				this.href = 'mai' + 'lt' + 'o:' + content;
				this.title = 'mai' + 'lt' + 'o:' + content;
			}
		})	
	});

};

//--- read statistics goodies
function readstats_switchtab(contentdiv, id, v) {
	if (!v || v == null) {
		v = 0;
	}

	var firsttab = $('#'+contentdiv + '_tab_all');
	var allopentabs = $('td.rs_tab_next_open');

	if (v == 0) {
		firsttab.attr('class','rs_tab_first_open');
	} else {
		firsttab.attr('class','rs_tab_first');
		var newversiontab = $('#'+contentdiv + '_tab_' + v);
		if (newversiontab) {
			newversiontab.attr('class','rs_tab_next_open');
		}
	}
	allopentabs.each(function(index){
		if(this.id.match(contentdiv)){
			$(this).attr('class', 'rs_tab_next');
		}
	});
	
	$('#'+contentdiv).html('<div style="padding-left: 10px; padding-right: 10px; text-align: center;">&nbsp;<br><img src="/images/loading.gif" width=32 height=32 alt="" border=0><br>&nbsp;</div>');

	
	var req = $.get(basehref + "lib/reads_getcontent.comp", { forumid:forumid, id:id, v:v, ajax:1, contentdivid:contentdiv }, function(data){
		$('#'+contentdiv).html(data);
	});
	
	//var req = new Ajax.Request(basehref + "lib/reads_getcontent.comp", {
	//		method:'get',
	//		parameters: { forumid:forumid, id:id, v:v, ajax:1, contentdivid:contentdiv },
	//		
	//	    onComplete: function(transport){	
	//			text = transport.responseText;
	//			$(contentdiv).update(text);
	//	    },
	//	    onFailure: function() { 
	//			$(contentdiv).update('Could not complete ajax request');
	//		}
	//	  });
	return;
}

function readstats_viewusers(contentdiv, id, v) {
	if (!v || v == null) {
		v = 0;
	}

	var divtoupdate = $('#'+contentdiv + '_userlist');

	if (divtoupdate.html() == '' || divtoupdate.html() == null) {
		divtoupdate.html('<div style="padding-left: 10px; padding-right: 10px; text-align: center;">&nbsp;<br><img src="/images/loading.gif" width=32 height=32 alt="" border=0><br>&nbsp;</div>').show();
		
		var req = $.get(basehref + "lib/reads_getcontent.comp", { forumid:forumid, id:id, v:v, ajax:1, viewusers:1, contentdivid:contentdiv }, function(data){
			divtoupdate.html(data);
		});
		
		//var req = new Ajax.Request(basehref + "lib/reads_getcontent.comp", {
		//	method:'get',
		///	parameters: { forumid:forumid, id:id, v:v, ajax:1, viewusers:1, contentdivid:contentdiv },
//
		//	onComplete: function(transport){	
		//		text = transport.responseText;
		//		divtoupdate.update(text);
		//	},
		//		onFailure: function() { 
		//		divtoupdate.update('Could not complete ajax request');
		//	}
		//});
	} else {
		divtoupdate.html('').hide();
	}
	return;
}

function readstats_show(contentdiv, id, v) {
	var divtoupdate = $('#'+contentdiv + '_top');

	if (divtoupdate.html() == '' || divtoupdate.html() == null) {
		divtoupdate.html('<div style="padding-left: 10px; padding-right: 10px; text-align: center; width: 560px;">&nbsp;<br><img src="/images/loading.gif" width=32 height=32 alt="" border=0><br>&nbsp;</div>').show();

		var req = $.get(basehref + "lib/reads.comp", { forumid:forumid, id:id, v:v, ajax:1, contentdivid:contentdiv, isincluded:0 }, function(data){
			divtoupdate.html(data);
		});
		
		
		
		//var req = new Ajax.Request(basehref + "lib/reads.comp", {
		//	method: 'get',
		//	parameters: { forumid:forumid, id:id, v:v, ajax:1, contentdivid:contentdiv, isincluded:0 },
//
		//	onComplete: function(transport){	
		//		text = transport.responseText;
		//		divtoupdate.update(text);
		//	},
		//	onFailure: function() { 
		//		divtoupdate.update('Could not complete ajax request');
		//	}
		//});
	} else {
		divtoupdate.html('').hide();
	}
	return;
}


//---------------------------------------------------------------------
function showReferersFull(id, v) {
	var contentdiv = $('#facttagstargets_' + id + '_' + v);
	if (contentdiv.length > 0) {
		contentdiv.html('<div style="padding-left: 10px; padding-right: 10px; border: 1px solid #EEEEEE; text-align: center; width: 560px;">&nbsp;<br><img src="/images/loading.gif" width=32 height=32 alt="" border=0><br>&nbsp;</div>');
		$.get(basehref + "lib/show_facttagstargets.comp", { forumid:forumid, id:id, v:v, all:1, useajax:1 }, function(data) {
			contentdiv.html(data);
		});
	}
}


function open_myunpuiblishedversions_more(linkage) {
	$('#myunpuiblishedversions_more').show();
	$('#myunpuiblishedversions_morelink').hide();
}


function qanda_switchsearchform() {
	$('#qanda_searchdiv').toggle();
	$('#qanda_searchbutton_search').toggle();
	$('#qanda_searchbutton_filter').toggle();

	$('#qanda_gobutton').attr('value',($('qanda_searchdiv').is(':visible') ? "Search" : "Filter"));
	if ($('#qanda_searchdiv').is(':visible')) {
		$('#filterform *[name="keyword"]').attr('value','');
		categoryselector.resetForm();
	}
}

function qanda_resetsearchform() {
	categoryselector.resetForm();
	$('#filterform *[name="keyword"]').val('');
	$('#filterform *[name="keyword"]').val('questiondate_desc');
	$('#filterform *[name="keyword"]').val('');
	$('#filterform *[name="keyword"]').val('');	
}


//--- permissions selectors functions
function changeSame(obj){
	var cClass = obj.className;
	//alert(cClass);
	$('.' + cClass).each(function(){
		if(this.id == obj.id){
			this.checked = obj.checked;
		}
	});
}


//--- default permissionsis inside the folder forms
function show_folderdefaultpermissions(onoroff, id, v) {
	var container = $('#folderdefaultpermissions');
	if (onoroff == 1) {
		if (container.html() == '' || container.html() == null) {
			$.get(basehref + "edit/form2/permissions.comp", {forumid:forumid, parent_id:id, parent_v:v, prefix:"fdp", doctype:"factfolder", nomandatory:1, ajax:1}, function(data){
				container.html(data).show();
			});
		} else {
			container.show();
		}
	} else {
		container.hide();
	}
}

//--- current permissions (info box), open all
function currentpermissions_showall(c) {
	$('.' + c).each(function(){
		$(this).show();
	});
	
	$('.' + c + '_link').each(function(){
		$(this).hide();
	});
	
}

//--- europass temporary javascript
var epcv_formopen = false;
function epcv_editelement(id, v, element, divtouse, formcontrolname, displaycontrolname, a, goforit) {
	if (epcv_formopen) {
		alert('Please close the other open forms to contine.');
		return;
	}
	
	if (!goforit) {
		$('#'+divtouse).html('<div style="padding-left: 10px; padding-right: 10px; text-align: center;">&nbsp;<br><img src="/images/loading.gif" width=32 height=32 alt="" border=0><br>&nbsp;</div>');
		checkSession('epcv_editelement(\''+id+'\', \''+v+'\', \''+element+'\', \''+divtouse+'\', \''+formcontrolname+'\', \''+displaycontrolname+'\', \''+a+'\', 1)', false);
		return;
	} else {

	}

	epcv_formopen = true;
	
	$.get(basehref + "europasscv/forms/" + formcontrolname + ".comp", {forumid:forumid, id:id, v:v, element:element, divtouse:divtouse, formcontrolname:formcontrolname, displaycontrolname:displaycontrolname, a:a, ajax:1}, function(data){
		$('#'+divtouse).html(data);
		if (tinyMCE && simpleTinyMceOptions) { 
				var nodes = $A(cdiv.getElementsByTagName('textarea')).map(Element.extend);

				$('#'+divtouse).find('textarea').each(function(index){
					if(this.className == 'simpletinymce' && this.id){
						if(!tinyMCE.get(this.id)){
							tinyMCE.execCommand('mceAddControl', false, this.id);
						}
					}
				});
			}
	});

	var req = $.get(basehref + "europasscv/forms/" + formcontrolname + ".comp", { forumid:forumid, id:id, v:v, element:element, divtouse:divtouse, formcontrolname:formcontrolname, displaycontrolname:displaycontrolname, a:a, ajax:1 }, function(data){
			$('#'+divtouse).html(data);
	});
}
function epcv_moveelement(id, v, element, divtouse, formcontrolname, displaycontrolname, a) {
	var cdiv = $("#"+divtouse);
	cdiv.html('<div style="padding-left: 10px; padding-right: 10px; text-align: center;">&nbsp;<br><img src="/images/loading.gif" width=32 height=32 alt="" border=0><br>&nbsp;</div>');

	$.get(basehref + "europasscv/actions/" + formcontrolname + ".comp",{ forumid:forumid, id:id, v:v, element:element, divtouse:divtouse, formcontrolname:formcontrolname, displaycontrolname:displaycontrolname, a:a, ajax:1 }, function(data){
		$.get(basehref + "europasscv/display/" + displaycontrolname + ".comp", { forumid:forumid, id:id, v:v, element:element, ajax:1 }, function(data){
			cdiv.html(data);
			$('#epcv_mustpublishdiv').show();
			$('#epcv_uptodate').hide();
		});
	});
	
}

function epcv_cacel_editelement(id, v, element, divtouse, displaycontrolname, goforit) {
	epcv_formopen = false;
	var cdiv = $('#'+divtouse);

	if (!goforit) {
		createOverlay(cdiv);
		checkSession('epcv_cacel_editelement(\''+id+'\', \''+v+'\', \''+element+'\', \''+divtouse+'\', \''+displaycontrolname+'\', 1)', false);
		return false;
	}

	// remove tinymce here!!!!
	if (tinyMCE && simpleTinyMceOptions) { 
		cdiv.find('textarea').each(function(index){
			if (this.className == 'simpletinymce' && this.id) {
				if (tinyMCE.get(this.id)) {
					tinyMCE.execCommand('mceRemoveControl', false, this.id);
				}
			}
		});
		
	}
	$.get(basehref + "europasscv/display/" + displaycontrolname + ".comp", {forumid:forumid, id:id, v:v, element:element, ajax:1}, function(data){
		cdiv.html(data);
	});
}

function fileuploadread(newid, title) {
	document.simplegroupform.factID.value = newid;
	if (!document.simplegroupform.title.value) {
		document.simplegroupform.title.value = title;
	}
	epcv_submit(document.simplegroupform, true, true);
}

function epcv_submit(form, ignorefileuplaod, goforit) {
	if (typeof(form) != 'object') { eval( 'form = document.' + form ); }

	var formcontrolname = form.formcontrolname.value;
	var displaycontrolname = form.displaycontrolname.value;
	var cdiv = $('#'+form.divtouse.value);
	var displaydiv = form.divtodisplay && form.divtodisplay.value ? $('#'+form.divtodisplay.value) : $('#'+form.divtouse.value);

	if (!goforit) {
		createOverlay(cdiv);
		checkSession('epcv_submit(\'' + $(form).attr("name") + '\', ' + ignorefileuplaod + ', 1)', false);
		return false;
	} else {

	}

	var elements = form.elements;
	var pairs = new Array();

	var params = {};
	params['ajax'] = 1;
	
	$(elements).each(function(index){
		if (this.className == 'simpletinymce' && this.id) {
			params[this.name] = tinyMCE.get(this.id).getContent();
			if (simpleTinyMceOptions && this.id && tinyMCE.get(this.id)) tinyMCE.execCommand('mceRemoveControl', false, this.id);
		}
		
		if(this.type == 'checkbox'){
			if(this.checked){
				params[this.name] = this.value;
			}
		} else if (this.type == 'radio'){
			if(this.checked){
				params[this.name] = this.value;
			}
		} else {
			params[this.name] = this.value;
		}
		
		
		
	});
	

	if (params['fileref'] && !ignorefileuplaod) {
		//--- file upload form
		var containerdiv = $(form).parent();
		containerdiv = $(containerdiv);
		var overlaydiv = containerdiv.children()[0];

		$(overlaydiv).css( { width: $(containerdiv).width()+'px', height: $(containerdiv).height()+'px' } ).show();

		form.target = 'fileuploadiframe';
		form.submit();
		return false;
	}
	
	$.post(form.action, params, function(data){
		var reslogin = data.match(/<mustloginfirst\/>/i);
		if (reslogin && reslogin[0]) {
			window.top.location.reload();
			return;
		}
		var res = text.match(/<error>(.+)<\/error>/i);
		if(res && res[0]){
			epcv_formopen = true;
			params['ajax'] = 1;
			params['error'] = res[0];
			$.get(basehref + "europasscv/forms/" + formcontrolname + ".comp", params, function(data){
				cdiv.html(data);
				if (tinyMCE && simpleTinyMceOptions) { tinyMCE.init(simpleTinyMceOptions); }
			});
		} else {
			epcv_formopen = false;
			params['ajax'] = 1;
			$.get(basehref + "europasscv/display/" + displaycontrolname + ".comp", params, function(data){
				displaydiv.html(data);
				$('#epcv_mustpublishdiv').show();
				$('#epcv_uptodate').hide();
				$.get(basehref + "europasscv/lib/exportform.comp", { 'forumid': forumid, 'id': params['id'], 'ajax': 1 }, function(data){
					$('#epcv_exportformdiv').html(data);
				});
			});
		}
	});
		 
	return false;
}
function epcv_specialhover(element, onoroff) {
	var e = $('#'+element);
	var t = e.parent().parent().parent();
	var nodes = $A(t.getElementsByTagName('td')).map(Element.extend);
	t.find('td.right').css({backgroundColor: onoroff ? '#EEEEEE' : 'transparent' });
}
function epcv_checkimageform(form) {
	if (form.image.value) {
		var res = form.image.value.match(/\.(jpg|jpeg|png|gif|bmp)$/i);
		if (!res) {
			alert('Please select a valid image (jpg/png/gif)!');
			return false;
		}
	} else {
		alert('Please select an image file!');
		return false;
	}
	return true;
}
function epcv_showexportmore(onoroff) {
	if (onoroff) {
		$('#epcv_exportmore').show();
	} else {
		$('#epcv_exportmore').hide();
	}
}


function _dump(arr,level) {
	var dumped_text = "";
	if (!level) level = 0;
	if (level > 0) return;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += _dump(value, level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}


function createOverlay(parentelementid) {
	parentelement = $('#'+parentelementid);
	parentelement.css({'position':'relative'});

	var overlay = $('<div></div>')
	.css({position:'absolute', top:0, left:0, width:$('#'.parentelement).width(), height:$('#'.parentelement).height(), opacity:0.7, filter:'alpha(opacity=70)', 'text-align':'center', 'background-color':'#FFFFFF'})
	.appendTo(parentelement);

	var loadingImg = $('<img>').css({width:32, height:32, border:0, 'margin-top':10, 'margin-left':'auto', 'margin-right':'auto'}).attr('src',"/images/loading.gif").attr('alt',"Loading...").appendTo(overlay);
	return overlay; 
}

var createshortfcutargs;
function modal_createshortcut(forumid, folderid, folderv, referer, title) {
	createshortfcutargs = {
		'forumid' : forumid,
		'parent_id' : folderid,
		'parent_v' : folderv,
		'directcreate' : 1,
		'referer' : escape(referer)
	};
	var url = basehref + "editor/factlink.htm?forumid=" + forumid + '&type=custom&successcallback=modal_createshortcut_result&parent_id='+folderid+'&parent_v='+folderv+'&directcreate=1&referer='+escape(referer)+'&clearbody=1';
	$('<div style="width: 820px; height: 400px;"><iframe src="' + url + '" style="border: 0px; padding: 0px; margin: 0px; width: 820px; height: 400px;" frameborder="0" framespacing="0" border="0"></iframe></div>').appendTo($('body')).dialog(
		{
			width:			842, 
			height:			'auto',
			modal:			true,
			closable:		true,
			resizable:		false,
			title:			title
		}
	);
//	});
}

function modal_createshortcut_result(id) {
	create_body_loadingoverlay();

	var res = id.match(/^(\d+)\.(\d+)$/);
	if (res && res[1]) {
		createshortfcutargs['targetfactid'] = res[1];
		createshortfcutargs['targetfactversionid'] = res[2];
	} else {
		return false;
	}

	var url = '/structure/edit/add_shortcut_form.comp?' + jQuery.param(createshortfcutargs);
	window.location = url;
}


function modalLoginSubmit(dowhat){
	
}

var modalLogin = {
	dowhat : null,
	init : function (dowhat) {
		this.dowhat = dowhat;
		this.openForm();
	},
	openForm : function () {
		closeAllWindows();
		if (typeof window.form2_preparetopreview == 'function') {
			form2_preparetopreview(0);
		}
		//------------------------------
	  	var url = basehref + "login/modallogin.htm?forumid=" + forumid;
		$.get(url, function(data){
			$('<div class="fcsdialog" id="modallogin"></div>').html(data).appendTo(document).dialog(
				{
					modal:			true,
					closeable:		false,
					resizable:		false,
					width :			'600',
					height : 		'350'
					
				}
			);
		});

	},
	submitForm : function () {
		var params = {};
		$('.modallogin-field').each(function(){
			params[this.name] = this.value;
		});
	
		$.post($('.modallogin-form').attr('action'), params, function(data){
			//alert(data.match(/loginsuccess/gi));
			if(data.match(/loginerror/gi)){
				$('#loginerrormsg').html('Sorry, wrong login-data. Please try again or register.');
			} else if (data.match(/loginsuccess/gi)) {				
				$('.fcsdialog').dialog("close");
				eval(modalLogin.dowhat);
			} else {
				$('#loginerrormsg').html('Unknown error.');
			}
			return;
		});
		return;
	}

}


$(function(){
	$('.components').hide();
	HeaderSearchForm.init();
	prevNext.init();
	$('.section-display-shortcuts').hover(function(){
		$(this).toggleClass('section-display-shortcuts-hover row-shade-color-hover');
	});
	initCalendars();
	SearchForm.init();
	$('#loginform-input-username').select().focus();
});
function initCalendars(){
   $( ".datepicker" ).datepicker({ dateFormat: 'yy-mm-dd', changeMonth: true, changeYear: true });
}
var HeaderSearchForm = {
	init : function () {
		$( "#searchformheader_submit").addClass("ui-state-default ui-corner-all").find("span").addClass("ui-icon ui-icon-search");
		$("#searchform-header-dropdown-typeselector").toggle(
		  function () {
			$("#searchformheader_type").show();
		  },
		  function () {
			$("#searchformheader_type").hide();
		  }
		);
		$("#searchformheader_type li a").click(function(){
			$("#searchform-header-dropdown-typeselector #label").html($(this).html());
			$("#search-form-header-showonly").val(this.id);
		});
		$('#searchformheader_submit').click(function(){
			document.getElementById('searchformheader').submit();
		});

		
	}
}
var prevNext = {
	init: function () {
		$("#prevnext-container").find(".toggle").hide();
		$("#prevnext-container").find(".openclosebutton").toggle(
			function(){
				$(this).removeClass("icon-14-boxopen").addClass("icon-14-boxclose");
				$("#prevnext-container").find(".toggle").show();
			},
			function(){
				$(this).removeClass("icon-14-boxclose").addClass("icon-14-boxopen");
				$("#prevnext-container").find(".toggle").hide();
			}
		);
	}
}

var Autocomplete = {

	init : function (obj, existingid, existingv) {
		$(obj).autocomplete({
			source: function (request, response) {
				var url =  basehref + "lib/autocomplete.comp";
				$.get(url, {forumid: forumid, fieldid: $(obj).attr("id"), input: request.term, existingid:existingid, existingv:existingv}, function(data){
					var results = [];
					$(data).find('rs').each(function(){
						if($(this).attr('id') && $(this).text()){
							results.push({ value: $(this).text(), id:$(this).attr('id'), label: $(this).text(), info:$(this).attr('info'), usgrid:$(this).attr('usgrid') });
						} else {
							results.push($(this).text());
						}
					});
					
					response(results);
				});
			},

			focus: function() {
				// prevent value inserted on focus
//				if (!this.id.match(/^usersearch_(.+?)$/i)) {
//					return false;
//				}
			},

			select: function( event, ui ) {	
				var re_tagging = this.id.match(/^tagselectsearch_(.+?)_(.+?)$/i);
				if (re_tagging && ui.item.id && parseInt(ui.item.id) == ui.item.id) {
					$.post(basehref + 'structure/edit/add_shortcut_form.comp',{ forumid:forumid, ajax:1, parent_id:ui.item.id, parent_v:1, targetfactid:re_tagging[1], targetfactversionid:0 }, function(data) {
						$(this).val('').focus();
						updateTagsDisplayDiv(re_tagging[1], re_tagging[2]);
					});
				}

				var re_usersearch = this.id.match(/^usersearch_(.+?)$/i);
				if (re_usersearch && ui.item.id) {
					stf_ajaxselect(ui.item.usgrid);
				}

				if ((this.id == 'tagselectsearch' || this.id == 'wl_tag') && ui.item.id && parseInt(ui.item.id) == ui.item.id) {
					var terms = Autocomplete.split( this.value );
					// remove the current input
					terms.pop();
					// add the selected item
					terms.push( ui.item.value );
					// add placeholder to get the comma-and-space at the end
					terms.push( "" );
					this.value = terms.join( ", " );
				}

				return false;
			}
		});
	},

	split: function (val) {
		return val.split( /,\s*/ );
	},

	convertVersionString: function (versionString){
		var r = versionString.split('.');
		return parseInt(r[0])*100000 + parseInt(r[1])*1000 + parseInt(r[2]);
	}
}

//---- tage inputs related functions
function tag_ajaxselect_search_direct(tagtitle, fieldname) {
	var currentVal = $('input[name='+fieldname+']').val();

	if (currentVal.indexOf(",") > -1) {
		currentVal = currentVal.replace(/,[^,]+$/gi, ', ' + tagtitle);
	} else {
		currentVal = tagtitle;
	}

	$('input[name='+fieldname+']').val(currentVal + ', ');
}

var SearchForm = {
	/*
	search-keyword		    onchange="if(this.value.length){document.searchform.nokeyword.value=0}else{document.searchform.nokeyword.value=1}"
	search-factype
	tagselectsearch
	search-searchin
	search-fromdate
	search-todate
	search-myfactsonly
	search-onlyread
	search-publishedonly
	search-saveme
	lang-selector
	*/

	init : function () {
		$('#search-keyword, #tagselectsearch, #search-fromdate, #search-todate')
			.focus(function(){
				if($(this).val() == $(this).attr('initialvalue')){
					$(this).val('').removeClass('search-form-labels');
				}
			})
			.blur(function(){
				if($.trim($(this).val()) == ''){
					$(this).val($(this).attr('initialvalue')).addClass('search-form-labels');
				}
			})
			.each(function(){
				if($(this).val() == $(this).attr('initialValue')){
					$(this).addClass('search-form-labels');
				}
				//$(this).attr('initialValue', $(this).val());
			});
	},
	checkBeforeSubmit : function (formID) {
		$('#search-keyword, #tagselectsearch, #search-fromdate, #search-todate').each(function(){
			if($(this).val() == $(this).attr('initialvalue')){
				$(this).val('');
			}
		});
		$('#'+formID).submit();
	}
}
function delete_myeditform (forumid,formuid) {
	if(confirm("Are you sure you would like to delete the selected form?")){
		$.ajax({
			url			: basehref + 'edit/forms3/actions/delformrecord.comp',
			type		: 'POST',
			data		: {formuid:formuid, forumid:forumid},
			success		: function(responseContent) {
				if (responseContent.match(/<ok\/>/)){
					window.location.reload();
				} else {
					alert("There was an error deleting this form");
				}	
			},
			error		: function() { alert("error"); }
		});
	}
}



function create_body_loadingoverlay() {
	$('<div style="position: absolute; top: 0px; left: 0px; width: 100%; height: 100%; line-height: 100%; text-align: center; z-index: 20000; background-color: #FFFFFF;"><img src="/images/loading.gif" alt="" border="0" style="vertical-align: middle; margin: auto;"></div>').css({ opacity: 0, height: $('body').height(), width: $('body').width()}).find('img').css({ 'margin-top': parseInt($('body').height() / 2) }).end().appendTo($('body')).animate({ opacity: 0.8 });
}



function grouplist_checkbox_click(check) {
	var res = $(check).attr('id').match(/g(\d+)_(.)/i);
	if (res && res[2] == 'w') {
		$('#g'+res[1]+'_r').attr('checked', $(check).attr('checked'));
		$('#g'+res[1]+'_p').attr('checked', $(check).attr('checked'));
		$('#g'+res[1]+'_x').attr('checked', $(check).attr('checked'));
	}
	if (res && res[2] == 'p') {
		$('#g'+res[1]+'_x').attr('checked', $(check).attr('checked'));
		$('#g'+res[1]+'_r').attr('checked', $(check).attr('checked'));
	}
	if (res && res[2] == 'x') {
		$('#g'+res[1]+'_r').attr('checked', $(check).attr('checked'));
	}
}


//---- section edit javascripts
$(document).ready(function () {
	$('.se_std').add('.se_unpub').mouseenter(function () {
		var me = $(this);
		me.data('oldclass', me.attr('class')).attr('class', 'se_over').find('.se_controls').first().fadeIn();
	}).mouseleave(function () {
		var me = $(this);
		me.attr('class', me.data('oldclass')).find('.se_controls').first().fadeOut();
	});
});



function inArray (wanted, list) {
	for(var i = 0; i < list.length; i++){
		//alert(wanted+','+list[i]);
		if (wanted == list[i]) {
			return 1;
		}
	}
	return 0;
}


//---- FCS lists javascripts
function disable (objid) {
	$('#'+objid + 'imglink').disable();
	$('#'+objid + 'link').disable();
	$('#'+objid).disable();
}
function enable (objid) {
	$('#'+objid).enable();
	$('#'+objid + 'link').enable();
	$('#'+objid + 'imglink').enable();
	
}
function showactionhint(who) {
	$('#'+who + 'div').show();
}
function hideactionhint(who) {
	$('#'+who + 'div').hide();
}
function returnnull () {}
function formSubmit(objid){
	$('#actioninput').attr("name", objid);
	$('#actioninput').attr("value",objid);
	
	var oldactionform =	document.publishform.action;
	if (objid == 'zip') {
		document.publishform.action = basehref + 'fsDownload/filesdownload.zip?forumid=' + forumid + '&downloadaszip=1';
	}
	if (objid == 'report') {
		document.publishform.action = basehref + 'structure/generatereport.comp?forumid=' + forumid + '';
	}
	document.publishform.submit();
	if (objid == 'zip' || objid == 'report') {
		document.publishform.action = oldactionform;
	}
}
function check_buttons(){
	disable("publishall");
	var items = document.publishform.elements;
	var moreThanOneIsChecked = 0;
	var onlyfactlinks = 1;
	var unpublishedSelected = 0;
	var publishedSelected = 0;
	var rootsselected = 0;
	var allowChagePerm = 0;
	var allowDownloadAsZip = 1;
	var allowReport = 1;

	var creatableObjects = jQuery.parseJSON($('#fcs-creatable-objects').html());

	for (i=0; i<items.length; i++) {
		var field = items[i];
		if(field.name == 'ids'){
			if(field.checked){
				var fTitle = field.title;		
				var arrayTitle = fTitle.split('.');		
				var version = arrayTitle[1];
				var elementIDarray = field.id.split('-');	
				var elementName = elementIDarray[0];
				var realElementName = elementIDarray[1];
				var writePerm = elementIDarray[2];
				var isRoot = elementIDarray[3];
				//alert(isRoot);
				moreThanOneIsChecked ++;
				if(elementName!='factlink'){
					onlyfactlinks = 0;
				}
				
				if(writePerm){
					allowChagePerm = 1;
				} else {
					allowChagePerm = 0;
				}
				if(isRoot==1){
					allowChagePerm = 0;
				}
				if(realElementName=='commententry'){
					allowChagePerm = 0;
				}
				if(realElementName=='discussionentry'){
					allowChagePerm = 0;
				}
				if(realElementName!='factfsfile' && realElementName!='image'){
					allowDownloadAsZip = 0;
				}
				if(realElementName!='image'){
					allowReport = 0;
				}
				if(version && version > 100000){
					unpublishedSelected++;
				} else {
					publishedSelected++;
				}

				if(inArray(realElementName,creatableObjects) && writePerm){
					enable("editall"); 
				} else {
					disable("editall");
				}
				if (isRoot==1) rootsselected++;
			}
		}
	}
	
	if (moreThanOneIsChecked - rootsselected > 0) { 
		disable("add");
		disable("addfolder");
		disable("editme");
		disable("translateme");
		disable("deleteme");

		if (moreThanOneIsChecked != 1) disable("editall");
		if (unpublishedSelected > 0 && !publishedSelected) enable("publishall"); else disable("publishall");
		if (allowDownloadAsZip) enable("zip"); else disable("zip");
		if (allowReport) enable("report"); else disable("report");
		if (allowChagePerm) enable('changeperm'); else disable("changeperm");
		if (onlyfactlinks && moreThanOneIsChecked) enable("removeall"); else disable("removeall");

		enable("deleteall");
		enable("hideall");
		enable("moveto");
		enable("clone");
		enable("multishortcuts");
		enable("sendtoafriend");
	} else {
		enable("add");
		enable("addfolder");
		enable("editme");
		enable("translateme");
		enable("deleteme");

		disable("editall");
		disable("publishall");
		disable("zip");
		disable("report");
		disable("changeperm");
		disable("removeall");

		disable("deleteall");
		disable("hideall");
		disable("moveto");
		disable("clone");
		disable("multishortcuts");
		disable("sendtoafriend");
	}

	if (rootsselected) enable("removeall"); 
}
function checkAll(obj){
	$("input.actioncheckbox").attr("checked", obj.checked);
	check_buttons();
}


//************** all post requests for IE get connection close header with ajax *************************

$(function(){  
    $.ajaxSetup({
      beforeSend: function(request, options) {
        if(options.type == 'POST'){
        	request.setRequestHeader("Connection","close");
        }
      }
    }); 
});

