/**
 * Created by samuel on 23/07/2014.
 */
function sortTable(tb, n) {
    var iter = 0;
    while (!tb.tagName || tb.tagName.toLowerCase()
        != "table") {
        if (!tb.parentNode) return;
        tb = tb.parentNode;
    }
    if (tb.tBodies && tb.tBodies[0]) tb = tb.tBodies[0];

    /* Tri par sélection
     */
    var reg = /^\d+(\.\d+)?$/g;
    var index = 0, value = null, minvalue = null;
    for (var i = tb.rows.length - 1; i >= 0; i -= 1) {
        minvalue
            = value = null;
        index = -1;
        for (var j = i; j >= 0; j -= 1) {
            value = tb.rows[j].cells[n].firstChild.nodeValue;
            if (!isNaN(value)) value = parseFloat(value);
            if
                (minvalue == null || value < minvalue) {
                index = j;
                minvalue = value;
            }
        }

        if (index != -1) {
            var row = tb.rows[index];
            if (row) {
                tb.removeChild(row);
                tb.appendChild(row);
            }
        }

    }
    //fin
}

function fix_apo(str) {
    a = "'";
    b = "\'";
    return str_replace2(str, a, b);
}

function str_replace2(SRs, SRt, SRu) {
    /*
     **  Replace a token in a string
     **    s  string to be processed
     **    t  token to be found and removed
     **    u  token to be inserted
     **  returns new String
     */
    SRRi = SRs.indexOf(SRt);
    SRRr = '';
    if (SRRi == -1) return SRs;
    SRRr += SRs.substring(0, SRRi) + SRu;
    if (SRRi + SRt.length < SRs.length)
        SRRr += str_replace2(SRs.substring(SRRi + SRt.length, SRs.length), SRt, SRu);
    return SRRr;
}

function sendData(param, page, champ, context) {

    if (document.all) {
        // Internet Explorer
        var XhrObj = new ActiveXObject("Microsoft.XMLHTTP");
    }// fin if
    else {
        // Mozilla
        var XhrObj = new XMLHttpRequest();
    } // fin else
    // définition de l'endroit d'affichage:
    var content = document.getElementById(champ);

    // add a class xhr to input field where the request is launched
    if (!context.className.match(/xhr/i)) {
        context.className = context.className + ' xhr';
    }

    XhrObj.open("POST", page);
    // Ok pour la page cible
    XhrObj.onreadystatechange = function () {
        if (XhrObj.readyState == 4 && XhrObj.status == 200) {
            document.body.style.cursor = "auto";

            // if field is from statut function
            if (context.parentElement.id.match(/_sel_stat_/g)) {
                $(context).parent().hide(); 
                $('.'+champ).html(XhrObj.responseText);
                $('.text_'+champ).fadeIn(1000);
                setTimeout(function() { $('.text_'+champ).fadeOut(1000); }, 3000);
            }

            //check if input CA VAD is hidden for set the value for CA, if a pure player
            if($("#input-ctrl-n-3").parents('table').hasClass('hidden')){
                if($(context).hasClass('input-ctrl-n-1')){
                    $("#input-ctrl-n-3").val($(context).val());
                }
            }

            // call back
            if (content != null) {
                // load content
                content.innerHTML = XhrObj.responseText;

            }
        }

        // Remove class xhr
        context.className = context.className.replace(' xhr', '');
    };
    XhrObj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    XhrObj.send(param);
}

/**
 * Call Ajax control value PanelCATotaux
 * @param param
 * @param page
 * @param champ
 * @param context
 * @param page2
 */
function sendDataControl(param, page, champ, context, page2) {

    if (document.all) {
        // Internet Explorer
        var XhrObj = new ActiveXObject("Microsoft.XMLHTTP");
    } //fin if
    else {
        // Mozilla
        var XhrObj = new XMLHttpRequest();
    } //fin else

    // définition de l'endroit d'affichage:
    var content = document.getElementById(champ);

    // add a class xhr to input field where the request is launched
    context.className = context.className + ' xhr';

    XhrObj.open("POST", page);

    // Ok pour la page cible
    XhrObj.onreadystatechange = function () {
        if (XhrObj.readyState == 4 && XhrObj.status == 200) {
            document.body.style.cursor = "auto";

            // unescape response string
            var data = XhrObj.responseText.replace(/\\"/g,'"');

            // parse json
            data = JSON.parse(data);

            // load tooltip alert data inconsistency
            if (data.status == 'ko' && data.action == 'created') {

                // send message
                alertMessageToolTip(context, 'Attention, pour information la donnée que vous avez saisie présente un écart de plus de 20% avec la dernière donnée actuellement stockée.<br/>Etes-vous certain qu’il ne s’agit pas d’une faute de frappe ?', 'top');


            } else if (data.status == 'ko' && data.action == 'modified') {

                // send message
                alertMessageToolTip(context, 'Attention, pour information la donnée que vous avez saisie présente un écart de plus de 20% avec la donnée actuellement stockée.<br/>Etes- vous certain qu’il ne s’agit pas d’une faute de frappe ?', 'top');

            }
            if(page2 != null) {
                // load call ajax save item in db
                sendData(param, page2, champ, context);
            }
        } else {
            // Remove class xhr
            context.className = context.className.replace(' xhr', '')
        }
    }

    XhrObj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    XhrObj.send(param);
}

// alert message tooltip
// selector : (jQuery obj) current selector
function alertMessageToolTip(selector, msg, position)
{
    if( $(selector).hasClass('tooltipstered')){
        $(selector).tooltipster('content',msg);
        $(selector).tooltipster('show');
    } else {
        // init tooltip
        $(selector).tooltipster({
            content: msg,
            trigger: 'custom',
            contentAsHTML: true,
            position: position,
            timer: 5000
        }).tooltipster('show');

    }


    // as soon as a key is pressed on the keyboard, hide the tooltip.
    $(selector).on('click', function(){
        $(selector).tooltipster('hide');
    });

}

