/**
 * Some JavaScript functions used in the admin backend
 *
 * @author    Thorsten Rinne <thorsten@phpmyfaq.de>
 * @author    Periklis Tsirakidis <tsirakidis@phpdevel.de>
 * @author    Matteo Scaramuccia <matteo@scaramuccia.com>
 * @author    Minoru TODA <todam@netjapan.co.jp>
 * @author    Lars Tiedemann <php@larstiedemann.de>
 * @since     2003-11-13
 * @copyright 2003-2008 phpMyFAQ Team
 * @version   CVS: $Id: functions.js,v 1.7 2008/06/24 11:04:35 paul_guhl Exp $
 *
 * The contents of this file are subject to the Mozilla Public License
 * Version 1.1 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 */

function Picture(pic,title,width,height)
{
    popup = window.open(pic, title, 'width='+width+', height='+height+', toolbar=no, directories=no, status=no, scrollbars=no, resizable=yes, menubar=no');
    popup.focus();
}

function checkAll(checkBox)
{
    var v = checkBox.checked;
    var f = checkBox.form;
    for (var i = 0; i < f.elements.length; i++) {
        if (f.elements[i].type == "checkbox") {
            f.elements[i].checked = v;
            }
        }
}

function addEngine(uri, name, ext, cat)
{
    if ((typeof window.sidebar == "object") && (typeof window.sidebar.addSearchEngine == "function")) {
        window.sidebar.addSearchEngine(uri+"/"+name+".src", uri+"/images/"+name+"."+ext, name, cat);
    } else {
        alert('Mozilla Firefox, Mozilla or Netscape 6 or later is needed to install the search plugin!');
    }
}

function focusOnUsernameField()
{
    if (document.getElementById('faqusername')) {
        document.getElementById('faqusername').focus();
    }
}

function focusOnSearchField()
{
    // customizing IE5: method focus apparently not supported here???
    // touble line: document.getElementById('suchbegriff').focus();
    // TODO try to reactivate as soon as design works out
    if(navigator.appVersion.indexOf("MSIE 5") > -1) {
        return;
    }
    if (document.getElementById('searchfield')) {
        document.getElementById('searchfield').focus();
    }
    if (document.getElementById('suchbegriff')) {
        document.getElementById('suchbegriff').focus();
    }
    if (document.getElementById('instantfield')) {
        document.getElementById('instantfield').focus();
    }
}

/**
 * showhideCategory()
 *
 * Displays or hides a div block
 *
 * @param    string
 * @return   void
 * @access   public
 * @since    2006-03-04
 * @author   Thorsten Rinne <thorsten@phpmyfaq.de>
 */
function showhideCategory(id)
{
    if (document.getElementById(id).style.display == 'none') {
        document.getElementById(id).style.display = 'block';
    } else {
        document.getElementById(id).style.display = 'none';
    }
}

/**
* deletes all options from given select-object.
*
* @access public
* @author Lars Tiedemann, <php@larstiedemann.de>
* @param select
* @return void
*/
function select_clear(select)
{
    while (select.length > 0) {
        select.remove(0);
    }
}

/**
* adds an option to the given select-object.
*
* @access public
* @author Lars Tiedemann, <php@larstiedemann.de>
* @param select node
* @param string
* @param text node
* @param string
* @return void
*/
function select_addOption(select, value, content, classValue)
{
    var opt;
    opt = document.createElement("option");
    opt.value = value;
    if (classValue) {
        opt.className = classValue;
    }
    opt.appendChild(content);
    select.appendChild(opt);
}

/**
* selects all list options in the select with the given ID.
*
* @access public
* @author Lars Tiedemann, <php@larstiedemann.de>
* @param string
* @return void
*/
function select_selectAll(select_id)
{
    var select_options = document.getElementById(select_id).options;
    for (var i = 0; i < select_options.length; i++) {
        select_options[i].selected = true;
    }
}

/**
* unselects all list options in the select with the given ID.
*
* @access public
* @author Lars Tiedemann, <php@larstiedemann.de>
* @param string
* @return void
*/
function select_unselectAll(select_id)
{
    var select_options = document.getElementById(select_id).options;
    for (var i = 0; i < select_options.length; i++) {
        select_options[i].selected = false;
    }
}

/**
 * checks all checkboxes in form with the given ID.
 *
 * @access  public
 * @author  Lars Tiedemann, <php@larstiedemann.de>
 * @param   string
 * @return  void
 */
function form_checkAll(form_id)
{
    var inputElements = document.getElementById(form_id).getElementsByTagName('input');
    for (var i = 0, ele; ele = inputElements[i]; i++) {
        if (ele.type == "checkbox") {
            ele.checked = true;
        }
    }
}

/**
 * unchecks all checkboxes in form with the given ID.
 *
 * @access  public
 * @author  Lars Tiedemann, <php@larstiedemann.de>
 * @param   string
 * @return  void
 */
function form_uncheckAll(form_id)
{
    var inputElements = document.getElementById(form_id).getElementsByTagName('input');
    for (var i = 0, ele; ele = inputElements[i]; i++) {
        if (ele.type == "checkbox") {
            ele.checked = false;
        }
    }
}

/**
* returns the text content of a child element.
*
* When having a dom structure like this:
* <item id="1">
*   <name>Item Name</name>
*   <value>Text Value</value>
* </item>
* text_getFromParent(document.getElementById(1), "name")
* would return "Item Name".
*
* @access public
* @author Lars Tiedemann, <php@larstiedemann.de>
* @param Object select
* @return void
*/
function text_getFromParent(parentObject, childElement)
{
    var result = "";
    result = parentObject.getElementsByTagName(childElement)[0];
    if (result) {
        if (result.childNodes.length > 1) {
            return result.childNodes[1].nodeValue;
        } else {
            if (result.firstChild) {
                return result.firstChild.nodeValue;
            } else {
                return "";
            }
        }
    } else {
        return "n/a";
    }
}

/**
* deletes all rows from given table-object.
*
* @access public
* @author Lars Tiedemann, <php@larstiedemann.de>
* @param table
* @return void
*/
function table_clear(table)
{
    while (table.rows.length > 0) {
        table.deleteRow(0);
    }
}

/**
* inserts a new row into the given table at the given position.
*
* @access public
* @author Lars Tiedemann, <php@larstiedemann.de>
* @param table
* @param int
* @param node
* @param node
* @return void
*/
function table_addRow(table, rowNumber, col1, col2)
{
    var td1;
    var td2;
    var tr;
    td1 = document.createElement("td");
    td1.appendChild(col1);
    td2 = document.createElement("td");
    td2.appendChild(col2);
    tr = table.insertRow(rowNumber);
    tr.appendChild(td1);
    tr.appendChild(td2);
}

/**
* Function to get a pretty formatted output of a variable
*
* NOTE: Just for debugging!
*
* @param    string
* @return   void
* @access   public
* @since    2005-12-26
* @author   Thorsten Rinne <thorsten@phpmyfaq.de>
*/
function pmf_dump(data)
{
    var s = '';
    for(idx in data){
        s += idx + '('+typeof data[idx]+'): ' + data[idx]+'\n';
    }
    document.write('<pre>' + s + '</pre>');
}

/**
* Hide a <div> container
*
* @param    string
* @return   void
* @access   public
* @since    2006-01-07
* @author   Thorsten Rinne <thorsten@phpmyfaq.de>
*/
function hide(id)
{
    document.getElementById(id).style.display = 'none';
}

/**
* Show a <div> container
*
* @param    string
* @return   void
* @access   public
* @since    2006-01-07
* @author   Thorsten Rinne <thorsten@phpmyfaq.de>
*/
function show(id)
{
    document.getElementById(id).style.display = 'block';
}

function switchLanguage(language)
{
  document.getElementById('language').value = language;
  document.frmLang.submit();
}

// transfers the item from identified source box to identified target box
function transferOptionBySelect(source_select, target_select)
{
    if(source_select && target_select) {
        var selection_index = source_select.options.selectedIndex;
        if(selection_index > -1) {
            // reassign the option object
            target_select.options[target_select.options.length]
            = new Option(source_select.options[selection_index].text,
            source_select.options[selection_index].value,
            false,
            true);
            source_select.options[selection_index] = null;
        }
    }
}

// creation options list in specified select box
function fillSelectBox(select_object, options_list)
{
    if (!select_object || 0 == options_list.length) return;
    // flush existing items
    select_object.options.length = 0;
    // fill in
    var
    option_index = -1,
    option_count = options_list.length;
    while(++option_index < option_count) {
        select_object.options[option_index]
        = new Option(options_list[option_index][1],
        options_list[option_index][0],
        false,
        true);
    }
}

function getRecordIdFromSelBox(box_name)
{
    // box found
    if(document.getElementById(box_name)) {

        var indx = document.getElementById(box_name).options.selectedIndex;
        if(indx > -1) {
            return document.getElementById(box_name).options[indx].value;
        }
        return 0;
    }
    return 0;
}

function shiftLeft(id, lang)
{
    ajaxUnAssignFaqRelation(id, getRecordIdFromSelBox('target'), lang);
    transferOptionBySelect(document.getElementById('target'),
                           document.getElementById('source'));
}

function shiftRight(id, lang)
{
    ajaxAssignFaqRelation(id, getRecordIdFromSelBox('source'), lang);
    transferOptionBySelect(document.getElementById('source'),
                           document.getElementById('target'));
}


function ajaxAssignFaqRelation(id_left, id_right, lang)
{
    var url = 'index.php';
    var pars = 'action=ajax&ajax=crosslinking&id_left=' + id_left + '&id_right=' + id_right + '&lang=' + lang + '&lookup=1&doassign=1';
    var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onComplete: ajaxOnDemandVerify_success, onFailure: ajaxOnDemandVerify_failure} );
    function ajaxOnDemandVerify_success(XmlRequest)
    {
    }
    function ajaxOnDemandVerify_failure(XmlRequest)
    {
    }
}

function ajaxUnAssignFaqRelation(id_left, id_right, lang)
{
    var url = 'index.php';
    var pars = 'action=ajax&ajax=crosslinking&id_left=' + id_left + '&id_right=' + id_right + '&lang=' + lang + '&lookup=1&doassign=0';
    var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onComplete: ajaxOnDemandVerify_success, onFailure: ajaxOnDemandVerify_failure} );


    function ajaxOnDemandVerify_success(XmlRequest)
    {
    }

    function ajaxOnDemandVerify_failure(XmlRequest)
    {
    }
}

function highlightOnLoad(searchTerms)
{
  // Get search string
  if (searchTerms != 'NaN') {
    // Starting node, parent to all nodes you want to search
    // Make sure we highlight only the search results.
    var SearchLinks = document.getElementById('search_result').getElementsByTagName("a");

    // Split search terms on '|' and iterate over resulting array
    var searchTerms = searchTerms.split('|');
    for(var j in SearchLinks) {
        for (var i in searchTerms) 	{
          // The regex is the secret, it prevents text within tag declarations to be affected
          highlightTextNodes(SearchLinks[j], searchTerms[i], i);
        }
    }
  }
}

function highlightTextNodes(element, regex, termid) {
    if(element && element.innerHTML) {
        var tempinnerHTML = element.innerHTML;
        element.innerHTML = tempinnerHTML.replace(regex,'<span class="highlighted term'+termid+'">'+regex+'</span>');
    }
}

function trigSearch()
{
    document.getElementById('search').value = document.getElementById('srch').value;
    document.frmSearch.submit();
}

function searchPrompt()
{
    if(navigator.appVersion.indexOf("MSIE 5") > -1) {
        document.getElementById('srch').value
            = prompt("Search", "keyword...");
    }
}

function hookInput(KbEvent)
{
    if(navigator.appVersion.indexOf("MSIE 5") > -1) {
        var keynum;
        if(window.event) // IE
        {
            keynum = KbEvent.keyCode;
        }
        else if(KbEvent.which) // Netscape/Firefox/Opera
        {
            keynum = KbEvent.which;
        }
        return String.fromCharCode(keynum);
    }
    return '';
}

function remapSubmit()
{
    document.getElementById('rubrik').value = document.getElementById('rubrik2').value;
    document.getElementById('name').value = document.getElementById('name2').value;
    document.getElementById('email').value = document.getElementById('email2').value;
    document.getElementById('question').value = document.getElementById('question2').value;
    document.getElementById('captcha').value = document.getElementById('captcha2').value;
    document.frmComment.submit();
}
