/*----------------------------------*/
/* button behaviour v210308         */


$(function(){

  // test for cookies, display modal dialog if no cookies
  if(!document.cookie) {
  $('#flashnotice').html('Achtung, ihr Browser unterstützt in der jetzigen Einstellung keine Cookies. Die Website läßt sich ohne Cookies leider nicht benutzen.<br>Um Cookies zu aktivieren, befolgen Sie die unten stehenden Anweisungen für den Browser, den Sie verwenden. <br><br><b>Firefox</b><ol style="padding-left:2em;"><li>Rufen Sie das Menü "Extras" auf.<li>Wählen Sie "Einstellungen".<li>Wählen Sie das Symbol "Datenschutz" und dann die Registerkarte "Cookies".<li>Aktivieren Sie das Kästchen "Cookies akzeptieren" und "Cookies von Drittanbietern akzeptieren".<li>Klicken Sie auf "OK", um Ihre Änderungen zu speichern.</ol> <br><br><b>Microsoft Internet Explorer</b><ol style="padding-left:2em;"><li>Öffnen Sie das Menü "Extras" und wählen Sie "Internetoptionen…" aus.<li>Klicken Sie auf die Registerkarte "Datenschutz".<li>Klicken Sie auf die Schaltfläche "Standard" (oder schieben Sie den Regler manuell bis zu der Option "Mittel") unter "Einstellungen".<li>Klicken Sie auf "OK".</ol><br><br><br>Wenn Sie dies getan, können Sie diese Seite neu laden.');
  $('#flashnotice').dialog({modal: true, draggable: false, closeOnEscape: false, resizable: false, width:430, autoOpen: true, title: 'Warn-Hinweis', buttons: { 'Seite neu laden': function() { document.location.href = document.location.href; } }      });
  }

  $(document).ajaxError(function(event, request, settings){window.alert('Wir entschuldigen uns für den Fehler. Bitte versuche es später noch einmal.')});

  if(document.all) {jQ_setHeightofLockscreen();$(window).bind('resize', jQ_setHeightofLockscreen);}

  jQ_makeButtonsClickable(1);
  $('.errorhint').bind("click",function(){$(this).hide();});
  $(window).bind("ajaxComplete",function(){jQ_makeButtonsClickable(0);});

  jQuery("body").bind("ajaxSend", function(elm,xhr,s) {
    if(s.type=="GET") return;
    if(s.data) s.data = s.data + "&";
    s.data = s.data + "_method"+"="+s.type;
  });

  //add hints to all inputfields that have text in the title attribute
  $('input[title!=""]').hint();
  
  //add big image click event to all thumbnail images
  $('.thumbnail_img').parent().click(function(){jQ_show_HTML_in_Dialog('#feedback','<div style="height:width:460px;overflow:auto;height:400px;"><img src="'+this.href+'"></div>','Bild');return false;});

});

function jQ_makeButtonSpin(btn){btn.html('<a href="#"><center><img src="/images/spinner_green_kl.gif"/></center></a>');}

function jQ_updateMetalbuttons()
    {
    $('.metalbutton').each(function(){
        if(!$(this).children("label").children("input").attr("checked") && $(this).hasClass("pushed_metalbutton"))  $(this).removeClass("pushed_metalbutton");
        });
    }

function jQ_makeButtonsClickable(rebind_all)
  {
  if(rebind_all) {
  $('.metalbutton').mousedown(function(event){
    $(this).removeClass("highlight_metalbutton");
    if($(this).hasClass("pushed_metalbutton")) {$(this).removeClass("pushed_metalbutton"); $(this).children("label").children("input").attr("checked",false);}
    else                                       {$(this).addClass("pushed_metalbutton");    $(this).children("label").children("input").attr("checked",true);}
    jQ_updateMetalbuttons();
    
    event.stopImmediatePropagation();
    });

  $('.metalbutton').hover(  function(event){if(!$(this).hasClass("pushed_metalbutton")){$(this).addClass("highlight_metalbutton");}    event.stopImmediatePropagation();},
                            function(event){if(!$(this).hasClass("pushed_metalbutton")){$(this).removeClass("highlight_metalbutton");} event.stopImmediatePropagation();});


  $('#floatingeditor').draggable({handle:'.draghandle'});

  $('.linkbutton').hover(function(){$(this).addClass("linkbutton_hover");$(this).children("ul").show();},function(){$(this).removeClass("linkbutton_hover");$(this).children("ul").hide();});
  $('.linkbutton2').hover(function(){$(this).addClass("linkbutton2_hover");$(this).children("ul").show();},function(){$(this).removeClass("linkbutton2_hover");$(this).children("ul").hide();});
  $('.linkbutton_black').hover(function(){$(this).addClass("linkbutton_black_hover");$(this).children("ul").show();},function(){$(this).removeClass("linkbutton_black_hover");$(this).children("ul").hide();});
  }

  $('.button').mousedown(function(event){$(this).removeClass("mouseout");$(this).removeClass("mouseover");$(this).addClass("pressed"); event.stopImmediatePropagation();});
  $('.button').hover(function(){$(this).removeClass("pressed");$(this).removeClass("mouseout");$(this).addClass("mouseover");},function(){$(this).removeClass("pressed");$(this).removeClass("mouseover");$(this).addClass("mouseout");});
  $('.button').mouseup(function(){$(this).removeClass("mouseover");$(this).removeClass("pressed");$(this).addClass("mouseout");});
  
  $('.toolstabs li a').bind('click',function(){$(this).parent().parent().children('.active').removeClass('active');$(this).parent().addClass('active');});
  $('.tabsw li a').bind('click',function(){$(this).parent().parent().children('.active').removeClass('active');$(this).parent().addClass('active');});

  }



function jQ_loadApp(link_obj,width)
  {
  var offset = get_offset_from_site(link_obj);
  $('#floating_app_window_content').html('<div class="center"><img src="/images/spinner_black_big.gif"/></div>');
  $('#floating_app_window_content').load(link_obj.href);
  if(typeof(pageTracker)!="undefined") pageTracker._trackPageview(link_obj.href);
  
  if(offset)
    {
    $('#floating_app_window_content').css('width',width+'px');
    $('#floating_app_window_content').css('min-width',width+'px');
    $('#floating_app_window_content').css('max-width',width+'px');
    $('#app_window_arrow_up').hide();
    $('#app_window_arrow_right').hide();
    $('#app_window_arrow_left').hide();
    if(offset.top<100) $('#app_window_arrow_up').show();
    else if(offset.left>500) $('#app_window_arrow_right').show();
    else $('#app_window_arrow_left').show();

      if(width<750)
        {
        $('#app_window_arrow_up').css('margin-right','0');
        $('#floating_app_window').css('left',(offset.left>500 ? offset.left-width-(offset.top<100 ? -10 : 60) : offset.left+60)+'px');
        }
      else
        {
        $('#floating_app_window').css('left',parseInt((932.0-width)/2.0)+'px');
        $('#app_window_arrow_up').css('margin-right',900-offset.left+0+'px');
        }
      $('#floating_app_window').css('top', (offset.top<100 ? offset.top+50 : offset.top-30)+'px');
      $('#floating_app_window').show();
    }
  }

function jQ_closeApp()
  {
  $('#floating_app_window_content').html('<div class="center"><img src="/images/spinner_black_big.gif"/></div>');
  $('#floating_app_window').hide();
  $('#app_window_arrow_up').hide();
  $('#app_window_arrow_right').hide();
  $('#app_window_arrow_left').hide();
  }


function get_offset_from_site(obj)
    {
    var this_offset = {top:0, left:0};
    while(obj.id!="site" && obj.id!="floating_app_window_content")
        {
        this_offset.top += obj.offsetTop;
        this_offset.left += obj.offsetLeft;
        obj = obj.offsetParent;
        }
    if(obj.id=="floating_app_window_content") this_offset = false;
    return(this_offset);
    }


function box_entfernen()
    {
    if(window.confirm("Wirklich entfernen?")) {
    $(this).parent().remove();
    $('#test_me').load('/save_startpage_config',{sp_config: createSPconfig()},function()
        {
        $('#newboxes_content').load('/load_box',{box_name: 'newboxes'});
        });
    }
    }

function box_nachladen(event, ui)
    {
    if($(this).parent(".startpage_items") && ui.item.attr('id').indexOf('-')==-1)
        {
        update_sp = false;
        ui.item.load('/load_box',{box_name: ui.item.attr('id')},function()
            {
            $(this).prepend($('#li_elems_icons').html()).attr('id',ui.item.attr('id')+'-A-1-0');
            initOneSPItem(this);    
            $('#test_me').load('/save_startpage_config',{sp_config: createSPconfig()});
            update_sp = true;
            });
        }
    }

function box_aufzuklappen()
    {
    if($(this).parent().find('.fold_me_up').hasClass('hidden'))
    {
    $(this).parent().find('.fold_me_up').removeClass('hidden');
    $(this).parent().find('.show_me_instead').addClass('hidden');
    $(this).parent().attr('id',$(this).parent().attr('id').replace(/([a-z_]+)\-(A|B)\-(\d)\-(\d)/,'$1-$2-1-$4'));
    } else {
    $(this).parent().find('.fold_me_up').addClass('hidden');
    $(this).parent().find('.show_me_instead').removeClass('hidden');
    $(this).parent().attr('id',$(this).parent().attr('id').replace(/([a-z_]+)\-(A|B)\-(\d)\-(\d)/,'$1-$2-0-$4'));
    }
    $('#test_me').load('/save_startpage_config',{sp_config: createSPconfig()});
    }

function initOneSPItem(obj)
    {
    $(obj).children('.ui-icon-arrowthickstop-1-n').bind('click',box_aufzuklappen);
    $(obj).children('.ui-icon-trash').bind('click',box_entfernen);
    }

function initStartpageItems()
    {
    $('.startpage_items .ui-icon-arrowthickstop-1-n').bind('click',box_aufzuklappen);
    $('.startpage_items .ui-icon-trash').bind('click',box_entfernen);
    $('.startpage_items').sortable({ cancel: '.cannot_edit', handle: '.ui-icon-arrow-4', connectWith: 'ul.startpage_items', placeholder: 'drophere',
    receive: box_nachladen,
    remove: function(event, ui) { update_sp = false; },
    start: function(event, ui) { update_sp = true; },
    update: function(event, ui) {if(update_sp) $('#test_me').load('/save_startpage_config',{sp_config: createSPconfig()});}
    }).disableSelection();
    }

function createSPconfig()
    {
    result_config = [];
    $('.spalte1 .startpage_items > li').each(function (i){result_config.push(this.id.replace(/\-/g,':').replace(/:B:/,':A:'));});
    $('.spalte4 .startpage_items > li').each(function (i){result_config.push(this.id.replace(/\-/g,':').replace(/:A:/,':B:'));});
    return(result_config.join(','));
    }



/*----------------------------------*/
/* for snippet editing              */

function jQ_showAdminOutlines(show_outlines)
  {
  if(show_outlines) $('.snippet').addClass("admin");
  else              $('.snippet').removeClass("admin");
  }


/*----------------------------------*/
/* user settings function v130708   */

function jQ_setUserSetting(settings_url,authKey,authValue,settingKey,settingValue)
  {
  $.ajax({
    type: "PUT",
    url: settings_url,
    data: authKey + "=" + encodeURIComponent(authValue) + "&setting[" + settingKey + "]=" + settingValue
    });
  }


/*********** checkups ************/

var next_question = '';

function markAnswer(obj)
  {
  $(obj).parent().parent().parent().children('.checkup_answer').removeClass('selected');
  $(obj).parent().parent().parent().children('.checkup_answer').children('label').children('span').children('.hidden').hide();
  $(obj).parent().parent().addClass('selected');
  $(obj).parent().children('span').children('.hidden').show();
  }

function countAnsweredQuestions()
  {
  var questions_answered = 0;
  $('.checkup_question').each(function()
    {
    $(this).children('.checkup_answer').children('label').children('input').each(function(){if(this.checked){questions_answered++;}});
    }
  );
  return(questions_answered);
  }

  function shownextquestion()
    {
    next_question = $('.checkup_question.visible').next().children('.question_title').html();
    $('#next_question').html(next_question);
    }

  function checkIfFinished(q_nr)
    {
    updateProgressBar(countAnsweredQuestions(),question_count);
    var question_answered = false;
    if($('.question_'+q_nr).length==0) {question_answered = true;}
    for(var q=0;q<$('.question_'+q_nr).length;q++) {if($('.question_'+q_nr).get(q).checked) {question_answered = true;break;}}
    if(question_answered) {$('#weiter_'+q_nr).removeClass('invisible_button');}
    }
    
  function updateProgressBar(answered,total)
    {
    $('.progress_indicator').height('17px');
    $('.progress_indicator').width(parseInt(answered/total*224)+'px');
    if(answered==total)
      {
      $('.status_comment').hide();
      $('.finished').show();
      }
    $('.fragen_gesamt').html(total);
    $('.offene').html(''+answered);
    }

    function checkup_next()
      {
      $('#next_question').html(next_question);
      var checkup_page = $('#checkup_topics').children('.visible');
      checkup_page.toggleClass('visible');
      checkup_page.next().toggleClass('visible');
      }

    function checkup_prev()
      {
      var checkup_page = $('#checkup_topics').children('.visible');
      checkup_page.toggleClass('visible');
      checkup_page.prev().toggleClass('visible');
      }




/*********** help message boxes ************/


function jQ_showHelp(id,thisevent,text)
  {
  if($('#'+id).length==0)
    {
    var obj = (document.all ? thisevent.srcElement : thisevent.target);
    var oh = $(obj).parent().height();
    var ow = $(obj).parent().width();
    $(obj).append('<div class="absolute hidden contexthelp" id="'+id+'"><div class="infobox_arrow absolute"></div><div class="helpclose right" onClick="$(\'#'+id+'\').remove();"></div>'+text+'</div>');
    $('#'+id).css("top",oh+2);
    $('#'+id).css("right",parseInt(ow/2));
    var parentwidth = $('#'+id).parent().parent().parent().parent('.box').width();
    if(typeof(overwrite_parentwidth) != "undefined") parentwidth = overwrite_parentwidth;
    if(parentwidth!=null) {$('#'+id).width(parentwidth+"px");}
    $('#'+id).show();
    }
  }


var active_request = 0;

/******* for messages **************/

function jQ_loadMSG(id,wohin,message_ids,navi_id)
  {
  var myid = getMSGindex(id,message_ids);

  priv_switch_to_page_of_MSG(myid);
  selectMSG(id);

  $(wohin).html('<center><br/><br/><br/><br/><br/><br/><br/><br/><img src="/images/spinner2.gif"/><br/><br/></center>');

  if(active_request) {active_request.abort();}
  active_request = $.ajax({
    type: "GET",
    url: message_ids[myid][1],
    datatype: "html",
    success: function(data)
      {
      active_message = id;
      updateMSGnavigation(myid,navi_id,wohin,message_ids);
      jQ_updateMSGstati(id);
      $(wohin).html(data);
      }
    });
  }

//private

function priv_switch_to_page_of_MSG(msg_index)
  {
  jQ_switchToPage(Math.floor(msg_index/max_pages_for_msg), num_of_pages);
  }

function selectMSG(id)
  {
  $('#message_list_body tr').css("background-color",'#ffffff');
  $('#div_message_'+id).css("background-color",'#dae8e6');
  oldcolor = '#dae8e6';
  }

function updateMSGnavigation(myid,navi_id,wohin,message_ids)
  {
  var navi_html = "<div class=center>Nachricht " + (myid+1) + " von " + message_ids.length + "</div>";
  if(myid>0) {navi_html = '<a class=left href="javascript:;" onClick="jQ_loadMSG(\''+message_ids[myid-1][0]+ '\',\'' + wohin + '\',messages,\'' + navi_id + '\');"><img src="/images/pfeil_zurueck.gif"> vorherige</a>' + navi_html;}
  else {navi_html = '<span class=left>vorherige</span>' + navi_html;}
  if(myid<message_ids.length-1) {navi_html = '<a class=right href="javascript:;" onClick="jQ_loadMSG(\''+message_ids[myid+1][0]+ '\',\'' + wohin + '\',messages,\'' + navi_id + '\');">nächste <img src="/images/pfeil.gif"></a>' + navi_html;}
  else {navi_html = '<span class=right>nächste</span>' + navi_html;}
  $(navi_id).html(navi_html);
  }

function updatePageNavigation(myid,message_ids)
  {
  for(i=0;i<message_ids.length;i++){message_ids[i][2] = Math.floor(i/max_pages_for_msg);}
  num_of_pages = Math.floor(message_ids.length/max_pages_for_msg) + (message_ids.length % max_pages_for_msg==0 ? 0 : 1);
  jQ_createPageNavigation(Math.floor(myid/max_pages_for_msg),num_of_pages);
  priv_showPage(Math.floor(myid/max_pages_for_msg));
  }


function getMSGindex(id,message_ids)
  {
  var myid = 0;
  for(myid=0;myid<message_ids.length;myid++) {if(message_ids[myid][0] == id) break;}
  return(myid);
  }

function jQ_removeMSG(id,message_ids)
  {
  var old_msg_index = -1;
  var msgidarr = [];
  var n = 0;
  for(var i=0;i<message_ids.length;i++)
    {
    if(message_ids[i][0]!=id)
      {
      msgidarr[n] = message_ids[i];
      n++;
      }
    else {old_msg_index = i;}
    }

  if(active_message==id)
    {
    if(old_msg_index>=msgidarr.length) {old_msg_index = msgidarr.length-1;}
    jQ_loadMSG(msgidarr[old_msg_index][0],'#messageview',msgidarr,'#message_navigation');    
    updatePageNavigation(old_msg_index,msgidarr);
    }
  else
    {
    updateMSGnavigation(getMSGindex(active_message,msgidarr),'#message_navigation','#messageview',msgidarr);
    updatePageNavigation(getMSGindex(active_message,msgidarr),msgidarr);
    jQ_updateMSGstati(id);
    }

  return(msgidarr);
  }

function jQ_updateMSGstati(id)
  {
  if(($('#msg_'+id+'_status').attr('src')).indexOf('nachricht_g.gif')!=-1)
    {
    $('#msg_'+id+'_status').attr('src','/images/icons/nachricht_read_g.gif').attr('alt','Gelesen');
    newInboxCount = parseInt($('#Inbox_count').html().replace(/[\(\)]/g,''))-1;
    $('#Inbox_count').empty();
    if(newInboxCount>0) {$('#Inbox_count').html('('+newInboxCount+')');}
    $('#messagebox_status').load('/message_boxes/get_messagebox_status');
    }
  }


/************** Username check ********************/

var oldsearchstring = "";
var hidetimeout = 0;
var searchstarttimeout = 0;
var ac_textfield = '';
var userdisplayname_status = -1;

function jQ_checkUserName(event)
  {
  var textfield = (document.all ? event.srcElement : event.target);
  var keystroke = (document.all ? event.keyCode : event.which);
  
  if(!textfield.value.match(/^[a-z|A-Z|_|0-9|\-|\.|ä|ö|ü|Ö|Ä|Ü|ß|é|è|á|à|ç|å][a-z|A-Z|_|0-9|\s|\-|\.|ä|ö|ü|Ö|Ä|Ü|ß|é|è|á|à|ç|å]{0,28}[a-z|A-Z|_|0-9|\-|\.|ä|ö|ü|Ö|Ä|Ü|ß|é|è|á|à|ç|å]$/))
    {
    if(active_request) {active_request.abort();}
    $('#'+textfield.id+'_check .usernamehint').hide();
    $('#'+textfield.id+'_check .username_check').hide();
    $('#'+textfield.id+'_check .username_notok').show();
    $('#'+textfield.id+'_check .username_notok2').show();
    userdisplayname_status = -1;
    oldsearchstring = textfield.value;
    }
  else if((keystroke < 16 || keystroke > 18) && keystroke != 224 && keystroke != 37 && keystroke != 38 && keystroke != 39 && keystroke != 40
    && textfield.value != oldsearchstring && textfield.value.length > 1)
    {
    oldsearchstring = textfield.value;
    var searchstring = textfield.value;
    window.clearTimeout(searchstarttimeout);
    $('.ac_spinner').remove();
    $(textfield).after('<div class="ac_spinner hidden"></div>');
    $('.ac_spinner').css("left", parseInt(textfield.offsetLeft) + (-18) + parseInt(textfield.offsetWidth) + "px");
    $('.ac_spinner').css("top", textfield.offsetTop + 2 + "px");
    $('#'+textfield.id+'_check .usernamehint').hide();
    ac_textfield = textfield;
    searchstarttimeout = window.setTimeout("startNameSearch(ac_textfield,'" + searchstring.replace("'", "\\'") + "');", 300);
    }
  }

function startNameSearch(textfield,searchstring){
  $('.ac_spinner').show();
  $('#'+textfield.id+'_check .username_check').show();
  if(active_request) {active_request.abort();}
  active_request = $.ajax({
    type: "POST",
    url: '/users/check_display_name',
    data: 'display_name=' + searchstring,
    datatype: "text",
    success: function(data){
      userdisplayname_status = parseInt(data);
      $('#'+textfield.id+'_check .username_check').hide();
      if(data=='1') {$('#'+textfield.id+'_check .username_free').show();}
      if(data=='0') {$('#'+textfield.id+'_check .username_taken').show();}
    },
    complete: function(){
      $('.ac_spinner').remove();
      $('#'+textfield.id+'_check .username_check').hide();
    }
  });
}



// for pagination ---->

var pg_activepage = 0;
var pg_max_pages = 0;


function jQ_createPageNavigation(initpage,pages_length)
  {
  pg_activepage = initpage;
  if(pages_length>1)
    {
    pg_max_pages = pages_length;
    var navi_str = '<a href="javascript:;" class="prev" onClick="jQ_prevPage(\''+pages_length+'\');"><img src="/images/pfeil_zurueck.gif"/><\/a>';
    if(pg_max_pages>7)
      {
      navi_str += '<div class="page active">'+(1+pg_activepage)+' - '+pg_max_pages+'<\/div>';
      }
    else
      {
      for(var i=0;i<pg_max_pages;i++)
        {
        if(i!=pg_activepage) {navi_str += '<a href="javascript:;" class="page" onClick="jQ_switchToPage(\''+i+'\',\''+pages_length+'\');">'+(i+1)+'<\/a>';}
        else {navi_str += '<div class="page active">'+(i+1)+'</div>';}
        }
      }

    navi_str += '<a href="javascript:;" class="next" onClick="jQ_nextPage(\''+pages_length+'\');"><img src="/images/pfeil.gif"/><\/a>';
    $('.navigation').html(navi_str);
    }
  else {$('.navigation').empty();}
  }

function jQ_switchToPage(page,pages_length)
  {
  if(page!=pg_activepage)
    {
    jQ_createPageNavigation(page,pages_length);
    priv_showPage(pg_activepage);
    }
  }

function jQ_nextPage(pages_length)
  {
  window.status = "Page: "+pg_activepage+" / max: " + pg_max_pages;
  if(pg_activepage<(pg_max_pages-1)) {jQ_createPageNavigation(parseInt(pg_activepage)+1,pages_length);}
  else {pg_activepage = pg_max_pages-1;}
  priv_showPage(pg_activepage);
  }

function jQ_prevPage(pages_length)
  {
  if(pg_activepage>0) {jQ_createPageNavigation(parseInt(pg_activepage)-1,pages_length);}
  else {pg_activepage = 0;}
  priv_showPage(pg_activepage);
  }

// <---- for pagination


/*----------------------------------*/
/* for blog edit v100408            */

    function checkBlogForm(id)
      {
      var formerrors = [];
      if($('#article_title').val()=='')
        {
        $('#article_title').css('border-bottom','3px solid red');
        formerrors.push('Gib deinem Blog-Beitrag einen Titel.');
        }
      else $('#article_title').css('border-bottom','1px solid #333333');

      var notags = true;
      for(var i=0;i<quevita_tags.length;i++)
        {
        if($('#'+quevita_tags[i]).get(0).checked)
          {
          $('.tagbutton.left').css('border-bottom','none');
          notags = false;
          break;
          }
        else
          {
          $('.tagbutton.left').css('border-bottom','3px solid red');
          }
        }
      if(notags) {formerrors.push('Wähle einen Quevita-Tag.');}

      if(formerrors.length==0) {$(id).get(0).submit();}
      else {window.alert("Fehler:\n"+formerrors.join('\n'));}
      }



/*----------------------------------*/
/* for goals v240308                */


function jQ_expandTextfield(field)
  {
  if(field.value.length>60 && field.tagName!="TEXTAREA")
    {
    var w = $(field).width();
    $(field).before('<textarea class="' + field.className + '" name="' + field.name + '" onChange="' + $(field).attr('onChange') + '" style="width:' + w + '" cols="60" rows="2">' + field.value + '</textarea>');
    $(field).prev('textarea').focus();
    $(field).remove();
    }
  }






/*----------------------------------*/
/* tdudai, tracker specific v130308 */


function getMin(data,index){
  var result = 0;
  if(data[0]!=null){
    result = data[0][index];
    for(var n=1;n<data.length;n++){if(data[n][index]<result) {result = data[n][index];}}
  }
  return(result);
}


function getMax(data,index){
  var result = 0;

  if(data[0]!=null){
    result = data[0][index];
    for(var n=1;n<data.length;n++){if(data[n][index]>result) {result = data[n][index];}}
  }
  return(result);
}


function positionDataHelper(x,y){
  $('.tracker_info').hide();
  if (active_helper != -1) {
    $('#tracker_info_' + active_helper).css("top", (y) + "px");
    $('#tracker_info_' + active_helper).css("left", (x+100) + "px");
    $('#tracker_info_' + active_helper).show();
  }
}

function weekendAreas(plotarea) {
        var areas = [];
        var d = new Date(plotarea.xmin);
        d.setDate(d.getDate() - ((d.getDay() + 1) % 7));
        d.setSeconds(0);
        d.setMinutes(0);
        d.setHours(0);
        var i = d.getTime();
        do {
            areas.push({ x1: i, x2: i + 2 * 24 * 60 * 60 * 1000 });
            i += 7 * 24 * 60 * 60 * 1000;
        } while (i < plotarea.xmax);

        return areas;
    }


function initFlotPlot(id,d,d2,d3,d4,ymin,ymax,col_areas,col_lines,labels){
  if(col_lines===undefined || col_lines.length==0) col_lines = ["#777777", "#99dc34", "#009900","#333333"];
  var plot_width  = parseInt($(id).width());
  var plot_height = parseInt($(id).height());
  var internalflot = $.plot($(id), [
  {
    data: d4,
    label: (labels.length>3 ? labels[3] : ''),
    points: {show: (d4.length>2 ? true : false)},
    lines: {show: (d4.length>1 ? true : false)},
    shadowSize: 0
  },
  {
    data: d3,
    label: (labels.length>2 ? labels[2] : ''),
    points: {show: (d3.length>2 ? true : false)},
    lines: {show: (d3.length>1 ? true : false)},
    shadowSize: 0
  }, 
  {
    data: d2,
    label: (labels.length>1 ? labels[1] : ''),
    points: {show: (d2.length>2 ? true : false)},
    lines: {show: (d2.length>1 ? true : false)},
    shadowSize: 0
  }, {
    data: d,
    label: (labels.length>0 ? labels[0] : ''),
    points: {show: true},
    lines: {show: true}
  }], {
    xaxis: {
      mode: "time",
      ticks: parseInt(plot_width/50),
      tickFormatter: function (v, axis) {
                    var timeUnitSize = {"second": 1000,"minute": 60 * 1000,"hour": 60 * 60 * 1000,"day": 24 * 60 * 60 * 1000,"month": 30.43 * 24 * 60 * 60 * 1000,"year": 365.2425 * 24 * 60 * 60 * 1000};
                    function formatDate(d, fmt) {
                      var leftPad = function(n) {n = "" + n;return(n.length == 1 ? "0" + n : n);};
                      var r = [];
                      var escape = false;
                      var DayNames = ["So","Mo","Di","Mi","Do","Fr","Sa"];
                      for(var i = 0; i < fmt.length; ++i) {
                        var c = fmt.charAt(i);
                        if(escape) {
                            switch (c) {
                            case 'h': c = "" + d.getHours(); break;
                            case 'H': c = leftPad(d.getHours()); break;
                            case 'M': c = leftPad(d.getMinutes()); break;
                            case 'S': c = leftPad(d.getSeconds()); break;
                            case 'd': c = "" + d.getDate()+'.'; break;
                            case 'm': c = "" + (d.getMonth() + 1)+'.'; break;
                            case 'y': c = "" + d.getFullYear(); break;
                            case 'D': c = "" + (d.getHours()==0 ? DayNames[d.getDay()] : '&nbsp;'); break;
                            }
                            r.push(c);
                            escape = false;
                          }
                          else {
                            if(c == "%") {escape = true;}
                            else {r.push(c);}
                          }
                        }
                      return r.join("");
                    }
                    var d = new Date(v);   
                    var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]];
                    var span = axis.max - axis.min;
                    if(t < timeUnitSize.minute) {fmt = "%H:%M Uhr";}
                    else if(t < timeUnitSize.day) {
                      fmt = "%D %d%m<span>%h Uhr</span>";
                    }
                    else if(t < timeUnitSize.month) {fmt = "%d%m";}
                    else if(t < timeUnitSize.year)  {fmt = "%m/%y";}
                    else {fmt = "%y";}
                    return formatDate(d, fmt);
                  },
      minTickSize: [12, "hour"]
    },
    yaxis: {
      ticks: parseInt(plot_height/20),
      minTickSize: 1,
      min: ymin,
      max: ymax
    },
    colors: col_lines,
    legend: {show:(labels.length>0 ? true : false)},
    grid: {
      clickable: true,
      color: "#333333",
      tickColor: "#cccccc",
      hoverable: true,
      coloredAreas: col_areas
    }
  });

  var plot_x_span = getMax(d, 0) - getMin(d, 0);
  var plot_y_span = getMax(d, 1) - getMin(d, 1);
  if(plot_y_span==0) {plot_y_span = 30;}
  if(plot_x_span==0) {plot_x_span = 30;}
  var mein_faktor = (plot_height / plot_y_span) / (plot_width / plot_x_span);

  $(id).bind("click", function(e){
    var x = 0;
    var y = 0;
    if(document.all) {x = e.clientX;}
    else {x = e.pageX;}
    if(document.all) {y = e.clientY;}
    else {y = e.pageY;}
    window.setTimeout("positionDataHelper(" + x + "," + y + ");", 2);
  });

  $(id).bind("plotclick", function(e, pos, item){
    active_helper = -1;
    if(item && item.series.label!='avg') active_helper = item.dataIndex;
  });
  return(internalflot);
}


function jQ_deleteTrackerPoint(id, sender, auth_token, confirm_question){
  if (window.confirm(confirm_question)) {
    $(sender).html('<img src="/images/spinner_green_kl.gif"/>');

    $.ajax({
      type: 'DELETE',
      url: sender.href,
      data: auth_token,
      dataType: 'html',
      success: function(data){
        $(id).html(data);
      }
    });
  }
}


/*--------------------------------*/
/* tdudai, auto-completer v100308 */

var autocomplete_itemlist = [];
var oldsearchstring = "";
var searched_item_index = 0;
var hidetimeout = 0;
var searchstarttimeout = 0;
var ac_textfield = '';
var active_request = 0;
var return_pressed = false;
var ac_selectedresult = -1;
var ac_result_function = function(data,field) {field.value = data;}
var new_result_function = 0;

  function unique_array(arr)
    {
    var a = [];
    var l = arr.length;
    for(var i=0; i<l; i++)
      {
      for(var j=i+1; j<l; j++) {if(arr[i] === arr[j]) {j = ++i;}}
      a.push(arr[i]);
      }
    return a;
    }

  function jQ_createContactList(form, textfield_id, item_delimiter)
    {
    formdata = $(form).serializeArray();
    var nickname_list = [];
    var oldnickname_list = $(textfield_id).val().split(item_delimiter);
    for(var i=0;i<oldnickname_list.length;i++) {if(oldnickname_list[i]!="") {nickname_list.push(oldnickname_list[i])}}
    for(var i=0;i<formdata.length;i++) {nickname_list.push(formdata[i].value);}
    nickname_list = unique_array(nickname_list);
    $(textfield_id).val(nickname_list.join(item_delimiter));
    }


function jQ_autocomplete_getValue(textfield, found_item, item_delimiter){
  autocomplete_itemlist[searched_item_index] = found_item[0];
  oldsearchstring = found_item;
  if(new_result_function==0) ac_result_function(autocomplete_itemlist.join(item_delimiter),textfield);
  else new_result_function(autocomplete_itemlist.join(item_delimiter),textfield);
  hidetimeout = window.setTimeout("$('#ac_result').remove();", 100);
  return_pressed = false;
}

function jQ_autocomplete(event, searchurl, item_delimiter,user_function)
  {
  var searchstring = '';
  if(user_function) new_result_function = user_function;
  else new_result_function = 0;
  var textfield = (document.all ? event.srcElement : event.target);
  var keystroke = (document.all ? event.keyCode : event.which);

  if (keystroke >= 37 && keystroke <= 40) {
    selectEntry(textfield, keystroke);
    return_pressed = false;
  }
  else if (keystroke == 13) {
    insertEntry(textfield, keystroke, item_delimiter);
    return_pressed = true;

  }
  else {
    if(String.fromCharCode(keystroke) != item_delimiter &&
        (keystroke < 16 || keystroke > 18) && keystroke != 224 &&
        textfield.value != oldsearchstring && textfield.value.length > 1) {
      oldsearchstring = textfield.value;
      searchstring = textfield.value;
      if(item_delimiter != '')
        {
        var items = textfield.value.split(item_delimiter);
        if (items.length == 1)
          {
          searched_item_index = 0;
          searchstring = textfield.value;
          }
        else
          {
          for (var i = 0; i < items.length; i++)
            {
            if (autocomplete_itemlist[i])
              {
              if (autocomplete_itemlist[i] != items[i])
                {
                searchstring = items[i];
                searched_item_index = i;
                break;
                }
              }
            }
          }
        autocomplete_itemlist = items;
        }
      else
        {
        searched_item_index = 0;
        }

      window.clearTimeout(searchstarttimeout);
      if(searchstring.length>1 && (!item_delimiter || searchstring.indexOf(item_delimiter)==-1))
        {
        //window.alert(searchstring + "  /  " + searched_item_index);
  
        $('.ac_spinner').remove();
        $(textfield).after('<div class="ac_spinner hidden"></div>');
        $('.ac_spinner').css("left", textfield.offsetLeft + (document.all ? 0 : 0) + (-18) + textfield.offsetWidth + "px");
        $('.ac_spinner').css("top", textfield.offsetTop + (document.all ? 2 : 2) + "px");
  
        prepare_AC_ResultList(textfield);
        
        searchstarttimeout = window.setTimeout("startAjaxSearch(ac_textfield,'" + searchurl.replace("'", "\\'") + "','" + searchstring.replace("'", "\\'") + "','" + item_delimiter + "');", 300);
        }
      }
    }
  }

function prepare_AC_ResultList(textfield)
    {
        $('#ac_result').remove();
        $(textfield).after('<div id="ac_result"><div class="ui-widget-header"><a title="Schliessen" style="color: white;" onclick="$(\'#ac_result\').remove();$(\'.ac_spinner\').remove();; return false;" href="#"><span class="right ui-icon ui-icon-closethick"></span></a>...bitte warten. Suche läuft...<div class="clear"></div></div></div>');
        $('#ac_result').css("left", textfield.offsetLeft + (document.all ? 0 : 0) + "px");
        $('#ac_result').css("top", textfield.offsetTop + (document.all ? 0 : 0) + textfield.offsetHeight + "px");
        if(parseInt(1 + textfield.offsetWidth)<200)
          {
          $('#ac_result').width("230px");
          }
        else $('#ac_result').width(parseInt(1 + textfield.offsetWidth) + "px");
  
        $(textfield).blur(function(){
          //hidetimeout = window.setTimeout("$('#ac_result').remove();$('.ac_spinner').remove();", 300);
          return_pressed = false;
        });
  
        $(textfield).keydown(captureReturn);
  
        ac_textfield = textfield;
    }


function captureReturn(event)
  {
  if((document.all ? event.keyCode : event.which)==13) {return_pressed = true;}
  else {return_pressed = false;}
  }

function insertEntry(textfield,keystroke,item_delimiter)
  {
  if($('#ac_result span').get(ac_selectedresult)!=null)
   {
    var content = "";
    if(document.all) content = $('#ac_result span').get(ac_selectedresult).innerText;
    else content = $('#ac_result span').get(ac_selectedresult).textContent;
    jQ_autocomplete_getValue(textfield, [content,$('#ac_result span').get(ac_selectedresult).id], item_delimiter);
    }
  }

function selectEntry(textfield,keystroke)
  {
  if((keystroke==40) && ac_selectedresult<$('#ac_result li').length-1) {ac_selectedresult++;}
  if((keystroke==38) && ac_selectedresult>0) {ac_selectedresult--;}
  $('#ac_result li a').removeClass('hover');
  if($('#ac_result li a').get(ac_selectedresult)) $('#ac_result li a').get(ac_selectedresult).className = 'hover';
  textfield.focus();
  }

function startAjaxSearch(textfield,searchurl,searchstring,item_delimiter){
  $('.ac_spinner').show();
  if(active_request) active_request.abort();
  active_request = $.ajax({
    type: "POST",
    url: searchurl,
    data: 'q=' + searchstring,
    datatype: "html",
    success: function(data){
      if(!data.match('<title>')){
      $('#ac_result').html(data);
      $('#ac_result').show();
      $('.ac_spinner').remove();
      if($('#ac_result li').length>0){
        ac_selectedresult = 0;
        $('#ac_result li a').get(ac_selectedresult).className = 'hover';
      }
      $('#ac_result li').click(function(){
        window.clearTimeout(hidetimeout);
        var content = "";
        if(this.getElementsByTagName("span").length>0)
            {
            if(document.all) content = this.getElementsByTagName("span")[0].innerText;
            else content = this.getElementsByTagName("span")[0].textContent;
            if(content!="") jQ_autocomplete_getValue(textfield, [content,this.getElementsByTagName("span")[0].id], item_delimiter);
            }
      });
    }else{$('#ac_result').html("<div style='background:white;color:red;border:1px solid red;padding:3px;'>Es trat ein Fehler in der Suche auf, wir bitten um Entschuldigung. Versuche es später noch einmal.</div>");}
    },
    complete: function(){
      $('.ac_spinner').remove();
    }
  });
}

function update_ac_result_items_onclick(textfield,item_delimiter)
    {
    $('#ac_result li').click(function(){
        window.clearTimeout(hidetimeout);
        var content = "";
        if(this.getElementsByTagName("span").length>0)
            {
            if(document.all) content = this.getElementsByTagName("span")[0].innerText;
            else content = this.getElementsByTagName("span")[0].textContent;
            if(content!="") jQ_autocomplete_getValue(textfield, [content,this.getElementsByTagName("span")[0].id], item_delimiter);
            }
      });
    }


/* <<< auto-completer */
/*--------------------*/

function jQ_setHeightofLockscreen()
    {
    var innerh = window.innerHeight;
    var wih = document.lastChild.lastChild.offsetHeight;
    if(document.all) {wih = document.body.offsetHeight;}
    if(wih<innerh) {wih = innerh;}
    $('#lockscreen_background').height(wih);
    }

function jQ_insertTag(id,tag,delimiter)
  {
  if($(id).val().length<2) {$(id).val(tag);}
  else if($(id).val().indexOf(tag)==-1) {$(id).val($(id).val()+delimiter+tag);}
  }

function jQ_checkTagSyntax(inputfield,delimiter)
  {
  var usertags = inputfield.value.split(delimiter);
  var j = 0;
  for(var i=0;i<usertags.length;i++)
    {
    usertags[j] = usertags[i].replace(/[^a-zA-Z_0-9\s\-\.äöüÖÄÜßéèáàçå]+/,delimiter);
    if(usertags[j].length>0) {j++;}
    }
  var resultstring = usertags.join(delimiter);

  //kicks out doubles
  resultstring = resultstring.replace(delimiter+delimiter,delimiter);

  //if resultstring is not identical to delimiter, insert
  if(resultstring!=delimiter) {inputfield.value = resultstring;}
  else {inputfield.value = '';}
  }

function jQ_removeDelimatEnd(inputfield,delimiter)
  {
  jQ_checkTagSyntax(inputfield,delimiter);
  jQ_checkTagSyntax(inputfield,delimiter);
  jQ_checkTagSyntax(inputfield,delimiter);
  jQ_checkTagSyntax(inputfield,delimiter);
  var resultstring = inputfield.value;
  resultstring = resultstring.replace(eval("/("+delimiter+")*$/"),'');
  //if(resultstring.substr(-(delimiter.length),delimiter.length)==delimiter) {resultstring = resultstring.substr(0,resultstring.length-delimiter.length);}
  inputfield.value = resultstring;
  }

function jQ_load_Partial_to_Dialog(id, url, titel){
  $(id).html('<center><br/><br/><img src="/images/spinner.gif"/><br/><br/></center>');
  $(id).load(url);
  if($(id).dialog({
     width: 450,
     title: titel,
     resizable: false,
     modal: false
     }))
    {}
    $(id).dialog('open');
   
}

function jQ_show_HTML_in_Dialog(id, htmlcode, titel){
  $(id).html(htmlcode)
  if($(id).dialog({
    width: 450,
    title: titel,
    resizable: false,
    modal: false
    }))
    {}
  $(id).dialog('open');
}

function jQ_send_Form_over_Ajax(id, myurl, form, method){
  if (!return_pressed) {
    var formdata = null;

    if(id.indexOf('ajaxstatus_')!=-1)
      {
      if(id.indexOf('ajaxstatus_green_')!=-1) {$(id).append('<img src="/images/spinner_green3_kl.gif"/>');}
      else if(id.indexOf('ajaxstatus_white_')!=-1) {$(id).append('<img src="/images/spinner_white.gif"/>');}
      else {$(id).css("opacity","0.5").prepend('<img src="/images/spinner_kl.gif" class="absolute"/>');}
      }
    else if($(id+' form .button').length>0) {jQ_makeButtonSpin($(id+' form .button').eq(0));}
    else if($(id+' .button').length>0) {jQ_makeButtonSpin($(id+' .button').eq(0));}

    if(method === undefined) method = 'POST';
    
    if(method == 'get' || method == 'GET')
        {
        $.get(myurl, $(form).serializeArray(), function(data){if(id!=''){$(id).html(data);$(id).css("opacity","1");}});
        }
    else
        {
        $.ajax({
            type: method,
        url: myurl,
        data: $(form).serializeArray(),
        dataType: 'html',
        success: function(data){
            if(id!='')
                {
                $(id).html(data);
                $(id).css("opacity","1");
                }
            }
        });
        }
  }
}

function jQ_deleteItem(id, sender, auth_token, confirm_question){
  if (window.confirm(confirm_question)) {
    $(sender).html('<img src="/images/spinner_kl.gif"/>');

    $.ajax({
      type: 'DELETE',
      url: sender.href,
      data: auth_token,
      dataType: 'html',
      success: function(data){
        $(id).fadeOut();
        $(id).remove();
        //$(id).html(data);
      }
    });
  }
}

function jQ_send_delete_request(id, sender, auth_token, confirm_question){
	  if (window.confirm(confirm_question)) {
	    $(sender).html('<center><img src="/images/spinner_green_kl.gif"/></center>');
	    $.ajax({
	      type: 'DELETE',
	      url: sender.href,
	      data: auth_token,
	      dataType: 'html',
	      success: function(data){
	        $(id).html(data);
	      }
	    });
	  }
	}



function socialbookmark(target)
  {
  var doc   = encodeURIComponent(location.href);
  var title = encodeURIComponent(document.title);
  switch(target)
    {
    case 'delicious':
      window.open('http://del.icio.us/post?url='+doc+'&title='+title);
      break;
    case 'mrwong':
      window.open('http://www.mister-wong.de/index.php?action=addurl&bm_url='+doc+'&bm_description='+title);
      break;
    case 'blinkList':
      window.open('http://www.blinklist.com/index.php?Action=Blink/addblink.php&Description=&Url='+doc+'&Title='+title);
      break;
    case 'yahoo':
      window.open('http://myweb2.search.yahoo.com/myresults/bookmarklet?u='+doc+'&t='+title);
      break;
    case 'yigg':
      window.open('http://yigg.de/neu?exturl='+doc+'&exttitle='+title);
      break;
    case 'furl':
      window.open('http://www.furl.net/storeIt.jsp?u='+doc+'&t='+title);
      break;
    case 'oneview':
      window.open('http://beta.oneview.de:80/quickadd/neu/addBookmark.jsf?URL='+doc+'&title='+title);
      break;
    case 'folkd':
      window.open('http://www.folkd.com/submit/page/'+doc);
      break;
    case 'linkarena':
      window.open('http://linkarena.com/bookmarks/addlink/?url='+doc+'&title='+title+'&desc=&tags=');
      break;
    case 'google':
      window.open('http://www.google.com/bookmarks/mark?op=add&hl=de&bkmk='+doc+'&title='+title);
      break;
    case 'webnews':
      window.open('http://www.webnews.de/einstellen?url='+doc+'&title='+title);
      break;
    };
  }

/* Forum */

var EditForm = {
  init: function(postId) {
    $('#edit-post-' + postId + '_spinner').show();
    this.clearReplyId();
  },

  setReplyId: function(postId) {
    $('#edit').attr('post_id', postId.toString());
    $('#post_' + postId + '-row').addClassName('editing');
    if($('#reply')) {$('#reply').hide();}
  },

  clearReplyId: function() {
    var currentId = this.currentReplyId();
    if(!currentId || currentId == '') {return;}

    var row = $('post_' + currentId + '-row');
    if(row) {row.removeClassName('editing');}
    $('#edit').attr('post_id', '');
  },

  currentReplyId: function() {return $('#edit').attr('post_id');},

  isEditing: function(postId) {
    if(this.currentReplyId() == postId.toString())
      {
      $('#edit').show();
      $('#edit_post_body').get(0).focus();
      return true;
      }
    return false;
  },

  cancel: function() {
    this.clearReplyId();
    $('#edit').hide();
  }
};

var ReplyForm = {init : function() {EditForm.cancel();$('#reply').toggle();$('#post_body').get(0).focus();}};


function mark_for_destroy(e)
  {
  $(e).next('.should_destroy').val(1);
  $(e).parent().parent().parent('.milestone').remove();
  }

  
function set_target(obj,linktarget) {obj.target = linktarget;}


/***** for bodycoach ******/

function check_100p()
    {
    var comp_fields = ['protein_percent','carbohydrate_percent','fat_percent','water_percent'];
    var prefix = 'diary_item_';
    //check single fields
    var sum = 0.0;
    var temp_val = 0.0;
    for(var i=0;i<comp_fields.length;i++)
        {
        temp_val = parseFloat($('#'+prefix+comp_fields[i]).val());
        if(temp_val) sum += temp_val;
        if(temp_val>100.0) $('#'+prefix+comp_fields[i]).css('border-color','red');
        else $('#'+prefix+comp_fields[i]).css('border-color','black');
        }
    //check sum
    if(sum>101.0) $('#percent_warning').show();
    else $('#percent_warning').hide();
    
    }

function balance_components(obj)
    {
    if(parseFloat(obj.value)>100.0) obj.value = 100;
    if(parseFloat(obj.value)<0.0) obj.value = 0;
    var prefix = 'diary_item_';
    var comp_fields = ['protein_percent','carbohydrate_percent','fat_percent'];
    var all_fields_empty = true;
    var rest = 100.0;
    for(var i=0;i<comp_fields.length;i++)
        {
        if(parseFloat($('#'+prefix+comp_fields[i]).val())) {all_fields_empty=false;rest -= parseFloat($('#'+prefix+comp_fields[i]).val());}
        }
    if(all_fields_empty){$('#'+prefix+'water_percent').val('');$('#show_water_percent').html('');}
    else{
    if(rest<0) rest = 0;
    if(rest>100) rest = 100;
    $('#'+prefix+'water_percent').val(rest);
    $('#show_water_percent').html(rest+' g');
    }
    check_100p();
    }

