/*
 *   This file is part of NOALYSS.
 *
 *   NOALYSS is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   NOALYSS is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with NOALYSS; if not, write to the Free Software
 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/
/* $Revision$ */

// Copyright Author Dany De Bontridder danydb@aevalys.eu

/**
 * @file
 * javascript for searching a card
 */

/**
 * search a card an display the result into a inner box
 */
function boxsearch_card(p_dossier)
{
	try
	{
	waiting_box();
	removeDiv('boxsearch_card_div');
	var queryString="gDossier="+p_dossier+"&op=cardsearch"+"&card="+encodeURI(id$("card_search").value);
	var action = new Ajax.Request(
				  "ajax_misc.php" ,
				  {
				      method:'get', parameters:queryString,
				      onFailure:ajax_misc_failure,
				      onSuccess:function(req){
						remove_waiting_box();
                                                if (req.responseText == 'NOCONX') {
                                                    reconnect();
                                                    return;
                                                }
						var y=calcy(15);
						var div_style="position:absolute;"+";top:"+y+"px;z-index:"+get_next_layer();
						add_div({id:'boxsearch_card_div',cssclass:'inner_box',html:loading(),style:div_style,drag:true});
						id$('boxsearch_card_div').innerHTML=req.responseText;
						sorttable.makeSortable(id$('tb_fiche'));
				      }
				  }
				  );
	}catch( e)
	{
		alert_box(e.message);
	}
}
/**
 * show the ipopup with the form to search a card
 * the properties
 * @param obj
 * @param {int} obj.jrn for the ledger
 * @param {int} obj.fs route to the action
 * @param {string} obj.price for the price of the card (field to update)
 * @param {string} obj.tvaid for the tvaid of the card (field to update)
 * @param {string} obj.inp input text to update with the quickcode
 * @param {string} obj.label field to update with the name
 * @param {string} obj.ctl the id to fill with the HTML answer (ending with _content)
 * @param {int} obj.acc 1 if accounting are visible
 */
function search_card(obj)
{
    try
    {
        var gDossier=id$('gDossier').value;
        var inp=obj.inp;
        var string_to_search=id$(inp).value;
        var label=obj.label;
        var typecard=obj.typecard;
        var price=obj.price;
        var tvaid=obj.tvaid;
        var jrn=obj.jrn;
        var inactive_card=0;
        if ( obj.inactive_card) {inactive_card=obj.inactive_card.value;}
        var amount_from_type=0;
        if ( obj.amount_from_type) {
            amount_from_type=obj.amount_from_type;

        }
        if ( jrn==undefined)
        {
            if ( document.getElementById('p_jrn'))   {
		jrn=id$('p_jrn').value;
	    }
            else 	    {
		jrn=-1;
	    }
        }
        var accvis=obj.accvis;
        if ( accvis == undefined ) {
            accvis=0;
        } else {
            accvis=obj.accvis;
        }
	var query=encodeJSON({'gDossier':gDossier,
                      'inp':inp,'label':label,'price':price,'tvaid':tvaid,
                      'ctl':'search_card','op2':'fs','jrn':jrn,
                      'typecard':typecard,'query':string_to_search,'op':'card',
                      'accvis':accvis,
                      'amount_from_type':amount_from_type,
                      'inactive_card':inactive_card
                             });
	if (  document.getElementById('search_card') ) {
	    removeDiv('search_card');
	}
        

        waiting_box();


        var action=new Ajax.Request ( 'ajax_misc.php',
                                      {
                                  method:'get',
                                  parameters:query,
                                  onFailure:errorFid,
                                  onSuccess:result_card_search
                                      }
                                    );
    }
    catch(e)
    {
        alert_box('search_card failed'+e.message);
    }
}
/**
 * Display found card and let you select several to link them to an action-followup
 * @param {obj} obj form object
 * @param {obj} obj form object
 */
function action_concerned_save_card(obj)
{
    try {
        waiting_box();
        // get all data from FORM
        var query = obj.serialize();
        new Ajax.Request("ajax_misc.php", {
            method: "POST",
            parameters: query,
            onSuccess: function (req) {
                remove_waiting_box();
                var answer = req.responseXML;
                var a = answer.getElementsByTagName('ctl');
                if (a.length == 0)
                {
                    var rec = req.responseText;
                    alert_box('erreur :' + rec);
                }
                var html = answer.getElementsByTagName('code');
                var namectl = a[0].firstChild.nodeValue;
                var nodeXml = html[0];
                var code_html = getNodeText(nodeXml);
                code_html = unescape_xml(code_html);
                id$(namectl).update(code_html);
                removeDiv('search_card');
                /* if dialog box exist with list other card, then refresh it */
                if ( document.getElementById("action_concerned_list_dv") ) {
                    action_concerned_list({ag_id:obj.ag_id.value,dossier:obj.gDossier.value});
                }

            }
        });
    } catch (e)
    {

        alert_box('action_concerned_save_card' + e.message);
        return false;
    }
    return false;
}
/**
 * Display the list of other card from a followup action
 * @returns {undefined}
 */
function action_concerned_list(p_obj) {
    try {
        var action = new Ajax.Request('ajax_misc.php',
                {
                    method: 'get',
                    parameters: {gDossier: p_obj.dossier, op: 'card', 'op2': "action_concerned_list", "ag_id": p_obj.ag_id
                        ,"ctl":'action_concerned_list_dv'},
                    onFailure: errorFid,
                    onSuccess: function (req, txt)
                    {
                        try {
                            var sx = 0;
                            if (window.scrollY)
                            {
                                sx = window.scrollY + 40;
                            } else
                            {
                                sx = document.body.scrollTop + 60;
                            }
                            var div_style = "top:" + sx + "px;z-index:"+get_next_layer();
                            add_div({id: 'action_concerned_list_dv', cssclass: 'inner_box', html: "",
                                style: div_style, drag: true});
                            remove_waiting_box();
                            var answer = req.responseXML;
                            var a = answer.getElementsByTagName('ctl');
                            if (a.length == 0)
                            {
                                var rec = req.responseText;
                                alert_box('erreur :' + rec);
                            }
                            var html = answer.getElementsByTagName('code');
                            var namectl = a[0].firstChild.nodeValue;
                            var nodeXml = html[0];
                            var code_html = getNodeText(nodeXml);
                            code_html = unescape_xml(code_html);


                            id$('action_concerned_list_dv').innerHTML = code_html;
                        } catch (e) {
                            alert_box(e.message);
                        }
                    }
                }
        );
    } catch (e) {
        alert_box("action_concerned_list" + e.message);
    }
}
/**
 * Display form for searching cards to add to action-follow-up
 *@see ajax_add_concerned_card.php
 *@param {object} obj form object
 *@param obj.elements.ag_id id of the action (elements)
 *@param obj.elements.gDossier folder id
 *@param obj.elements.query
 */
function action_concerned_search_card(obj)
{
    try
    {
        var dossier = 0;
        var inp="";
        var ag_id=0;
        var search_in=-1;
        var inactive_card=0;
        var search_cat=-1;

        if (obj.dossier) {
            dossier = obj.dossier; /* From the button */
        }
        if (obj.ag_id) {
            ag_id=obj.ag_id;
        }
        /* from the form */
        if (obj.elements) {
            if (obj.elements['gDossier'])
            {
                dossier = obj.elements['gDossier'].value;
            }

            if (obj.elements['query']) {
                inp = obj.elements['query'].value;
            }

            if (obj.elements['ag_id']) {
                ag_id = obj.elements['ag_id'].value;
            }
            if (obj.elements['search_in']) {
                search_in = obj.elements['search_in'].value;
            }
            if ( obj.elements['inactive_card']) {
                inactive_card=obj.elements['inactive_card'].value;
            }
            if ( obj.elements['search_cat']) {
                search_cat=obj.elements['search_cat'].value;
            }
        }
        if (dossier == 0) {
            throw "obj.dossier not found";
        }
        if (ag_id == 0) {
            throw "obj.ag_id not found";
        }
        var query = encodeJSON({
            'gDossier': dossier,
            'op2': 'action_add_concerned_card',
            'query' : inp,
            'ctl' : 'unused',
            'ag_id' : ag_id,
            'op':'card',
            'accvis':0,
            'search_in':search_in,
            'inactive_card':inactive_card,
            'search_cat':search_cat
        });

        waiting_box();


        var action = new Ajax.Request('ajax_misc.php',
                {
                    method: 'get',
                    parameters: query,
                    onFailure: errorFid,
                    onSuccess: function (req, txt)
                    {
                        try {
                        remove_waiting_box();
                        var answer = req.responseXML;
                        var a = answer.getElementsByTagName('ctl');
                        if (a.length == 0)
                        {
                            var rec = req.responseText;
                            alert_box('erreur :' + rec);
                        }
                        var html = answer.getElementsByTagName('code');
                        var namectl = a[0].firstChild.nodeValue;
                        var nodeXml = html[0];
                        var code_html = getNodeText(nodeXml);
                        code_html = unescape_xml(code_html);

                        var sx = 0;
                        if (window.scrollY)
                        {
                            sx = window.scrollY + 40;
                        }
                        else
                        {
                            sx = document.body.scrollTop + 60;
                        }
                        var div_style = "top:" + sx + "px;height:52rem;z-index:"+get_next_layer();
                        if ( ! document.getElementById('search_card')) { add_div({id: 'search_card', cssclass: 'inner_box', html: "", style: div_style, drag: true}); }
                        id$('search_card').innerHTML = code_html;
                        id$('query').focus();
                        activate_checkbox_range('select_card_ck');
                        }catch (e) {
                            alert_box(e.message);
                        }
                    }
                }
        );
    }
    catch (e)
    {
        alert_box('search_card failed' + e.message);
        return false;
    }
    return false;
}

/**
 * when you submit the form for searching a card
 *@param obj form
 *@note the same as search_card, except it answer to a FORM and not
 * to a click event
 * @see ajax_card.php
 */
function search_get_card(obj)
{
    var dossier=id$('gDossier').value;

    var queryString="gDossier="+dossier;
    queryString+="&op2=fs&op=card";

    if ( obj.elements['inp'] )
    {
        queryString+="&inp="+$F('inp');
    }
    if ( obj.elements['typecard'] )
    {
        queryString+="&typecard="+$F('typecard');
    }
    if ( obj.elements['jrn'] )
    {
        queryString+="&jrn="+$F('jrn');
    }
    if ( obj.elements['label'])
    {
        queryString+="&label="+$F('label');
    }
    if ( obj.elements['price'])
    {
        queryString+="&price="+$F('price');
    }
    if ( obj.elements['tvaid'])
    {
        queryString+="&tvaid="+$F('tvaid');
    }
    if( obj.elements['query'])
    {
        queryString+="&query="+$F('query');
    }
    if (obj.ctl )
    {
        queryString+="&ctl="+obj.ctl;
    }
    if ( obj.elements['accvis'] )
    {
        queryString+="&accvis="+$F('accvis');
    } else {
        queryString+="&accvis=0";
    }
   if ( obj.elements['amount_from_type']) {
        queryString+="&amount_from_type="+obj.elements['amount_from_type'].value;
    }
    if (obj.elements['page_card']) {
        queryString+="&page_card="+obj.elements["page_card"].value;
    }
    if ( obj.elements["inactive_card"]) {
         queryString+="&inactive_card="+obj.elements["inactive_card"].value;
    }

    queryString=encodeURI(queryString);
    id$('asearch').innerHTML=loading();

    var action=new Ajax.Request ( 'ajax_misc.php',
                                  {
                                  method:'get',
                                  parameters:queryString,
                                  onFailure:errorFid,
                                  onSuccess:result_card_search
                                  }
                                );
}
/**
 * show the answer of ajax request
 * @see search_get_card
 *@param  answer in XML
 */
function result_card_search(req)
{
    try
    {

        remove_waiting_box();
        if ( req.responseText == 'NOCONX') { reconnect();return;}
        var answer=req.responseXML;
        var a=answer.getElementsByTagName('ctl');
        if ( a.length == 0 )
        {
            var rec=req.responseText;
            alert_box ('erreur :'+rec);
        }
        var html=answer.getElementsByTagName('code');

        var name_ctl=a[0].firstChild.nodeValue;
        var nodeXml=html[0];
        var code_html=getNodeText(nodeXml);
        code_html=unescape_xml(code_html);

        var sx=0;
	if ( window.scrollY)
	{
            sx=window.scrollY+40;
	}
	else
	{
            sx=document.body.scrollTop+60;
	}

        var div_style="top:"+sx+"px;min-height:80%;height:auto;z-index:"+get_next_layer();;
        add_div({id:'search_card',cssclass:'inner_box',html:"",style:div_style,drag:false,effect:'blinddown'});

        id$('search_card').innerHTML=code_html;

        if (document.getElementById('query')) { id$('query').focus();}
    }
    catch (e)
    {
        alert_box(e.message);
    }
    try
    {
        code_html.evalScripts();
    }
    catch(e)
    {
        alert_box(content[53]+"\n"+e.message);
    }

}



/**
 * Set the value of 2 input fields
*
* Set the quick code in the first ctrl and the label of the quickcode in the second one. This function is a variant of SetData for
* some specific need.  This function is called if the caller is searchcardCtrl
*
*@param p_ctrl the input with the name of the quick code
*@param  p_quickcode the found quick_code
*@param p_ctrlname the name of the input field with the label
*@param p_label the label of the quickcode
*/
function setCtrl(p_ctrl,p_quickcode,p_ctrlname,p_label)
{
    var ctrl=id$(p_ctrl);
    if ( ctrl )
    {
        ctrl.value=p_quickcode;
    }
    var ctrl_name=id$(p_ctrlname);
    if ( ctrl_name )
    {
        ctrl_name.value=p_label;
    }
}




function errorFid(request,json)
{
    alert_box(content[53]);
}
function update_value(text,li)
{
	   ajaxFid(text);
}
/**
 * is called when something change in ICard
 *@param the input field
 *@see ICard
 */
function fill_data_onchange(ctl)
{
    ajaxFid(ctl);

}
/**
 * is called when something change in ICard
 *@param the input field
 *@see ICard
 */
function fill_data(text,li)
{
    ajaxFid(text);

}
/**
 * is called when something change in ICard
 *@param the input field
 *@see ICard
 */
function fill_fin_data_onchange(ctl)
{
    ajaxFid(ctl);
    ajax_saldo(ctl.id);
}
/**
 * is called when something change in ICard
 *@param the input field
 *@see ICard
 */
function fill_fin_data(text,li)
{
    ajaxFid(text);
    ajax_saldo(id$(text.id));
}
/**
 * show the ipopup window and display the details of a card,
 * to work some attribute must be set
 *@param obj.qcode is the qcode, obj.nohistory if you don't want to  display
 * the history button, obj.ro is the popin is readonly
 *@note you must the gDossier as hidden in the calling page
 *
 *@see ajax_card.php
 */
function fill_ipopcard(obj)
{

    var card_layer=get_next_layer();

    var content='card_'+card_layer;
    var nTop=170+card_layer;
    if ( nTop > 300 ) {
        nTop=170;
    }
    var str_top="top:"+calcy(nTop)+"px";

    var str_style=str_top+";height:auto;position:absolute;z-index:"+get_next_layer();
    waiting_box();
    var popup={'id':  content,'cssclass':'inner_box2','style':str_style,'html':"",'drag':false};

    add_div(popup);
    var dossier=id$('gDossier').value;
    var qcode='';
    if ( obj.qcode != undefined )
    {
        qcode=obj.qcode;
    }
    else
    {
        qcode=id$(obj).value;
    }
    //    ctl=id$(obj).id;

    var queryString='gDossier='+dossier;
    queryString+='&qcode='+qcode;
    queryString+='&ctl='+content;
    queryString+='&op2=dc'; 	// dc for detail card
    queryString+='&op=card'; 	// dc for detail card
    if ( obj.readonly != undefined) {
     queryString+='&ro';
    }

    if ( obj.nohistory != undefined) {
     queryString+='&nohistory';
    }
    if ( obj.nofollowup != undefined) {
        queryString+='&nofollowup';
    }
    queryString=encodeURI(queryString);
    var action=new Ajax.Request ( 'ajax_misc.php',
                                  {
                                  method:'get',
                                  parameters:queryString,
                                  onFailure:errorFid,
                                  onSuccess:fill_box
                                  }
                                );
}
/**
 *
 * @param request : object request
 * @param json : json answer
*/
function  successFill_ipopcard(req,json)
{
    try
    {
        if (req.responseText=='NOCONX') { reconnect();return; }
        var answer=req.responseXML;
        var a=answer.getElementsByTagName('ctl');
        var html=answer.getElementsByTagName('code');

        if ( a.length == 0 )
        {
            var rec=req.responseText;
            alert_box ('erreur :'+rec);
        }
        var name_ctl=a[0].firstChild.nodeValue;
        var code_html=getNodeText(html[0]);
        code_html=unescape_xml(code_html);

        id$(name_ctl).innerHTML=code_html;
    }
    catch (e)
    {
        alert_box(e.message);
    }
    try
    {
        code_html.evalScripts();
    }
    catch(e)
    {
        alert_box(content[53]+"\n"+e.message);
    }
}
/**
 * show the ipopup for selecting a card type, it is a needed step before adding
 * a card
 *@param input field (obj) it must have the attribute ipopup
 *       possible attribute :
 *        - filter possible values are deb, cred, fd_id list, -1 means there  is no filter
 *        - ref if we want to refresh the window after adding a card
 *        - type type of card (supplier, customer...)
 *@see ajax_card.php
 */
function select_card_type(obj)
{
    var dossier=id$('gDossier').value;
    var elementId="";
    // give a filter, -1 if not
    var filter=id$(obj).filter;
    if ( filter==undefined)
    {
        filter=-1;
    }
    var content="select_card_div";
    if ( document.getElementById(content)){removeDiv(content);}
    var sx=0;
    sx=calcy(160);

    var str_style="top:"+sx+"px;height:auto;z-index:"+get_next_layer();
    waiting_box();
    var popup={'id':  content,'cssclass':'inner_box','style':str_style,'html':"",'drag':false};



    var queryString='gDossier='+dossier;
    queryString+='&ctl='+content;
    queryString+='&op2=st'; 	// st for selecting type
    queryString+='&op=card'; 	// st for selecting type
    if ( id$(obj).win_refresh!=undefined)
    {
        queryString+='&ref';
    }
    /* if an element id must be updated after creating a new card */
    if (  id$(obj).elementId) {
        var elementId=id$(obj).elementId;
        queryString+="&eltid="+elementId;
    }
    queryString+='&fil='+filter;
    // filter on the ledger, -1 if not
    var oledger=id$(obj).jrn;
    if (oledger==undefined)
    {
        ledger=-1;
    }
    else
    {
        ledger=id$(obj).jrn;
    }

    queryString+='&ledger='+ledger;

    if ( obj.type_cat)
    {
        queryString+='&cat='+obj.type_cat;
    }

    var action=new Ajax.Request ( 'ajax_misc.php',
                                  {
                                  method:'get',
                                  parameters:queryString,
                                  onFailure:errorFid,
                                  onSuccess:function(req) {
                                      if (req.responseText=='NOCONX') { reconnect(); return;}
                                       add_div(popup);
                                      // Get all the category,
                                      var answer=req.responseXML.getElementsByTagName("fiche_cat_item");
                                      if (answer.length == 0) {
                                          removeDiv(content);
                                          remove_waiting_box();
                                          alert_box(getNodeText(req.responseXML.getElementsByTagName("code")[0]));
                                          return;
                                      }
                                      if ( answer.length == 1) {
                                          // There is only one category of card
                                          dis_blank_card({"ctl":"div_new_card","fd_id":answer[0].firstChild.nodeValue,"op2":"bc","op":"card",gDossier:dossier,"elementId":elementId});
                                          removeDiv(content);
                                          remove_waiting_box();
                                          return;
                                      }
                                      fill_box(req);
                                       id$('lk_cat_card_table').focus();
                                    }
                                  }
                                );
}
/**
 * Show a blank card
 *@param obj Form object (obj)
 *       possible attribute :
 *        - filter is the filter but with a  fd_id list, -1 means there  is no filter
 *        - ref : reload the window after adding card
 *        - content : name of the div
 *@note dis_blank_card({gDossier:15,fd_id:12,ref:1});
 *@see ajax_card.php
 */
function dis_blank_card(obj)
{
    // first we have to take the form elt we need
    if ( obj.fd_id.value != undefined )
		{ var fd_id=$F('fd_id'); }
	else {fd_id=obj.fd_id;}

    var ref="";
    if ( obj.elements &&  obj.elements['ref'] )
    {
        ref='&ref';
    }
    var content='div_new_card';
    var nTop=calcy(150);
    var nLeft=posX;
    var str_style="top:"+nTop+"px;right:"+nLeft+"px;height:auto;width:45rem;z-index:"+get_next_layer();

    var popup={'id':  content,'cssclass':'inner_box','style':str_style,'html':loading(),'drag':false};

    add_div(popup);

    if ( obj.gDossier.value != undefined ) {
        var dossier=id$('gDossier').value;
    } else {
	var dossier=obj.gDossier;
    }
    var queryString='gDossier='+dossier;
    queryString+='&ctl='+content;
    queryString+='&fd_id='+fd_id;
    queryString+=ref;
    queryString+='&op2=bc'; 	// bc for blank card
    queryString+='&op=card'; 	// bc for blank card
    if (obj.after_save) {
        queryString+='&after_save='+obj.after_save;
    }

    if ( obj.elementId) queryString+="&eltid="+obj.elementId;
    var action=new Ajax.Request ( 'ajax_misc.php',
                                  {
                                  method:'get',
                                  parameters:queryString,
                                  onFailure:errorFid,
                                  onSuccess: function (req,json) {


                                      successFill_ipopcard(req,json);
                                  }
                              }
                            );
}
function form_blank_card(obj)
{
    // first we have to take the form elt we need
    var fd_id=obj.fd_id;
    var content='div_new_card';
    var nTop=posY-40;
    var nLeft=posX-20;
    var str_style="top:"+nTop+"px;left:"+nLeft+"px;width:60em;height:auto;z-index:"+get_next_layer();

    var popup={'id':  content,'cssclass':'inner_box','style':str_style,'html':loading(),'drag':true};
    if ( document.getElementById(content)) {removeDiv(content);}
    add_div(popup);


    var dossier=id$('gDossier').value;

    var queryString='gDossier='+dossier;
    queryString+='&ctl='+content;
    queryString+='&fd_id='+fd_id;
    queryString+='&op2=bc'; 	// bc for blank card
    queryString+='&op=card'; 	// bc for blank card

    var action=new Ajax.Request ( 'ajax_misc.php',
                                  {
                                  method:'get',
                                  parameters:queryString,
                                  onFailure:errorFid,
                                  onSuccess:successFill_ipopcard
                                  }
                                );
}

/**
 * save the data contained into the form 'save_card'
 *@param input field (obj) it must have the attribute ipopup
 *       possible attribute :
 *@see ajax_card.php
 */
function save_card(obj)
{
    var content=id$(obj).ipopup;
    var accounting= id$(obj)['av_text5'];
    if ( accounting && accounting.value.length > 40 ) {
      smoke.alert('Poste comptable trop grand');
      return false;
    }

    // Data must be taken here

    var    data=id$('save_card').serialize(false);
    waiting_box();
    var dossier=id$('gDossier').value;
    var queryString='gDossier='+dossier;
    queryString+='&ctl='+content;
    queryString+=data;
    queryString+='&op2=sc'; 	// sc for save card
    queryString+='&op=card'; 	// sc for save card

    var action=new Ajax.Request ( 'ajax_misc.php',
                                  {
                                  method:'post',
                                  parameters:queryString,
                                  onFailure:errorFid,
                                  onSuccess:function (req,json) {
                                      var elt=req.responseXML.getElementsByTagName("eltid");
                                      var status=req.responseXML.getElementsByTagName("status");
                                      var status_value='OK';
                                      var after_savetag=req.responseXML.getElementsByTagName("after_save");
                                      var after_save=0;
                                      if ( status.length !=0) {
                                        status_value=getNodeText(status[0]);
                                      }
                                      if ( after_savetag.length !=0 ) {
                                          after_save=getNodeText(after_savetag[0]);
                                      }
                                      // if status == OK and after_save == 0
                                      // then update the box
                                      if ( status_value == 'OK' && after_save == 0) {
                                             fill_box(req,json);
                                      }

                                      // if status == OK and after_save == 1
                                      // then add a row to the table
                                      if ( status_value == 'OK' && after_save == 1) {
                                            var table_card=id$('fiche_tb_id');
                                            f_id=getNodeText(req.responseXML.getElementsByTagName("f_id")[0]);
                                             var row=new Element('tr');
                                             row.id="row_card"+f_id;
                                             row.innerHTML=getNodeText(req.responseXML.getElementsByTagName("code")[0]);
                                             table_card.tBodies[0].appendChild(row);
                                              new Effect.Highlight(row.id ,{startcolor: '#FAD4D4',endcolor: '#F78082' });
                                             //
                                             if ( table_card.tBodies[0].rows.length % 2 == 0 ) {
                                                 row.addClassName("odd");
                                             } else {
                                                 row.addClassName("even");

                                             }
                                      }

                                      remove_waiting_box();
                                      if ( elt.length != 0) {
                                         var eltid=getNodeText(elt[0]);
                                         if ( eltid !="") {
                                            var eltvalue=req.responseXML.getElementsByTagName("elt_value");
                                            id$(eltid).value=getNodeText(eltvalue[0]);
                                            fill_data_onchange(eltid);
                                            id$(eltid).focus();
                                        }
                                      }
                                      if (status_value == "OK") {
                                            Effect.SlideUp(content, { duration: 1.0 });
                                        }
                                      if ( status_value == 'NOK') {
                                          var xml_message=req.responseXML.getElementsByTagName("code");
                                          var message=getNodeText(xml_message[0]);
                                          smoke.alert(message);
                                      }


                                  }
                              }
                        );
}
/**
 * add a category of card,
 *@param obj with the attribute
 * - ipopup the ipopup to show
 * - type_cat the category of card we want to add
 */
function add_category(obj)
{
    var sx=0;
	if ( window.scrollY)
	{
            sx=window.scrollY+120;
	}
	else
	{
            sx=document.body.scrollTop+120;
	}

	var div_style="top:"+sx+"px;width:60%;height:80%;z-index:"+get_next_layer();
    // show ipopup
	var div={id:obj.ipopup,
			cssclass:"inner_box",drag:1,style:div_style};
	if ( document.getElementById(div) ) {
		removeDiv(div);
	}
	add_div(div);
	waiting_box();
    var dossier=id$('gDossier').value;
    var queryString='gDossier='+dossier;
    queryString+='&op2=ac';
    queryString+='&op=card';
    queryString+='&ctl='+obj.ipopup;
    if ( obj.type_cat)
    {
        queryString+='&cat='+obj.type_cat;
    }
    var action=new Ajax.Request ( 'ajax_misc.php',
                                  {
                                  method:'get',
                                  parameters:queryString,
                                  onFailure:errorFid,
                                  onSuccess:fill_box
                                  }
                                );

}
/**
 *  save the form and add a new category of card
 * @param obj if the form object
 */
function save_card_category(obj)
{
    if ( ! $(obj).ipopup)
    {
        alert_box('Erreur pas d\' attribut ipopup '+obj.id);
        return;
    };
try {
		// Data must be taken here
    data=id$('newcat').serialize(false);
    var dossier=id$('gDossier').value;
    var queryString='ctl='+obj.ipopup+'&';
    queryString+=data;
    queryString+='&op2=scc'; 	// sc for save card
    queryString+='&op=card'; 	// sc for save card

    var action=new Ajax.Request ( 'ajax_misc.php',
                            {
                                method:'POST',
                                parameters:queryString,
                                onFailure:errorFid,
                                onSuccess:function (req) 
                                { 
                                    fill_box(req);
                                    // populate
                                     var answer = req.responseXML;
                                     var a = answer.getElementsByTagName('id');
                                     var b = answer.getElementsByTagName('name');
                                     if ( a.length == 1 && b.length == 1) {
                                         let option=new Element('option');
                                         option.value=getNodeText(a[0]);
                                         option.text=getNodeText(b[0]);
                                         id$('cat').add(option);
                                     }
                                }
                              }
                                );
	} catch(e)
	{
            
		alert_box(e.message);
		return false;
	}
	return false;
}
/**
 * Remove a definition of an  attribut
 *@param attr_def.ad_id
 *@param gDossier
 *@param table_id to rm the row
 *@param special this pointer of the row
 */

function removeCardAttribut(ad_id,gDossier,table_id,row)
{
    var queryString='gDossier='+gDossier;
    queryString+='&op=card';
    queryString+='&op2=rmfa';
    queryString+='&ctl=debug'; 	// debug id
    queryString+='&ad_id='+ad_id;
    var action=new Ajax.Request ( 'ajax_misc.php',
                                  {
                                  method:'get',
                                  parameters:queryString,
                                  onFailure:null,
                                  onSuccess:null
                                  }
                                );
    deleteRowRec(table_id,row);


}
/**
* update a card in ajax
*/
function update_card(obj)
{
try {
    var name=obj.id;

    var qs=Form.serialize(name)+'&op2=upc&op=card';
    var action=new Ajax.Request ( 'ajax_misc.php',
				  {
				      method:'get',
				      parameters:qs,
				      onFailure:errorFid,
				      onSuccess:successFill_ipopcard
				  }
				);
    } catch (e) {
	alert_box(e.message);
	return false;
    }
}
/***
 * In Follow-up, update, it is possible to add several card as concerned person or company
 * this function save it into the database, display the result and remove the search_card div
 * @param {type} p_dossier dossier
 * @param {type} p_fiche_id fiche.f_id
 * @param {type} p_action_id action_gestion.ag_id
 * @returns {undefined} nothing
 */
function action_save_concerned(p_form_id) {
    var query = encodeJSON({'gDossier': p_dossier, 'f_id': p_fiche_id, 'ag_id': p_action_id,'op':'card','op2':'action_save_concerned','ctl':'unused'});
    var a=new Ajax.Request('ajax_misc.php',
            {
                method: 'get',
                parameters: query,
                onFailure: errorFid,
                onSuccess: function (req, txt)
                {
                    try {
                        remove_waiting_box();
                        var answer = req.responseXML;
                        var a = answer.getElementsByTagName('ctl');
                        if (a.length == 0)
                        {
                            var rec = req.responseText;
                            alert_box('erreur :' + rec);
                        }
                        var html = answer.getElementsByTagName('code');
                        var namectl = a[0].firstChild.nodeValue;
                        var nodeXml=html[0];
                        var code_html = getNodeText(nodeXml);
                        code_html = unescape_xml(code_html);
                        removeDiv('search_card');
                        id$('concerned_card_td').innerHTML = code_html;
                    } catch (e) {

                    }
                }
            }
    );
    }
function action_remove_concerned(p_dossier,p_fiche_id,p_action_id)
{
 var query = encodeJSON({'gDossier': p_dossier, 'f_id': p_fiche_id, 'ag_id': p_action_id,'op':'card','op2':'action_remove_concerned','ctl':'unused'});
    var a=new Ajax.Request('ajax_misc.php',
            {
                method: 'get',
                parameters: query,
                onFailure: errorFid,
                onSuccess: function (req, txt)
                {
                    try {
                        remove_waiting_box();
                        var answer = req.responseXML;
                        var a = answer.getElementsByTagName('ctl');
                        if (a.length == 0)
                        {
                            var rec = req.responseText;
                            alert_box('erreur :' + rec);
                        }
                        var html = answer.getElementsByTagName('code');
                        var namectl = a[0].firstChild.nodeValue;
                        var nodeXml=html[0];
                        var code_html = getNodeText(nodeXml);
                        code_html = unescape_xml(code_html);
                        id$('concerned_card_td').innerHTML = code_html;
                        removeDiv('search_card');

                        id$(namectl).remove();

                    } catch (e) {
                        if ( console) { console.log('Erreur ') + e.message;}
                        alert_box('action_remove_concerned '+e.message);
                    }
                }
            }
    );
    }
/**
 * Remove a card after checking it is not used
 * @param obj {json} = gDossier,op,op2:rm_card,ctl,f_id
 */
function delete_card(obj) {
    smoke.confirm("Confirmez ? ", function (e) {
        if (e) {
            waiting_box();
            new Ajax.Request("ajax_misc.php", {
                "method": "get",
                parameters: obj,
                onSuccess: function (req) {
                    remove_waiting_box();
                    var answer = req.responseXML;
                    var a = answer.getElementsByTagName('ctl');
                    if (a.length == 0)
                    {
                        var rec = req.responseText;
                        alert_box('erreur :' + rec);
                    }
                    var html = answer.getElementsByTagName('code');
                    var namectl = a[0].firstChild.nodeValue;
                    var nodeXml = html[0];
                    var code_html = getNodeText(nodeXml);
                    code_html = unescape_xml(code_html);
                    if ( code_html == "OK") {
                        Effect.Fade(obj['ctl'], { duration: 1.5 });
                    } else {
                        smoke.alert(code_html);
                    }
                }

            });
        }
    });
}
/**
 * Display a card , modify it , redraw the row
 * before calling this function , it it neeed to have in the web page a hidden card_gdossier with the dossier id
 * @param {type} p_fiche_id
 * @returns {undefined}
 */
function modify_card(p_fiche_id)
{
    /* window with result */
     var card_layer=get_next_layer();

    var content = 'card_' + card_layer;
    var nTop = 170 + card_layer;
    if (nTop > 300) {
        nTop = 170;
    }
    var str_top = fixed_position(250, nTop)
    var str_style = str_top + ";width:45em;height:auto;position:absolute"+"; z-index:"+get_next_layer();

    var popup = {'id': content, 'cssclass': 'inner_box', 'style': str_style, 'html': loading(), 'drag': false};

    add_div(popup);

    /* dossier id */
    if ( ! document.getElementById("card_gdossier")) {

        console.error("card_gdossier error");
        throw ("card_gdossier not set");
    }
    var dossier = id$('card_gdossier').value;


    var action = new Ajax.Request('ajax_misc.php',
            {
                method: 'get',
                parameters: {'gDossier':dossier,"op":'card',"op2":"dc","f_id":p_fiche_id,'ctl':content,after_save:2} ,
                onFailure: errorFid,
                onSuccess: function (respTxt) {
                    fill_box(respTxt);
                }
            }
    );
}
/**
 * Delete a card and remove the row
 * before calling this function , it it neeed to have in the web page a hidden card_gdossier with the dossier id
 * @param {type} p_fiche_id
 * @returns {undefined}
 */
function delete_card_id(p_fiche_id)
{
    var row="row_card"+p_fiche_id;
    if ( ! document.getElementById("card_gdossier")) {

        console.error("card_gdossier error");
        throw ("card_gdossier not set");
    }
    id$(row).addClassName("background-selected");
    var dossier = id$('card_gdossier').value;
    smoke.confirm(content[47], function (e) {
        if (e) {
            waiting_box();
            new Ajax.Request("ajax_misc.php", {
                "method": "get",
                parameters: {'gDossier':dossier,"op":'card',"op2":"rm_card","f_id":p_fiche_id,'ctl':row} ,
                onSuccess: function (req) {
                    remove_waiting_box();
                    var table_card=id$('fiche_tb_id');
                    var answer = req.responseXML;
                    var a = answer.getElementsByTagName('ctl');
                    if (a.length == 0)
                    {
                        var rec = req.responseText;
                        alert_box('erreur :' + rec);
                    }
                    var html = answer.getElementsByTagName('code');
                    var namectl = a[0].firstChild.nodeValue;
                    var nodeXml = html[0];
                    var code_html = getNodeText(nodeXml);
                    code_html = unescape_xml(code_html);

                    if ((code_html) == "OK") {
                        Effect.Fade(row, {duration: 0.1});
                        table_card.tBodies[0].removeChild(id$(row));
                        alternate_row_color("fiche_tb_id");
                    } else {
                        smoke.alert(code_html);

                    }
                }

            });
        } else{
                   id$(row).removeClassName("background-selected");

        }
    });

}

/**
* update a card in ajax , and update a row
*
*/
function card_update_row(obj)
{
    try {
        var name = obj.id;

        var qs = Form.serialize(name) + '&op2=upr&op=card';
        var action = new Ajax.Request('ajax_misc.php',
                {
                    method: 'get',
                    parameters: qs,
                    onFailure: errorFid,
                    onSuccess: function (req) {
                        try {

                            remove_waiting_box();

                            var answer = req.responseXML;
                            var a = answer.getElementsByTagName('ctl');
                            var html = answer.getElementsByTagName('code');
                            if (a.length === 0) {
                                var rec = req.responseText;
                                alert_box('erreur :' + rec);
                            }
                            var name_ctl = "row_card" + obj.f_id.value;
                            var code_html = getNodeText(html[0]); // Firefox ne prend que les 4096 car.
                            code_html = unescape_xml(code_html);

                            if ( document.getElementById(name_ctl)) {
                                // update the row
                                id$(name_ctl).innerHTML = code_html;
                                new Effect.Highlight(name_ctl ,{startcolor: '#FAD4D4',endcolor: '#F78082' });

                            }
                            id$(a[0].firstChild.nodeValue).remove();


                        } catch (e) {
                            alert_box(e.message);
                            if (console) {
                                console.error(e);
                                console.error("log answer = " + req.responseText);
                            }
                        }
                        try {
                            code_html.evalScripts();
                        } catch (e) {
                            if (console) {
                                console.error(e);
                                console.error("log answer = " + req.responseText);
                            }
                            alert_box(content[53] + "\n" + e.message);
                        }


                    }
                }
        );
    } catch (e) {
        alert_box(e.message);
        return false;
    }
}
/**
 * Display the option of a contact linked in a action-followup
 * @param {int} p_action_person_id action_person.ap_id
 * @param {int} p_dossier current folder
 */
function linked_card_option(p_action_person_id,p_dossier) {
    try {
        waiting_box();
        new Ajax.Request("ajax_misc.php",{
            method:"get",
            parameters: {
                ap_id:p_action_person_id,
                gDossier:p_dossier,
                op:"card",
                op2:"display_card_option",
                ctl:"notused"
            },
            onSuccess:function(req) {
                remove_waiting_box();
                add_div({ "id":"d_linked_card_option",cssclass:"inner_box",style:"position:fixed;top:30%;min-width:20rem;width:auto;z-index:"+get_next_layer(),drag:0});
                id$("d_linked_card_option").update(req.responseText);

            }
        });
    } catch (e) {
        console.error(e.message);
    }
}
/**
 * Save option for the contact
 * @param {object} obj form
 * @see card_multiple_display_option.php
 * @returns {undefined}
 */
function save_linked_card_option(obj)
{
    waiting_box();
    new Ajax.Request("ajax_misc.php",{
        method:"post",
        parameters:obj.serialize(),
        onSuccess:function(req) {
            remove_waiting_box();
            removeDiv("d_linked_card_option");
            id$("other_"+obj.action_person_id.value).update(req.responseText);
              new Effect.Highlight("other_"+obj.action_person_id.value,{startcolor: '#FAD4D4',endcolor: '#F78082' });
        }
    });
    return false;
}

/**
 * @class
 * Manage adding, removing and ordering attributs of a card template (FICHE_DEF), used in the module CCARD
 * @param dossier_id {int} Folder
 * @param fiche_def_id {int} SQL : FICHE_DEF.FD_ID
 */
var CategoryCardDefinition = function (dossier_id, fiche_def_id) {
    this.dossier_id = dossier_id;
    this.fiche_def_id = fiche_def_id;
    this.available_list = 'avail_attribut_id';
    this.existing_list = 'attribut_card';
    this.op = 'category_card_definition';
}
/**
 * save the order + new attributes, remove old ones
 */
CategoryCardDefinition.prototype.save = function () {

    try {
        var here = this;
        var aAttribut=Sortable.serialize(this.existing_list);
        var queryString = {
            gDossier: this.dossier_id,
            fiche_def_id: this.fiche_def_id,
            op: this.op,
            op2: 'save',
            attribut:aAttribut
        };
        var action = new Ajax.Request(
            "ajax_misc.php",
            {
                method: 'POST',
                parameters: queryString,
                onFailure: ajax_misc_failure,
                onSuccess: function (req) {
                    if (req.responseText == 'NOCONX') {
                        reconnect();
                        return;
                    }
                    if ( req.responseText == 'OK') {
                        smoke.signal('Sauvé',function(e){},{duration:500});
                    }
                 
                   
                }
            }
        );
    } catch (e) {
        alert_box("CategoryCardDefinition.save" + e.message);
    }
};
/**
 * add an attribut from the DOM Element avail_attribut_id , do add an element in attribut_card and remove from avail_attribut_id
 * @param attribut_id {int} attr_def.ad_id , ad_id of attribute
 */
CategoryCardDefinition.prototype.add_attribut = function (attribut_id) {


    try {
        var here = this;
        var queryString = {
            gDossier: this.dossier_id,
            fiche_def_id: this.fiche_def_id,
            op: this.op,
            op2: 'add',
            ad_id: attribut_id
        };
        var action = new Ajax.Request(
            "ajax_misc.php",
            {
                method: 'GET',
                parameters: queryString,
                onFailure: ajax_misc_failure,
                onSuccess: function (req) {
                    if (req.responseText == 'NOCONX') {
                        reconnect();
                        return;
                    }

                    // if successfull add id on existing_list and remove from available_list

                    // remove from available_list
                    id$('avail_attr_' + attribut_id).remove();
                    var parser = new DOMParser();
                    var element = parser.parseFromString(req.responseText, 'text/html');
                     id$(here.existing_list).appendChild(element.body.firstChild);
                    new Effect.Highlight('existing_attr_' + attribut_id, {
                        startcolor: '#FAD4D4',
                        endcolor: '#F78082'
                    });
                    Sortable.create('attribut_card', {tag: 'li'});
                    alternate_row_color_list(here.available_list);
                }
            }
        );
    } catch (e) {
        alert_box("CategoryCardDefinition.add_attribut" + e.message);
    }
};
/**
 * remove an attribut from the DOM Element attribut_card , do add an element in avail_attribut_id and remove from attribut_card
 * @param attribut_id {int} attr_def.ad_id , ad_id of attribute
 */
CategoryCardDefinition.prototype.remove_attribut = function (attribut_id) {

    var here = this;
    try {

        var queryString = {
            gDossier: this.dossier_id,
            fiche_def_id: this.fiche_def_id,
            op: this.op,
            op2: 'remove',
            ad_id: attribut_id
        };
        var action = new Ajax.Request(
            "ajax_misc.php",
            {
                method: 'GET',
                parameters: queryString,
                onFailure: ajax_misc_failure,
                onSuccess: function (req) {
                    if (req.responseText == 'NOCONX') {
                        reconnect();
                        return;
                    }

                    // if successfull add id on existing_list and remove from available_list

                    // remove from available_list
                    id$('existing_attr_' + attribut_id).remove();
                    var parser = new DOMParser();
                    var element = parser.parseFromString(req.responseText, 'text/html');
                    id$(here.available_list).appendChild(element.body.firstChild);

                    alternate_row_color_list(here.available_list);
                    Sortable.create('attribut_card', {tag: 'li', hoverclass: inner_box});
                }
            }
        );
    } catch (e) {
        alert_box("CategoryCardDefinition.remove_attribut" + e.message);
    }
};
