
/**
 * initialize soft scrolling for links with css class "scroll-link"
 * @see http://css-tricks.com/snippets/jquery/smooth-scrolling/
 * @returns {undefined}
 */
function initSoftscroll(){
    $(function() {
      // $('a[href*=#]:not([href=#])').click(function() {
      $('a.scroll-link').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
          var target = $(this.hash);
          target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
          if (target.length) {
            $('html,body').animate({
              scrollTop: target.offset().top - 70
            }, 300);
            return false;
          }
        }
      });
    });
}

function showModalMessage(sMessage){
   $('#divmodalmessage').html(sMessage);
   $('#divmodal').show();
}
function showIdAsModalMessage(sId){
   var o=$('#'+sId);
   var sHtml='<a href="#" onclick="return hideModalMessage()" class="btn btn-danger" style="float:right"> X </a>' 
           + o.html()
           + '<hr><a href="#" onclick="return hideModalMessage()" class="btn btn-primary"><i class="fa fa-check"></i> OK </a>'
            ;
   $('#divmodalmessage').html(sHtml);
   $('#divmodal').show();
   return false;
}   

function hideModalMessage(){
   $('#divmodal').hide();
   return false;
}

// ----------------------------------------------------------------------
// general init in each page
// ----------------------------------------------------------------------

$(document).ready(function() {
    initSoftscroll();
    // $(".optionName").popover({trigger: "hover"});
    // $("#content").hide().fadeIn(300);
});


// ----------------------------------------------------------------------
// action log
// ----------------------------------------------------------------------

/**
 * get filtered action log table
 * @returns {undefined}
 */
function updateActionlog(){
    var sUrlBase="/webservice/?class=Actionlog&action=getLogs&type=json&args=";
    var aArgs={};

    var aFilteritems=["project", "where", "order", "limit"];
    var aTableitems=["id", "time", "loglevel", "ip", "user", "project", "action", "message"];
    
    // --- create query url
    
    for (i=0; i<aFilteritems.length; i++){
        sValue=$('#select' + aFilteritems[i]).val();
        if(sValue){
            aArgs[aFilteritems[i]]=sValue;
        }
    }
    
    var sWhere='';
    for (j=0; j<aTableitems.length; j++){
        sValue=$('#selectWhere' + aTableitems[j]).val();
        if(sValue){
            if (sWhere){
                sWhere+' AND ';
            }
            sWhere+='`'+aTableitems[j]+'`'+sValue;
        }
    }
    if (sWhere) {
        aArgs["where"]=sWhere;
    }

    // --- get data

    var sUrl=sUrlBase+'['+JSON.stringify(aArgs)+']';
    $.post( sUrl, function( aData ) {
        var sHtml='';
        
        // --- generate output
        if (aData.length && aData[0]["id"]){
            for (i=0; i<aData.length; i++){
                sHtml+='<tr class="tractionlogs loglevel-'+aData[i]["loglevel"]+' '+aData[i]["project"]+'">';
                for (j=0; j<aTableitems.length; j++){
                    sHtml+='<td>'+aData[i][aTableitems[j]]+'</td>';
                }
                sHtml+='</tr>';
            }
        }
        
        if (!sHtml){
            sHtml=sMsgNolog; // variable is set in actionlog.class.php
        } else {
            sHead='';
            for (j=0; j<aTableitems.length; j++){
                sHead+='<th>'+aTableitems[j]+'</th>';
            }
            sHead='<thead><tr>'+sHead+'</tr></thead>';
            sHtml='<table class="table table-condensed">'+sHead+'<tbody>'+sHtml+'</tbody></table>';
        }
        $('#tableLogactions').html(sHtml);
        filterLogTable();
    });
    
}
/**
* filter table with action logs by filtertext (input field)
*/
function filterLogTable(){
    var sSearch=$("#efilterlogs").val();
    var Regex = new RegExp(sSearch, "i");
    $(".tractionlogs").each(function() {
        sVisible="none";
        if ( Regex.exec(this.innerHTML)) {
            sVisible="";
        }
        $(this).css("display", sVisible);
    });
    return false;
}

// ----------------------------------------------------------------------
// tables
// ----------------------------------------------------------------------
var localStoreTablefilter="tblvalue" + location.pathname;


// http://blog.mastykarz.nl/jquery-regex-filter/
jQuery.extend(
        jQuery.expr[':'], {
    regex: function (a, i, m) {
        var r = new RegExp(m[3], 'i');
        return r.test(jQuery(a).text());
    }
}
);

/*
 highlight v4
 Highlights arbitrary terms.
 
 <http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html>
 
 MIT license.
 
 Johann Burkard
 <http://johannburkard.de>
 <mailto:jb@eaio.com>
 */

jQuery.fn.highlight = function (pat) {
    function innerHighlight(node, pat) {
        var skip = 0;
        if (node.nodeType == 3) {
            var pos = node.data.toUpperCase().indexOf(pat);
            if (pos >= 0) {
                var spannode = document.createElement('span');
                spannode.className = 'highlight';
                var middlebit = node.splitText(pos);
                var endbit = middlebit.splitText(pat.length);
                var middleclone = middlebit.cloneNode(true);
                spannode.appendChild(middleclone);
                middlebit.parentNode.replaceChild(spannode, middlebit);
                skip = 1;
            }
        }
        else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
            for (var i = 0; i < node.childNodes.length; ++i) {
                i += innerHighlight(node.childNodes[i], pat);
            }
        }
        return skip;
    }
    return this.length && pat && pat.length ? this.each(function () {
        innerHighlight(this, pat.toUpperCase());
    }) : this;
};

jQuery.fn.removeHighlight = function () {
    return this.find("span.highlight").each(function () {
        this.parentNode.firstChild.nodeName;
        with (this.parentNode) {
            replaceChild(this.firstChild, this);
            normalize();
        }
    }).end();
};


/**
 * add a filter form to a table
 * @returns {undefined}
 */
function addFilterToTable(){
    var sValue=localStorage.getItem(localStoreTablefilter) ? localStorage.getItem(localStoreTablefilter) : '';
    var sForm='<form class="pure-form">\n\
        <fieldset>\n\
            <label for="eFilter">\n\
                <i class="fa fa-filter"></i> Tabelle filtern\n\
            </label>\n\
            <input type="text" id="eFilter" size="40" name="q" placeholder="Suchbegriff..." value="'+sValue+'" onkeypress="filterTable(this);" onkeyup="filterTable(this);" onchange="filterTable(this);">\n\
            <button class="pure-button" onclick="$(\'#eFilter\').val(\'\'); filterTable(); return false;"><i class="fa fa-times"></i> </button>\n\
            <span id="filterinfo"></span>\n\
        </fieldset>\n\
        </form><div style="clear: both;"></div>';
    $(sForm).insertBefore($("table").first());
}


/**
 * callback ... filter the table
 * use addFilterToTable() before.
 * @returns {undefined}
 */
function filterTable() {
    var filter = $('#eFilter').val();
    localStorage.setItem(localStoreTablefilter, filter);
    $("table").removeHighlight();
    if (filter) {
        $("tr:regex('" + filter + "')").show();
        $("tr:not(:regex('" + filter + "'))").hide();
        $("tr").first().show();

        $("td").highlight(filter);
    } else {
        $("td").removeHighlight();
        $('tr').show();
    }

    var sInfo = '';
    var iVisible = -1; // 1 abziehen wg. tr der ersten Zeile
    $("tr").each(function () {
        if ($(this).css('display') != 'none') {
            iVisible++;
        }
    });

    sInfo = (iVisible == ($("tr").length - 1))
            ? "ges.: <strong>" + ($("tr").length - 1) + "</strong> Eintr&auml;ge"
            : "<strong>" + iVisible + "</strong> von " + ($("tr").length - 1) + " Eintr&auml;gen"
            ;
    $('#filterinfo').html(sInfo);

}
