function odtBindToolbar( nr, url ){
	$(document).bind('keydown', 'ctrl+' + nr, function(){
	  location.href = url;
	  return false; 
	});
	$(':input').bind('keydown', 'ctrl+' + nr, function(){
	  location.href = url;
	  return false; 
	});
}
	
function odtSetHelpText( aText ){
      document.getElementById( "odtHelpContext" ).innerHTML = aText;
}
var odtDebuggerConsoleInstalled = false;
function odtDebugLog( text ){
	if( !odtDebuggerConsoleInstalled ){
		odtDebuggerConsoleInstalled = true;
		$('#odtform').append( '<div id="odtDebuggerConsole"></div>' );
	}
	$('#odtDebuggerConsole').append( text + '<br>');
}
/*
function odtHasFocus( elem ){
	// warning: doesnt work in ie8 with table-cells
	if( document.activeElement )
		odtDebugLog( 'ae ' + document.activeElement + ' ' + document.activeElement.id );
	if( elem )
		odtDebugLog( 'e ' + elem + ' ' + elem.id );
	if( elem == null ){
		odtDebugLog( '! elem is null' );
		return false;
	}
	if( document.activeElement == null ){
		odtDebugLog( '! ae null' );
		return false;
	}
	if( elem == document.activeElement ){
		odtDebugLog( ' e = ae' );
		return true;
	}
	if( elem.id == document.activeElement.id ){
		odtDebugLog( ' id' );
		return true;
	}
	odtDebugLog( 'other' );
	return false;
}
*/
function odtGetViewportSize(){
    var myWidth = 0, myHeight = 0;	 
    if( typeof( window.innerWidth ) == 'number' ) {
        // Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        // IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        // IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }
    return { width: myWidth, height: myHeight };
}
function odtGetViewportScrollposition() {
    var scrOfX = 0, scrOfY = 0;	 
    if( typeof( window.pageYOffset ) == 'number' ) {
        // Netscape compliant
        scrOfY = window.pageYOffset;
        scrOfX = window.pageXOffset;
    } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
        // DOM compliant
        scrOfY = document.body.scrollTop;
        scrOfX = document.body.scrollLeft;
    } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
        // IE6 standards compliant mode
        scrOfY = document.documentElement.scrollTop;
        scrOfX = document.documentElement.scrollLeft;
    }
    return { x: scrOfX, y: scrOfY };
}
function odtEnsureVisible( elem ){
	var pos = elem.offset();
	var viewY = odtGetViewportScrollposition().y;
	var viewH = odtGetViewportSize().height;
	// odtDebugLog( 'scr: ' + pos.top + ' w ' + viewY + ' ' + viewH );
	pos.top -= viewY;
	viewH -= 24; // lineHeight 
	while( pos.top < 10 ){
		window.scrollBy( 0, -80 );
		pos.top += 80;
	}
	while( pos.top > viewH - 10 ){
		window.scrollBy( 0, +80 );
		pos.top -= 80;
	}
}

function odtCallServer( aUrl, aCallbackHandler ){
	//odtDebugLog( "callServer " + aUrl );
    if( window.XMLHttpRequest ){
      r = new XMLHttpRequest();
    } else {
      r = new ActiveXObject( "Microsoft.XMLHTTP" );
    }
    r.onreadystatechange = aCallbackHandler;
    r.open( "get", aUrl, true );
    r.send( null );
    return r;
}
function odtAddKeyUpListener( field, listener ){
	field.onkeyup = listener;
	if( (document.layers) ? true : false ){
		// fuer nicht-ie
		field.captureEvents( Event.KEYUP );
	}
}
function odtAddKeyDownListener( field, listener ){
	field.onkeydown = listener;
	if( (document.layers) ? true : false ){
		// fuer nicht-ie
		field.captureEvents( Event.KEYDOWN );
	}
}
function odtGetKeycodeFromEvent( e ){
	ev = (e) ? e : (window.event) ? window.event : null;
	if( ev ){
		keyCode = (ev.charCode) ? ev.charCode:
			( (ev.keyCode) ? ev.keyCode : ((ev.which) ? ev.which : null ) );
		return keyCode;
	} else {
		return 0;
	}
}

var odtSfId = null;
var odtSfCall = null;
function odtSfOnGetFocus( id ){
	if( odtSfId != null ){
		odtSfOnDispose( id );
	}
	odtSfId = id;
}
function odtSfOnLostFocus( id ){
}
function odtSfOnSflLostFocus( id ){
	odtSfOnDispose( id );
	var tf = document.getElementById( id + 'TF' );
	tf.focus();
}

function odtSfOnDispose( id ){
	odtSfCall = null;
	odtSfId = null;
	var lf = document.getElementById( id + 'LF' );
	if( lf != null ){
		lf.innerHTML = "";
		var idf = document.getElementById( id + 'ID' );
		if( idf.value == '0' ){
			odtSfDelete( id );
		}
	}
}
function odtSfIsNull(){
	var idf = document.getElementById( odtSfId + 'ID' );
	if( idf.value == '0' ){
		return true;
	} else {
		return false;
	}
}
function odtSfDelete( id ){
	var tf = document.getElementById( id + 'TF' );
	tf.value = '';
	var idf = document.getElementById( id + 'ID' );
	idf.value = '0';
}
function odtSfSflKeyDownListener( e ){
	var keyCode = odtGetKeycodeFromEvent( e );
	if( odtSfIsNull() ){
		if( keyCode == 13 ){
			// Return
			odtSfSelect( odtSfId );
			return false;
		}
	}
	return true;
}
function odtSfKeyDownListener( e ){
	var keyCode = odtGetKeycodeFromEvent( e );
	if( odtSfIsNull() ){
		if( keyCode == 13 ){
			// Return
			odtSfSelect( odtSfId );
			return false;
		}
	} else {
		if( ( 65 <= keyCode ) && ( keyCode <= 90 ) ){
			// a bis z
			odtSfDelete( odtSfId );
		} else if( ( 48 <= keyCode ) && ( keyCode <= 57 ) ){
			// 0 bis 9
			odtSfDelete( odtSfId );
		} else if( keyCode == 188 ){
			// ,
			odtSfDelete( odtSfId );
		} else if( keyCode == 46 || keyCode == 8 ){
			// Delete or Back
			odtSfDelete( odtSfId );
		}
	}
	return true;
}
function odtSfKeyUpListener( e ){
	var keyCode = odtGetKeycodeFromEvent( e );
	if( odtSfIsNull() ){
		if( keyCode == 40 ){
			// Down
	    	var sfl = document.getElementById( odtSfId + 'SFL' );
	    	if( sfl.selectedIndex +1 < sfl.length ){
				sfl.selectedIndex = sfl.selectedIndex +1;
			} else {
				sfl.selectedIndex = 0;
			}
		} else if( keyCode == 38 ){
			// Up
	    	var sfl = document.getElementById( odtSfId + 'SFL' );
	    	if( 0 < sfl.selectedIndex ){ 
				sfl.selectedIndex = sfl.selectedIndex -1;
			} else {
				sfl.selectedIndex = sfl.length-1;
			}
		} else {
			odtSfSearch( odtSfId, false );
		}
	} else {
	}
}

var odtSfSearchIndex = 0;
function odtSfSearch( id, force ){
	if( odtSfCall != null ){
		//odtDebugLog( "sfSearch cancels" );
		odtSfCall.abort();
		odtSfCall = null;
	}
	var tf = document.getElementById( id + 'TF' );
	if( tf.value.length < 1 ){
		if( !force )return;
	}
	var url = "SelectField?ViewId=" + escape( document.forms[0].ViewId.value );
	url = url + "&FieldId=" + escape( id );
	url = url + "&Filter=" + escape( tf.value );
	odtSfSearchIndex++;
	url = url + "&SearchIndex=" + escape( odtSfSearchIndex );
	odtSfCall = odtCallServer( url, odtSfCallback );
}
function odtSfCallback(){
	if( odtSfCall == null )return;
	if( odtSfCall.readyState == 4 ){
		 odtSfFillLF( odtSfCall.responseText );
		 odtSfCall = null;
	}    	
}
function odtSfFillLF( viStr ){
	//odtDebugLog( "sfFillLF " + viStr );
	var id = odtSfId;
	var lf = document.getElementById( id + 'LF' );
	var vi = eval( "(" + viStr + ")" );
	if( vi.length < 2 ){
		lf.innerHTML = "";
		return;
	}
	var result = '<select name="' + id + 'SFL" id="' + id + 'SFL" size="' + ( vi.length / 2 ) + '"';
	result = result + ' style="width:100%" ondblclick="odtSfOnDblClick( \'' + id + '\');"';
	result = result + ' onblur="odtSfOnSflLostFocus( \'' + id + '\' );">';
	for( i = 0; i < vi.length; i += 2 ){
		result = result + '<option value="' + vi[i] + '">' + vi[i+1] + '</option>';
	}
	result = result + '</select>';
	lf.innerHTML = result;
	var sfl = document.getElementById( id + 'SFL' );
	odtAddKeyDownListener( sfl, odtSfSflKeyDownListener );
}	
function odtSfSelect( id ){
	var sfl = document.getElementById( id + 'SFL' );
	if( sfl == null )return;
	if( sfl.selectedIndex < 0 )return;
	var idf = document.getElementById( id + 'ID' );
	idf.value = sfl.options[ sfl.selectedIndex ].value;
	var tf = document.getElementById( id + 'TF' );
	tf.value = sfl.options[ sfl.selectedIndex ].text;
	var lf = document.getElementById( id + 'LF' );
	lf.innerHTML = "";
	tf.focus();
}
function odtSfOnDblClick( id ){
	odtSfSelect( id );
}
function odtSfAutoselect( id, sfurl, searchtext ){
	$.getJSON( 
		sfurl + '&term=' + searchtext,
		function(data) {
			if( data.length == 1 ){
				var item = data[0];
				$( '#' + id + 'ID' ).val( item.id );
				$( '#' + id + 'TF' ).val( item.label );
			}
	  	}
	);	
}
function odtSfInit( id ){
	var sfurl = "SelectField?ViewId=" + escape( document.forms[0].ViewId.value );
	sfurl = sfurl + "&FieldId=" + escape( id );
	odtSfSearchIndex++;
	sfurl = sfurl + "&SearchIndex=" + escape( odtSfSearchIndex );
	$( '#' + id + 'TF' ).autocomplete({
		minLength: 0,
		source: sfurl,
		focus: function( event, ui ) {
			$( '#' + id ).val( ui.item.label );
			return false;
		},
		select: function( event, ui ) {
			$( '#' + id + 'TF' ).val( ui.item.label );
			$( '#' + id + 'ID' ).val( ui.item.id );
			return false;
		},
		change: function( event, ui ){
			if( ui.item == null ){
				if( $(this).val() != '' ){
					var text = $(this).val();
					$( '#' + id + 'TF' ).val( '' );
					$( '#' + id + 'ID' ).val( '0' );
					odtSfAutoselect( id, sfurl, text );
					// var t = 'changed: ' + $(this).val();
					// $( '#' + id + 'TF' ).val( t  );
					// var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
					// valid = false;
					// select.children( "option" ).each(function() {
					// if ( $( this ).text().match( matcher ) ) {
					// this.selected = valid = true;
					// return false;
					// }
					// });
				} else {		
					$( '#' + id + 'TF' ).val( '' );
					$( '#' + id + 'ID' ).val( '0' );
				}
			}
		}
	});
}


function odtSfDlgSelect(){
	$('#' + odtSfId + 'ID' ).val( $('#odtSfDlgList').val() );
	$('#' + odtSfId + 'TF' ).val( $('#odtSfDlgList :selected').text() );
	$('#odtSfDialog').dialog("close"); 
};
function odtSfDlgSearch( queryIndex ){
	//$('#odtSfDlgList').append( "<option value='33'>Text " + $('#odtSfDlgSearchTF').val() + "</option>" );
	//var url = odtSfGetURL( odtSfId, $('#odtSfDlgSearchTF').val() );
	odtSfSearchIndex++;
	
	$.get( "SelectField", { 
			ViewId: escape( document.forms[0].ViewId.value ),
			FieldId: escape( odtSfId ),
			QueryIndex: queryIndex,
			Filter:  $('#odtSfDlgSearchTF').val(),
			SearchIndex: escape( odtSfSearchIndex )
		},
		function(data){
			$('#odtSfDlgList').empty(); 
			var vi = eval( "(" + data + ")" );
			if( vi.length < 2 ){
				return;
			}
			for( i = 0; i < vi.length; i += 2 ){
				$('#odtSfDlgList').append( "<option value='" + vi[i] + "'>" + vi[i+1] + "</option>" );
				if( i == 0 ){
					$('#odtSfDlgList').focus();
				}
			}
		}
	);			
};
function odtSfShowDlg( id, queries ){
	odtSfOnGetFocus( id );
	$('#odtSfDlgSearchTF').val('');
	$('#odtSfDlgList').empty();
	$('#odtSfDialog').remove();
	var html = 'Suchen nach: <input type="text" name="odtSfDlgSearchTF" id="odtSfDlgSearchTF"/><a href="#" tabindex="-1" onclick="odtSfDlgSearch(0);" ><img src="img/selsrch.jpg"></a><br>';
	for( var q = 0; q < queries.length; q++ ){
		var query = queries[ q ];
		//html = html + query.Title + ' suchen  --- ';
		// name="Text 1" 
		html = html + '<input type="button" value="' + query.Title + ' suchen" onclick="odtSfDlgSearch('+q+');"> ';
	}
	html = html + '<br><select id="odtSfDlgList" size=30 ondblclick="odtSfDlgSelect();" style="height:400px;width:100%;"></select>';
	var htmlDlg = $( '<div id="odtSfDialog" title="Auswahl"/>' ).html( html );
	htmlDlg.dialog({
		autoOpen: false,
		modal: true,
		width: 600,
		buttons: {
			"Ok": function() {
				odtSfDlgSelect(); 
			}, 
			"Abbrechen": function() { 
				$(this).dialog("close"); 
			}						
		}
	});
	odtSfDlgSearch(0); 
	$('#odtSfDialog').dialog('open');
	
	$('#odtSfDlgSearchTF').keyup(function(e) {
    	if(e.keyCode == 13) {
    		odtSfDlgSearch(0);
    	}
    });			
    $('#odtSfDlgList').keyup(function(e) {
    	if(e.keyCode == 13) {
    		odtSfDlgSelect();
    	}
    });
}
function odtSfButton( id ){
	$.ajax({
		type: 'get',
		url: 'Ajaxer',
		data: 'ViewId=' + escape( document.forms[0].ViewId.value ) + '&CompId=' + id + '&GetAddQueries',
		dataType: 'json',
		success: function( respdata ){
			if( respdata.OK == 'ok' ){
				odtSfShowDlg( id, respdata.Queries );
	  		} else {
	    		alert('Fehler: unexpected result\n' + respdata );
	  		}
		},
		error: function( respdata ){ 
	  		alert('Fehler:\n' + respdata.responseText );
		}
	});
}

function OLDodtSfDlgInit(){
	$('#odtSfDialog').dialog({
		autoOpen: false,
			modal: true,
		width: 600,
		buttons: {
			"Ok": function() {
				odtSfDlgSelect(); 
			}, 
			"Abbrechen": function() { 
				$(this).dialog("close"); 
			}						
		}
	});
	$('#odtSfDlgSearchTF').keyup(function(e) {
    	if(e.keyCode == 13) {
    		odtSfDlgSearch(0);
    	}
    });			
    $('#odtSfDlgList').keyup(function(e) {
    	if(e.keyCode == 13) {
    		odtSfDlgSelect();
    	}
    });				

}
function odtSetCaretToEnd( fieldId ){
    	var target = document.getElementById( fieldId );
	pos = target.value.length;
	target.focus();
	if (target.setSelectionRange) //DOM
		target.setSelectionRange(pos, pos);
	else if (target.createTextRange) { //IE
		var range = target.createTextRange();
		range.collapse(true);
		range.moveEnd('character', pos);
		range.moveStart('character', pos);
		range.select();
	}
}

function odtInsertJnlpLink(parameter, name){
  var javawsInstalled = 0;
  var isIE = false;
  if( navigator.mimeTypes && navigator.mimeTypes.length ){
    if( navigator.mimeTypes['application/x-java-jnlp-file'])
      javawsInstalled = 1;
  }
  document.write( '<a href="Jnlp?GetJnlp=' + escape( location.href ) + '&' + parameter+'">' + name + '</a>' );
  if (javawsInstalled) {
  } else {
    // document.write( 'Ihr Browser schein kein Java Web Start zu unterstuetzen. Bitte wenden Sie sich an Ihren Administrator oder installieren Sie eine aktuelle Java-Version.');
  }
}

