/*
 * LEXsoft Javascript-Bibliothek
*/
var font_size = 13;
var tooltip_manager =
{
  actualElement : null,
  actualElementPosX : null,
  actualElementPosY : null,
  div : null,
  overLinkElement : false,
  overDivElement : false,
  timer : null,
  isCalledHideDiv : null
}
/**
 * öffnet oder schliesst ein Clickopen-Menu (Sidebox)
 * @param string id des Menus
 */
function toggle_box( id, imgpath )
{
  if( imgpath == '' || imgpath == undefined )
    return true;

  if( document.getElementById( 'box_'+id ).className == 'click_open' )
  {
    document.getElementById( 'box_'+id ).className = 'click_close';
    document.getElementById( 'img_'+id ).src = imgpath + 'expand.gif';
    return false;
  }
  else
  {
    document.getElementById( 'box_'+id ).className = 'click_open';
    document.getElementById( 'img_'+id ).src = imgpath + 'collapse.gif';
    return false;
  }
}

// Layer einblenden
function show_layer( id ) {
  document.getElementById(id).style.display = "block";
}

// Layer ausblenden
function hide_layer( id ) {
  document.getElementById(id).style.display = "none";
}

// Layer ein- / ausblenden
function toggle_layer( id ) {
  str = document.getElementById(id).style.display;
  if (str == "") str = "none";
  if (str == "none") show_layer(id);
  else hide_layer(id);
}

function toggle_functions_box( id )
{
  var more = "mehr..";
  var less = "weniger..";
  var link = document.getElementById( 'link_' + id );
  var box = document.getElementById( 'linkbox_' + id );

  if( !link || !box ) {
    return false;
  }

  if( link.firstChild.data == more )
  {
    for( var child = box.firstChild;
          child != null;
          child = child.nextSibling )
    {
      if( child.className == 'moreless' )
      {
          child.firstChild.data = less;
          show_layer( 'box_' + id );
      }
    }
  }
  else if( link.firstChild.data == less )
  {
    for( var child = box.firstChild;
          child != null;
          child = child.nextSibling )
    {
      if( child.className == 'moreless' )
      {
          child.firstChild.data = more;
          hide_layer( 'box_' + id );
      }
    }
  }
}

function clear_loading()
{
    if( document.schnellsuche )
    {
        document.schnellsuche.searchTerm.className="";
    }
}

function toggle_loading( for_what )
{
  document.schnellsuche.searchTerm.className="loading_suche";
  return true;

  /*
  var obj       = document.getElementById('sandclock');
  var obj_label = document.getElementById('sandclock_label');
  var show_text = "Bearbeite...";
  if( !obj || !obj_label ) {
      return true;
  }
  obj.style.display = "block";

  if( meaning == "Suche" ) {
      show_text = "F&uuml;hre Suche aus...";
  } else if( meaning == "Dokument" ) {
      show_text = "Verarbeite das Dokument...";
  } else if( meaning == "Fliesstext" ) {
      show_text = "Verarbeite das Dokument f&uuml;r Flie&szlig;textdarstellung...";
  }
  obj_label.innerHTML = show_text;
  */
}

function change_font_size( action )
{
  change_factor = 1;
  if( action == "+" && font_size <= 17 )
  {
    font_size = font_size+change_factor;
  }
  else if( action == "-" )
  {
    font_size = font_size-change_factor;
  }
  else if( action == "1" )
  {
    font_size = 13;
  }

  document.body.style.fontSize = font_size+"px";
}

function cursor_sandclock_activate() {
  document.body.className="cursor_show_sandclock";
  return true;
}

function cursor_sandclock_deactivate() {
  document.body.className="cursor_hide_sandclock";
  return true;
}


/**
 * Ajax Autosuggestion Class
 *
 * @param String - uri we want to call
 * @param Hash - URI params
 */
function ajaxLoadAutoSuggestion( requestURI, paramsURI )
{
    this.jobID = ajaxAutosuggestionJobmanager.registerNewJob();

    // register values
    ajaxAutosuggestionJobmanager.setJobValue( this.jobID, 'uri', requestURI );
    ajaxAutosuggestionJobmanager.setJobValue( this.jobID, 'params', paramsURI );
}


/**
 * @global
 * @var Hash - manage the jobs
 */
var ajaxAutosuggestionJobmanager =
{
    /**
     * clone each object from job[0]
     */
    jobs:
    [ {
        controller: null,   // autosuggestion controller
        typeAhead: null,    // delete input field on empty result
        params: null,       // URI params (searchterm etc.)
        uri: null,          // URI
        sending: false,     // sending on progress?
        process: 1,         // current internal job-process number
        lastSearchterm: '', // hold last searchterm and avoid loading the same data twice
        registerNewProcess: function() { return ++this.process; },
        clone: function() // jobcloner
        {
            var target = {};
            for( var i in this )
            {
                target[i] = this[i]; // clone each value
            }
            return target;
        },
        getValue: function( key ){ return this[key] || false; },
        setValue: function( key, value ){  return this[key] = value; }
    } ],
    jobCounter: 0,
    /**
     * register a nwe job an increment the jobcounter
     */
    registerNewJob: function()
    {
        this.setJob(++this.jobCounter, this.getJob(0).clone() ); // copy the default job
        return this.jobCounter;
    },
    /**
     * get a specific job
     * @return Object - the job, on error return job[0]
     */
    getJob: function( job  ) { return this.jobs[job] || this.jobs[0]; },
    /**
     * set a specific job
     */
    setJob: function( jobID, job  ) { return this.jobs[jobID] = job; },
    /**
     * try to set a specific job value
     */
    setJobValue: function( job, key, value )
    {
        try        { return this.jobs[job][key] = value; }
        catch( e ) { return false; }
    },
    /**
     * try to get a specific job value
     */
    getJobValue: function( job, key )
    {
        try { return this.jobs[job][key]; }
        catch( e ) { return false; }
    }
}


/**
 * Die Funktion ruft sich solange selber auf bist der Inhalt des Input-Feldes
 * für eine festgelegt Zeit sich nicht veraendert.
 *
 * @param Object - Control-Object
 * @param Boolean - bTypeAhead
 * @param String - old Input-Value (set after the first call)
 * @param Integer - forced a specific job, needed for recursion
 * @param Integer - forced a spefific process, handle only the newest process
 */
ajaxLoadAutoSuggestion.prototype.requestSuggestions = function( oAutoSuggestControl, bTypeAhead, recursiveValue, forcedJobID, forcedProcessID )
{
    // in milliseconds => default: 0.5 seconds
    var timeToWait = 0.5 * 1000;

    var jobID = forcedJobID || this.jobID;

    if( !jobID || jobID <= 0  )
    {
        return false;
    }

    // register a new job on first call
    if( ajaxAutosuggestionJobmanager.getJobValue( jobID, 'process' ) == 1  )
    {
        ajaxAutosuggestionJobmanager.setJobValue( jobID, 'controller', oAutoSuggestControl );
        ajaxAutosuggestionJobmanager.setJobValue( jobID, 'typeAhead', bTypeAhead );
        ajaxAutosuggestionJobmanager.setJobValue( jobID, 'sending', false );
    }

    var processID = forcedProcessID || ajaxAutosuggestionJobmanager.getJobValue( jobID, 'process' );

    if( !processID || processID <= 0  )
    {
        return false;
    }

    // get current textbox value
    var sTextboxValue = ajaxAutosuggestionJobmanager.getJobValue( jobID, 'controller' ).textbox.value.toLowerCase();

    if( sTextboxValue != recursiveValue )
    { // new user input, call me again after a defined time
        var newProcessID = ajaxAutosuggestionJobmanager.getJob( jobID ).registerNewProcess();
        setTimeout(
            "ajaxLoadAutoSuggestion.prototype.requestSuggestions("
                + "null,"
                + "null,"
                + "'" + sTextboxValue + "',"
                + "'" + jobID + "',"
                + "'" + newProcessID + "')",
            timeToWait );
    }
    else if( sTextboxValue != ajaxAutosuggestionJobmanager.getJobValue( jobID, 'lastSearchterm' ) )
    { // for a new search a new searchstring is a must
        if( (processID >= ajaxAutosuggestionJobmanager.getJobValue( jobID, 'process' )) && !ajaxAutosuggestionJobmanager.getJobValue( jobID, 'sending' ) )
        { // only run the newest process
            ajaxAutosuggestionJobmanager.getJob( jobID )['params']['searchterm'] = sTextboxValue; // set searchterm
            ajaxAutosuggestionJobmanager.setJobValue( jobID, 'sending', true ); // block this job
            ajaxAutosuggestionJobmanager.setJobValue( jobID, 'lastSearchterm', sTextboxValue );

            Ajax.request( ajaxAutosuggestionJobmanager.getJobValue( jobID, 'uri' ), function( response )
            {
                var aSuggestions  = [];

                eval( 'tmpArray = ' + response.replace(/<!--.*-->/g, '') );

                for( var i in tmpArray )
                {
                    if( tmpArray[i].length > 0 )
                    {
                        aSuggestions.push(tmpArray[i]);
                    }
                }

                ajaxAutosuggestionJobmanager.getJob( jobID ).getValue( 'controller' ).autosuggest(aSuggestions, false);
                ajaxAutosuggestionJobmanager.setJobValue( jobID, 'sending', false ); // mark the job as ready
            }
            ,
            { parameters: ajaxAutosuggestionJobmanager.getJobValue( jobID, 'params'  ) } );
        }
    }
}

/**
 * Die Funktion fragt mit AJAX eine URI ab und erwartet von dieser die Werte fuer
 * die Selectionbox. Die Werte werden als normaler Text empfangen und mithilfe von eval()
 * geparst. Mit den Werten wird dann die mitgelieferte Selectionbox dynamisch gefüllt.
 *
 * @param HTML-Object - Die Selectionbox die gefuellt werden soll
 * @param String - Die URI die einen String zurueckliefern muss in der Form: "Value","Value","Value" usw.
 * @param Hash - GET Parameter Bsp.: { sessionId: 123456, searchterm: "blablub" }
 * @param String - Eintrag der selektiert werden soll (Optional)
 * @param String - Prefix der vor den Eintraegen stehen soll (Optional)
 */

function ajaxLoadSelectionbox( selectionbox, requestURI, params, selected, prefix )
{
    Ajax.request( requestURI, function( response )
    {
        prefix = prefix || '';

        eval( 'var tmpArray = ' + response.replace(/<!--.*-->/g, '') );

        var newOptions = {};
        var counter = 0;
        for( var i in tmpArray )
        {
            if( i.length > 0 ){ newOptions[i] = tmpArray[i]; counter++ }
        }

        // remove all existing options
        selectionbox.length = 1;

        if( counter <= 0 )
        {
            selectionbox.options[1] = new Option( "Keine vorhanden", "", true, true );
            selectionbox.disabled = true; // disable the selectionbox
            return;
        }

        // append new
        for( var i in newOptions )
        {
            selectionbox.options[selectionbox.length] =
                new Option( prefix + newOptions[i], i, false, ( i == selected ) );
        }

        // show selectionbox
        selectionbox.style.display = 'block';
        // enable selectionbox
        selectionbox.disabled = false;
    }
    ,
    { parameters: params } ); // included searchterm and so on
}

function decode_utf8(utftext)
{
var plaintext = ""; var i=0; var c=c1=c2=0;
// while-Schleife, weil einige Zeichen uebersprungen werden
while(i<utftext.length)
  {
  c = utftext.charCodeAt(i);
  if (c<128) {
    plaintext += String.fromCharCode(c); i++;}
  else if((c>191) && (c<224)) {
    c2 = utftext.charCodeAt(i+1);
    plaintext += String.fromCharCode(((c&31)<<6) | (c2&63));
    i+=2;}
  else {
    c2 = utftext.charCodeAt(i+1); c3 = utftext.charCodeAt(i+2);
    plaintext += String.fromCharCode(((c&15)<<12) | ((c2&63)<<6) | (c3&63));
    i+=3;}
  }
return plaintext;
}

jQuery(document).ready(function()
{
  var task = "";
  var array_xid = "";
  var document_url = window.location.href;
  var url_param_xid  = document_url.match(/xid=([0-9,]*)/);
  var url_param_task = document_url.match(/task=([a-z,0-9_]*)/);

  if( url_param_xid )
  {
    array_xid = url_param_xid[1].split(",");
  }

  if( url_param_task )
  {
    task = url_param_task[1];
  }

  if( url_param_xid && task != "chose_fliesstext" )
  {
    jQuery( "#link_zitierung_tooltip" ).tooltip("zitierungen_tooltip", "zitierung" );
    jQuery( "span.fnr" ).tooltip("fussnoten_tooltip", "fussnote" );

    if( array_xid[1] != "1" )
    {
      jQuery( 'a.doklink' ).tooltip("gesetze_tooltip", "gesetz" );
    }
  }
});

function text_zitierung (div_id) {
    var result = null;
    var searchString = window.location.href;
    var searchResult = searchString.match(/sessionID=([0-9]*).*xid=([0-9,]*)/);
    var sessionId = searchResult[1];
    var xid = searchResult[2];

    searchResult = searchString.match(/\S+[?]/);

    var url_start = searchResult[0];

    var func_response = function( response ){
        eval( response.replace(/<!--.*-->/g, '') );

        if ( hits_count > 5) {
            var showMaxDocument = 5;
        }
        else {
            var showMaxDocument = hits_count;
        }

        var text = "<strong>1 - "+showMaxDocument+"</strong> von <strong>" + hits_count +
                   "</strong><br/><br/>";
        for (i=0;i<zitierungen.length && i < 5;i++) {
          text +=
              (i+1) + ". " +
              "<a href="+url_start+"sessionID="+sessionId+"&amp;source=js_zitierung&amp;templateID=document&amp;xid="+zitierungen[i].xid+">"+zitierungen[i].title_short +  "</a><br/>";
        }

        jQuery( div_id ).html(text);
        jQuery( div_id ).fadeIn();
    }

    var request_values =
    {
        templateID: "ajax_load_zitierung_zu_document",
        activeSearchAdvFilter: "",
        xid: xid,
        expertSearch: "zitierung",
        sessionID: sessionId
    }

    return jQuery.get( get_server_address(searchString) , request_values, func_response );
}

 function text_zu_gesetz_abkuerzung (div_id) {

    var result = null;

    var searchString = tooltip_manager.actualElement.href;

    var searchResult = searchString.match(/sessionID=([0-9]*).*xid=([0-9,]*)/);

    var sessionId = searchResult[1]

    var xid = searchResult[2];

    searchResult = searchString.match(/\S+[?]/);
    var url_start = searchResult[0];

    var func_response = function( response ){
      /*eval( response.replace(/<!--.*-->/, '') );*/

      var zitierungen = response;

      var text ="<a href="+url_start+"sessionID="+sessionId+"&amp;source=js_law&amp;templateID=document&amp;xid="+xid+">"+zitierungen +  "</a><br/>";

      jQuery( div_id ).html(text);
      jQuery( div_id ).fadeIn();
    }

    var request_values =
    {
        templateID: "ajax_load_information_for_gesetz",
        activeSearchAdvFilter: "",
        xid: xid,
        sessionID: sessionId
    }

    return jQuery.get( get_server_address(searchString) , request_values, func_response );
}

(function(jQuery) {
  jQuery.fn.extend( {
    tooltip : function(div_id, text_type) {

      var shown = false;

      div_id = "#"+div_id;

      var div_id_cut = div_id.substring(1,div_id.length);

      if(!document.getElementById(div_id_cut)){
        insertElementIntoDOM("div",document.body,{id: div_id_cut, className: div_id_cut}, div_id_cut);
      }

      jQuery( this ).mouseover( function( e ){

        if( this != tooltip_manager.actualElement
            && tooltip_manager.isCalledHideDiv
            || null == tooltip_manager.actualElement
            || null == tooltip_manager.isCalledHideDiv){

          jQuery( div_id ).css({position:"absolute",top:e.pageY,left:e.pageX});

          tooltip_manager.overLinkElement = true;
          tooltip_manager.actualElement = this;
          tooltip_manager.isCalledHideDiv = false;

          tooltip_manager.timer = setTimeout("showDivFadeIn('"+div_id + "','"+text_type+"')",1000);
        }
      }).mouseout( function() {
        tooltip_manager.overLinkElement = false;
        setTimeout("hide_div('"+div_id+"')",100);
      });

      jQuery( div_id ).mouseover(function () {
        tooltip_manager.overDivElement = true;
      }).mouseout( function( ) {
        tooltip_manager.overDivElement = false;
        if( shown == false )
        {
          setTimeout("hide_div('"+div_id+"')",100);
        }
        shown = false;
      });

      jQuery( div_id ).children( ).mouseover( function( ) {
        tooltip_manager.overDivElement = true;
        shown = true;
        jQuery( div_id ).show( );
      }).mouseout( function( ) {
        shown = true;
        jQuery( div_id ).show( );
      });
    }
  });
})(jQuery);

function set_text_for_tooltip(text_type, div_id){

  if (text_type == "zitierung"){
    text_zitierung(div_id);
  }
  else if (text_type == "fussnote") {
    var a_id = jQuery( tooltip_manager.actualElement ).children("sup").children("a:first").attr("href");

    jQuery( div_id ).html(jQuery( a_id ).text());
    jQuery( div_id ).fadeIn();
  }
  else if (text_type == "gesetz") {
    if ( null != tooltip_manager.actualElement ) {
      text_zu_gesetz_abkuerzung(div_id, tooltip_manager.actualElement);
    }
  }
}

function showDivFadeIn(div_id, text_type) {
  set_text_for_tooltip(text_type, div_id);
}

function hide_div(div_id) {
  tooltip_manager.isCalledHideDiv = true;
  tooltip_manager.actualElement = null;
  if (!tooltip_manager.overLinkElement && !tooltip_manager.overDivElement){
    if (tooltip_manager.timer != null) {
      clearTimeout(tooltip_manager.timer);
    }
    jQuery( div_id ).hide();
    jQuery( div_id ).html("");
  }
}

get_server_address = function (url)
{
  var server_address_string = url.match(/.*[?]/);
  server_address_string = server_address_string[0].substring(0,server_address_string[0].length-1);

  return server_address_string;
}

insertElementIntoDOM = function(type, parent, props, styleClass)
{
    var element = null,i;

    element = document.createElement(type);

    element.setAttribute("class",styleClass);
    if (parent)
        parent.appendChild(element);

    if (props)
        for (i in props)
            element[i] = props[i];

    return element;
};

/*
jQuery(function(){

    if( jQuery.browser.msie && jQuery.browser.version == '6.0' )
    {
        if( jQuery( '.functions' ).html( ) )
        {
            var html = jQuery( '.functions' ).html( );
            jQuery( '.functions' ).empty();
            jQuery(".container").before( '<div style="position:relative;"><div class="functions">' + html + '</div></div>' );
        }

        var right = (jQuery( 'body' ).width() - window.document.documentElement.clientWidth + 5 );
        jQuery( '.functions' ).css( 'right', right - 10 );
        jQuery( '.schriftgrad' ).css( 'right', right );
        jQuery( '.header .menu' ).css( 'right', right );
    }
    jQuery(window).resize(function(){
        if( jQuery.browser.msie && jQuery.browser.version == '6.0' )
        {
            var right = (jQuery( 'body' ).width() - window.document.documentElement.clientWidth + 5 );
            jQuery( '.functions' ).css( 'right', right - 10 );
            jQuery( '.schriftgrad' ).css( 'right', right );
            jQuery( '.header .menu' ).css( 'right', right );
        }
    });

});*/



