/**
 * Laden des WYSIWYG-Editors (TinyMCE)
 *
 * @author fpreusner
 */
function loadWYSIWYG() {

  tinyMCE.init({

    // Grundkonfiguration
    mode:             "textareas",
    editor_selector:   "wysiwyg",
    theme:             "advanced",
    language:          "de",
    convert_urls:     false,
    plugins:           "ibrowser,style,layer,table,advhr,advlink,emotions,iespell,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,noneditable,visualchars,nonbreaking,xhtmlxtras,template,inlinepopups",


    // Navigationselemente
    theme_advanced_buttons1:             "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontselect,fontsizeselect,|,print",
    theme_advanced_buttons2:             "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,ibrowser,link,unlink,code,|,forecolor,backcolor",
    theme_advanced_buttons3:             "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,iespell,media,advhr",

    theme_advanced_toolbar_location:     "top",
    theme_advanced_toolbar_align:       "left",
    theme_advanced_statusbar_location:   "bottom",
    theme_advanced_resizing:            false,

    // Example word content CSS (should be your site CSS) this one removes paragraph margins
    content_css : "css/word.css",

    // Drop lists for link/image/media/template dialogs
    template_external_list_url: "lists/template_list.js",
    external_link_list_url:     "lists/link_list.js",
    external_image_list_url:     "lists/image_list.js",
    media_external_list_url:     "lists/media_list.js"
  });
}

function ajaxfilemanager(field_name, url, type, win) {

  var ajaxfilemanagerurl = "../../../../js/wysiwyg/plugins/ajaxfilemanager/ajaxfilemanager.php";

  switch (type) {
    case "image":
      break;
    case "media":
      break;
    case "flash":
      break;
    case "file":
      break;
    default:
      return false;
  }

  tinyMCE.activeEditor.windowManager.open({

    url:             "../../../../js/wysiwyg/plugins/ajaxfilemanager/ajaxfilemanager.php",
    width:           782,
    height:         440,
    inline:         "yes",
    close_previous: "no"
  }, {

    window: win,
    input:   field_name
  });
}


/**
 * Laden des Contents via übergebener URL
 *
 * @author fpreusner
 */
function ajaxLoadContent(element_id, route, send_method) {

  new Ajax.Updater(element_id, route, { method:       send_method,
                                        asynchronous: false,
                                        evalScripts:   true,

                                        /*
                                         * Info-Box wird geladen
                                         */
                                        onComplete: loadInfoButtons
                                      });
}

/**
 * Laden der Userbox im Header
 *
 * @author fpreusner
 */
function ajaxRequestUserBox(route) {

  new Ajax.Request(route, {
    method: 'get',

    onSuccess: function(transport) {

      var response = transport.responseText;
      $('user_box').innerHTML = response;
      Effect.SlideDown('user_box', { duration: 0.6 });
    },

    onFailure: function() { }
  });
}

/**
 * sendet einen Request aus eienr Modalbox
 *
 * @author fpreusner
 */
function mbSendRequest(route) {

  new Ajax.Request(route, {
    method: 'post',

    onSuccess: function(transport) {
      response = transport.responseText;

      button               = document.createElement('img');
      button.src           = '/images/buttons/close_btn.png';
      button.style.cursor = 'pointer';
      button.onclick       = function() { window.location.href=window.location.href; };

      $('modalbox_status_notification').innerHTML     = response;
      $('modalbox_status_notification').style.display = 'block';

      $('modalbox_buttons').innerHTML = '';
      $('modalbox_buttons').appendChild(button);
    },

    onFailure: function() { }
  });
}

/**
 * Beim Laden der Seite ausführen
 *
 * @author maichele
 * @author fpreusner
 */
function load() {

  /*
   * Frage Eingabefelder verarbeiten
   */
  el_quest_input           = $('question_input');
  el_quest_desc            = $('question_desc_input');


  if(el_quest_input != null && el_quest_input != 'undefined') {

    if($('question_input').innerHTML != 'Deine Frage:') {

      el_quest_input.innerHTML = $('question_input').innerHTML;
    }else {

      el_quest_input.innerHTML = 'Deine Frage:';
    }

    el_quest_input.onclick   = updateQuestInput;
    el_quest_input.onblur    = updateQuestInput;

    el_quest_desc.value      = 'Mehr Infos zu deiner Frage:';
    el_quest_desc.onclick    = updateQuestDesc;
    el_quest_desc.onblur     = updateQuestDesc;


  }

  el_quest_sms_input  = $('question_sms_text');
  el_quest_sms_mobile = $('question_sms_mobile');

  if(el_quest_sms_input != null && el_quest_sms_input != 'undefined') {

    el_quest_sms_input.innerHTML = 'Deine Frage*:';
    el_quest_sms_input.onclick   = updateQuestSMSinput;
    el_quest_sms_input.onblur    = updateQuestSMSinput;

    el_quest_sms_mobile.value      = 'Deine Handynummer:';
    el_quest_sms_mobile.onclick    = updateQuestSMSmobile;
    el_quest_sms_mobile.onblur     = updateQuestSMSmobile;
  }

  /*
   * Antwort schreiben Quelle-Eingabefeld verarbeiten
   */
  el_answer_source = $('answer_source');

  if(el_answer_source != null && el_answer_source != 'undefined') {

    el_answer_source.value   = 'Quelle (Beispiel: http://www.smsguru.de)';
    el_answer_source.onclick = updateAnswerSourceInput;
    el_answer_source.onblur  = updateAnswerSourceInput;
  }

  /*
   * Info-Box wird geladen
   */
  loadInfoButtons();

  /*
   * Facebox-Autoloader
   */
  el_auto_display = $('facebox_auto_display');

  if (el_auto_display != null && el_auto_display != 'undefined') {

    var welcome_box = new Facebox;
    welcome_box.click_handler(el_auto_display);
  }
}

/*
 * Frage Input Feld zurücksetzen falls nötig
 *
 * @author maichele
 */
function updateQuestInput() {

  if ($('question_input').value == '') {

    $('question_input').value = 'Deine Frage:';
  } else if ($('question_input').value == 'Deine Frage:') {

    $('question_input').value = '';
  }
}

/*
 * Frage Beschreibung Textarea zurücksetzen falls nötig
 *
 * @author maichele
 */
function updateQuestDesc() {

  if ($('question_desc_input').value == '') {

    $('question_desc_input').value = 'Mehr Infos zu deiner Frage:';
  } else if ($('question_desc_input').value == 'Mehr Infos zu deiner Frage:') {

    $('question_desc_input').value = '';
  }
}

/*
 * Frage für SMS zurücksetzen falls nötig
 *
 * @author fpreusner
 */
function updateQuestSMSinput() {

  if ($('question_sms_text').value == '') {

    $('question_sms_text').value = 'Deine Frage*:';
  } else if ($('question_sms_text').value == 'Deine Frage*:') {

    $('question_sms_text').value = '';
  }
}

/*
 * Frage SMS Handynummer Textarea zurücksetzen falls nötig
 *
 * @author fpreusner
 */
function updateQuestSMSmobile() {

  if ($('question_sms_mobile').value == '') {

    $('question_sms_mobile').value = 'Deine Handynummer:';
  } else if ($('question_sms_mobile').value == 'Deine Handynummer:') {

    $('question_sms_mobile').value = '';
  }
}

/**
 * Quellenangabe der Antwort zurücksetzen falls nötig
 *
 * @author fpreusner
 */
function updateAnswerSourceInput() {

  if ($('answer_source').value == '') {

    $('answer_source').value = 'Quelle (Beispiel: http://www.smsguru.de)';
  } else if ($('answer_source').value == 'Quelle (Beispiel: http://www.smsguru.de)') {

    $('answer_source').value = '';
  }
}

/**
 * Blendet das Overlay für Hilfetexte aus
 *
 * @author sweber
 */
function hideInfoOverlay() {

  $('info_tip').style.display = 'none';
}

/**
 * Zeigt ein Overlay mit Hilfetext
 *
 * @author sweber
 */
function showInfoOverlay(element) {

  var p    = getAbsolutePos(element);
  var text = '';

  if($('infoboxtext_'+element.id)) {

    text = $('infoboxtext_'+element.id).value;
  }

  $('info_tip').style.display  = 'block';
  $('info_tip_text').innerHTML = (text !== '') ? text : 'Diese Information arbeiten wir derzeit für Sie aus!';
  $('info_tip').style.left     = (p.x - 32) + "px";
  $('info_tip').style.top      = (p.y > $('info_tip').scrollHeight) ? (p.y - $('info_tip').scrollHeight - 3) + "px" : ($('info_tip').scrollHeight - 3) + 'px';
}

/**
 * Fügt das onmouseout event allen infoicons hinzu
 *
 * @author sweber
 */
function loadInfoButtons() {

  info_icons = document.getElementsByClassName('info_opener');

  for(i = 0; i < info_icons.length; i++) {

    element = info_icons[i];
    element.onmouseout  = function() { hideInfoOverlay(); };
    element.onmouseover = function() { showInfoOverlay(this); };
  }
}

/**
 * Gibt die absolute Position eines Elementes zurück
 * parts taken from JSCalendar bundled with symfony
 */
function getAbsolutePos(el) {

  var SL = 0, ST = 0;
  var is_div = /^div$/i.test(el.tagName);
  if (is_div && el.scrollLeft) {

    SL = el.scrollLeft;
  }
  if (is_div && el.scrollTop) {

    ST = el.scrollTop;
  }
  var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST }

  if (el.offsetParent) {

    var tmp = this.getAbsolutePos(el.offsetParent);
    r.x += tmp.x;
    r.y += tmp.y;
  }
  return r;
}

/**
 * Absenden eines Formulares und das Ergebnis in ein
 * Element laden
 *
 * @author fpreusner
 */
function sendFormAndLoadContent(form_id, element_id, route) {

  new Ajax.Request(route, {
    method:      'post',
    parameters: $(form_id).serialize(true),
    evalScripts:  true,
    onSuccess:   function(transport) {
      $(element_id).innerHTML = transport.responseText;

      /*
       * Info-Box wird geladen
       */
      loadInfoButtons();

      window.scrollTo(0,0);
     }
  });
}

/**
 * Subnavi aktualisieren
 *
 * @author maichele
 */
function handleSubNavi(el, hide) {

  if (hide == true) {

    $('navi_overlay').style.display = 'none';
    return false;
  }

  pos = getAbsolutePos(el);

  $('navi_overlay').style.left = pos.x + 'px';
  $('navi_overlay').style.display = 'block';

  return false;
}

/**
 * Switch der Question-Box
 *
 * @author fpreusner
 */
function changeQuestionBox(who) {

  if (who == 'left') {

    $('q_tab_left').style.zIndex   = 6;
    $('q_tab_right').style.zIndex  = -1;

    $('q_normal').style.display    = 'block';
    $('q_dark').style.display      = 'none';

    $('q_info_sms_price').style.display = 'none';
  } else {

    $('q_tab_right_r').style.zIndex  = 6;
    $('q_tab_left_r').style.zIndex   = -1;

    $('q_dark').style.display      = 'block';
    $('q_normal').style.display    = 'none';

    $('q_info_sms_price').style.display = 'block';
  }
}

/**
 * Mesage Länge checken und verbleibende Zeichen aktualisieren
 *
 * @author maichele
 * @author fpreusner
 */
function checkMessageLength(element_id, remaining_element_id, limit) {

  if(!limit) {

    limit = 160;
  }

  var action_len = $(element_id).value.length;

  chars_left = limit - action_len;

  $(remaining_element_id).innerHTML = chars_left;

  if (chars_left <= 0) {

    $(element_id).value = $(element_id).value.substring(0, (limit - 1));
  }
}


/**
 * Mesage Länge checken und verbleibende Zeichen aktualisieren
 *
 * @author maichele
 * @author fpreusner
 */
function checkWgMessageLength(element_id, remaining_element_id, limit) {

  if(!limit) {

    limit = 100;
  }

  var action_len = $(element_id).value.length;

  chars_left = limit - action_len;

  $(remaining_element_id).innerHTML = chars_left;

  if (chars_left <= 0) {

    $(element_id).value = $(element_id).value.substring(0, (limit - 1));
  }
}


/**
 * Versenden des SMS-Formulars via Ajax
 *
 * @author fpreusner
 */
function sendSMSform() {

  route = $('question-form').action;


  new Ajax.Request(route, {
    method:      'post',
    parameters: $('question-form').serialize(),
    onSuccess:   function(transport) {

      $('q_dark').innerHTML = transport.responseText;
      checkMessageLength('question_sms_text', 'question-charsleft-value');
      checkErrorContainerFromSMS();
     }
  });

  $('submit').disabled = true; // avoid double clicking on submit-button
  return false;
}

/**
 * Prüft ob Fehler vorliegen und gibt diese in der
 * Facebox aus
 *
 * @author fpreusner
 */
function checkErrorContainerFromSMS() {

  if($('sms_send_error_container').innerHTML.length > 86) {

    var error_box = new Facebox;
    error_box.click_handler($('error_psydo_link'));
  }
}

/**
 * aktuelle Seite für den Loginvorgang in hidden field merken
 *
 * @author maichele
 */
function updateCurrentLoginUrl() {

  $('login_url').value = document.location.href;
}

/**
 * Drop-Down Options anzeigen oder ausblenden
 *
 * @author kscheffelmeier
 */
function showDropDownOptions() {

  if ($('drop_down_opt').style.display == 'none') {

    $('drop_down_opt').style.display  = 'block';
  } else if ($('drop_down_opt').style.display == 'block') {

    $('drop_down_opt').style.display  = 'none';
  } else {

    $('drop_down_opt').style.display  = 'block';
  }
}

/**
 * Drop-Down Options ausblenden
 *
 * @author kscheffelmeier
 */
function hideDropDownOpt(event) {

    if (event.target.id == 'question_d_btn' ||
        event.target.className == 'cat_dd_parent' ||
        event.target.id == 'question_dropdown' ||
        event.target.id == 'question_d_input') {

      return;
    }

    /*
    window.setTimeout(function() {
        if ($('drop_down_opt').style.display == 'block') {

          $('drop_down_opt').style.display  = 'none';
        }
    				}, 100);
    */
    
    // above call replaced by:
    window.setTimeout(function() {
                                 return true;
                       }, 100);
}

/**
 * Gewaehlte Drop-Down Option zurueck in das Input schreiben
 *
 * @author kscheffelmeier
 */
function selectOptionFromDropDown(elm) {

   /*
    * Option im Drop-Down anzeigen
    */
   var option                  = elm.innerHTML;
   option                      = str_replace('&raquo;', '', option);
   option                      = str_replace('&raquo ', '', option);
   option                      = str_replace('  &raquo ', '', option);
   option                      = str_replace('  &raquo ;', '', option);
   option                      = str_replace('&nbsp;', '', option);
   option                      = str_replace('&nbsp;', '', option);
   option                      = str_replace('&amp;', '&', option);
   $('question_d_input').value = option;

   /*
    * Den Kategorie-PK in das Hidden-Field  schreiben
    */
   var pk                      = str_replace('cat_d_', '', elm.id)
   $('question_d_value').value = pk;

   /*
    * Drop-Down ausblenden
    */
   $('drop_down_opt').style.display = 'none';
}

/**
 * Drop-Down Optionen mit einem Highlight versehen
 *
 * @author nschulze
 */
function highlightOptions(elm, color) {

  if (color == 'blue') {

    elm.style.backgroundImage  = 'url(\'/images/ba_sub_navi_hl_r.gif\')';
    elm.style.backgroundRepeat = 'repeat-y';
    elm.style.color            = '#1697D1';
  } else {

    elm.style.backgroundImage  = 'none';
    elm.style.backgroundRepeat = 'none';
    elm.style.color            = '#525252';
  }
}

/**
 * String ersetzen
 *
 * @author kscheffelmeier
 */
function str_replace(my_search, my_replace, my_subject) {

  return my_subject.split(my_search).join(my_replace);

}

/**
 * Anzeige der Suchoptionen für eine Frage
 *
 * @author fpreusner
 */
function toggleQuestionSpecial(element) {

  if(element.options[element.selectedIndex].value == 'question') {

    $('question_special').style.display = 'block';
  } else {

    $('question_special').style.display = 'none';
  }
}
