var start = new Date().getTime(); 

function kombo(elem,field,submit) {//{{{     
  if (elem.value=='||edit||') {
    $("#"+field).val("");
    $("#"+field).show();
    $("#"+field+"Submit").show();
  } else {
    $("#"+field).val(elem.value);
    if (submit) {
      elem.form.submit();
    }
  }
} //}}}

function dbgMsg(msg) {//{{{
  var now = new Date();
  d = now.getTime()-start;
  console.log(d+': '+msg);
} //}}}
function highlightWords(node,words) {//{{{
  
  // in the case we use the boolean fulltext search mode we need to highlight all words...
  // todo: disable stop-words
  /*
  // remove +-~"" etc.
  // split @wordboundaries
  // call for all words
  var splittedwords = words.replace('"','').replace('~','').replace('-','').replace('+','').split(" ");
  for(i = 0; i < splittedwords.length; i++){
	  if (''!=splittedwords[i]) {
	    highlightWord(node,splittedwords[i]);
	  }
	}
	*/
	highlightWord(node,words);
	
} //}}}


function highlightWord(node,word) {//{{{  
  if (node.hasChildNodes) { 
    var hi_cn; 
    for (hi_cn=0;hi_cn<node.childNodes.length;hi_cn++) {
      highlightWord(node.childNodes[hi_cn],word);
    }
  } 
  if (node.nodeType == 3) {
    tempNodeVal = node.nodeValue.toLowerCase(); 
    tempWordVal = word.toLowerCase(); 
    if (tempNodeVal.indexOf(tempWordVal)!= -1) { 
      pn = node.parentNode; 
      if (pn.className!= "searchword") { 
        nv = node.nodeValue; 
        ni = tempNodeVal.indexOf(tempWordVal); 
        before = document.createTextNode(nv.substr(0,ni)); 
        docWordVal = nv.substr(ni,word.length); 
        after = document.createTextNode(nv.substr(ni+word.length)); 
        hiwordtext = document.createTextNode(docWordVal); 
        hiword = document.createElement("span"); 
        hiword.className = "searchword"; 
        hiword.appendChild(hiwordtext); 
        pn.insertBefore(before,node); 
        pn.insertBefore(hiword,node); 
        pn.insertBefore(after,node); 
        pn.removeChild(node); 
      }
    }
  } 
} //}}}

function positionLoginBox() {//{{{ 
    if (null != $("#loginBoxToggler").offset()) {
      $("#loginBoxToggler").click(function(event) { 
        if ( $("#loginBox").is(":visible")){
          $("#loginBox").hide();
        } else {
          $("#loginBox").show();
        }
        return false;
      });
      //offset1 = $("#loginBoxToggler").offset();
      //offset1.top += $("#loginBoxToggler").outerHeight();
      //$("#loginBox").css("left",offset1.left);
      //$("#loginBox").css("top",offset1.top);
    }
} //}}}


var __itemWidth = 0; // wird dann berechnet aus den aktuellen werten 
var __numItems = 0;  // wird dann berechnet aus den aktuellen werten 
var __focus = 1;
var __visibleItems=0;
var __visibleItemsHalf=0;
var __timeout = 350; // not fewer than 200 because we do not stress the server 

function initTimeline() {//{{{ 
  
  /**
  initialisiere die Timeline,
  - scrolle zu current Item
  - beginne die sichtbaren Items zu laden
  - binde die scrollfunktionen an die ui-elemente
  
  */
  if ($("#itemcontainer").size()>0) {
    __itemWidth = parseInt($('#itemcontainer div.item:first-child').css('width'))+
                  parseInt($('#itemcontainer div.item:first-child').css('margin-left'))+
                  parseInt($('#itemcontainer div.item:first-child').css('margin-right'))+
                  parseInt($('#itemcontainer div.item:first-child').css('padding-left'))+
                  parseInt($('#itemcontainer div.item:first-child').css('padding-right'))+
                  parseInt($('#itemcontainer div.item:first-child').css('border-left-width'))+
                  parseInt($('#itemcontainer div.item:first-child').css('border-right-width'));
    __numItems = $('#itemcontainer > div').size();
    $('#itemcontainer').css('width',__itemWidth*__numItems+50); // etwas groesser als die items die reinmuessen
    $('#itemcontainer').css('min-height','200px');

    if ($('#clip').width() > $('#itemcontainer').width())  {
      $('#itemcontainer').css('margin','0 auto');
    }
    
    // needed for ipad native scrolling: 
    //$('#clip').css('overflow','scroll');
    $('#clip').css('overflow','hidden');
    $('#clip').scroll( function(evt) {
      // der slider soll manipuliert werden, wenn der Benutzer den scrollbar direkt benutzt.
      // sonst nicht
      currentvalue = $("#content-slider").slider('value');
      newvalue = Math.round((__numItems)*(parseInt($('#clip').scrollLeft()) / ( parseInt($('#itemcontainer').css('width')) - parseInt($('#clip').css('width')) ) ));
      //dbgMsg('scroll: current:'+currentvalue+' - new: '+newvalue);
      if (newvalue!=currentvalue) {  $("#content-slider").slider('value', newvalue); }
    });
    __visibleItems = Math.ceil(parseInt($('#clip').css('width'))/__itemWidth);
    __visibleItemsHalf = Math.ceil(__visibleItems/2);
    __focus = __numItems;    
    $("#content-slider").slider({
      animate: true,
      value:0,
      max: __numItems,
      change: function(e, ui) {
        var maxScroll = $("#clip").attr("scrollWidth") - $("#clip").width();
        $("#clip").attr({scrollLeft: ui.value * (maxScroll / __numItems) });
        __focus = ui.value;
        //dbgMsg('focus: '+__focus);
        loadItem(__focus);
      },
      slide: function(e, ui) {
        var maxScroll = $("#clip").attr("scrollWidth") - $("#clip").width();
        $("#clip").attr({scrollLeft: ui.value * (maxScroll / __numItems) });
      }
    });
    focusItem(__focus);
    loadItem(__focus);
  }       
} //}}}
function loadItem(idx) {//{{{    
  //dbgMsg('loadItem idx:: '+idx);
  currItem = $('#itemcontainer div.item:nth-child('+(idx)+')');
  if (currItem.attr('id')) {
    if (!currItem.hasClass('loaded')) {
      currItem.addClass('loaded');
      targetid = currItem.attr('id').substr(7);
      jQuery.get("getWerk.php", { id:targetid},
        function(data) {
          //alert(data);
          $("item", data).each(function(ii) {
            resid = $(this).attr('id');
            $('#itemid_'+resid).html(((null!=$(this).html())?$(this).html():'<p>failure</p>'));
            $('#itemid_'+resid+' a.tooltip').tooltip({
              bodyHandler: function() { 
                //return('hallo');
                return $($(this).attr("rel")).html(); 
              }, 
              showURL: false,
              track: true, 
              delay: 0, 
              fade: 250 
            });
            //dbgMsg('loadItem: '+resid);
          });
        }
      );
      //currItem.css('background-color','#f00');
      timeout = __timeout;
    } else {
      timeout = 1;
    }
  }
  // schedule next load
  // das aktuelle ist geladen, lade das nächste ...
  abstand = Math.abs(idx-__focus);
  if (abstand<=__visibleItems) {
    if (idx<__focus) {
      window.setTimeout(loadItem, timeout, __focus+abstand);
    } else {
      window.setTimeout(loadItem, timeout, __focus-abstand-1);          
    }
  }
  //$('#itemcontainer div.item:nth-child(5)').css('background-color','#f00');
} //}}}

function focusItem(idx) {//{{{ 
  $('#clip').scrollLeft((idx-__visibleItemsHalf)*__itemWidth);
  //$('#itemcontainer').css('left',-(idx-__visibleItemsHalf)*__itemWidth);
} //}}}
