var currentCat = 0;
var currentBigCat = 0;
var editableGrid= null;


function Vermeire(lang){
  this.lang = lang;
}


/* Chargement des grandes famille */
Vermeire.prototype.bigfamily = function ( )  {



  cmson.ajax('admin/action/vermeire/api.php', {
    action: "category",
    famweb: "category",
    niveau: "category",
    lang: lang
  },
  function(response) {
    var result = $.parseJSON(response);
    var res = result.data;
    $("#debug").html(result.url);
    var content = "";

    for ( var i=0; i< res.API_LISTE_GRANDES_FAMILLES_Result.length; i++ ) {
       $("#category_list").append("<div class='group' data-accordion-index='"+i+"' data-index='"+res.API_LISTE_GRANDES_FAMILLES_Result[i].ide_gfamw+"'><h3 class='link' data-index='"+res.API_LISTE_GRANDES_FAMILLES_Result[i].ide_gfamw+"'>"+res.API_LISTE_GRANDES_FAMILLES_Result[i].gfamw_lib+"</h3><div class='group_content' ></div></div>");
       content += "<div class='catalog_cat c"+res.API_LISTE_GRANDES_FAMILLES_Result[i].ide_gfamw+"' data-accordion-index='"+i+"' data-index='"+res.API_LISTE_GRANDES_FAMILLES_Result[i].ide_gfamw+"'><div>"+res.API_LISTE_GRANDES_FAMILLES_Result[i].gfamw_lib+"</div></div>";

    }

    $( "#category_list" )
      .accordion({
        header: "> div > h3",
        active: false,
        collapsible: true,
        heightStyle: "content",
        activate: function( event, ui ) { 
        currentBigCat =   $(ui.newHeader).attr('data-index');
          vermeire.categorySubList(ui.newHeader); 
          cmson.scrollTo("catalog_wrapper");
        }
        
      });

   $("#catalog_content_data").html(content);
    $("#catalog_content_data .catalog_cat").on('click', function() {
        currentBigCat =  $(this).attr('data-index');
        vermeire.categorySubList(this);
        $("#category_list").accordion('option', 'active' , parseInt($(this).attr('data-accordion-index')));  
    });
    $("#category_list .group li a").on('click', function() {
        currentBigCat =  $(this).attr('data-index');
        vermeire.categorySubList(this);
        $("#category_list").accordion('option', 'active' ,  parseInt($(this).attr('data-accordion-index'))); 
    });
    


  });

}

Vermeire.prototype.search = function ( ide_famw)  {

  $("#catalog_content_data").html("Chargement des données...");
  cmson.ajax('admin/action/vermeire/api.php', {
    action: "search",
    lang: lang,
    keywords:$("#keywords").val(),
    ide_famw: ide_famw != null ?   ide_famw : currentCat
    
  },
  function(response) {
    var result = $.parseJSON(response);
    var res = result.data;
    $("#debug").html(result.url);
    if ( res.Items ) {
        var content = "<table class='datagrid' id='resultgrid'><tr><th>Code</th><th>Description</th></tr>";
        for ( var i=0; i< res.Items.length; i++ ) {
          content += "<tr><td>"+res.Items[i]._x003C_Code_x003E_k__BackingField+ "</td><td>" + res.Items[i]._x003C_Description_x003E_k__BackingField+"</td></tr>";
        }
        content += "</table>";
        $("#catalog_content_data").html(content);

        editableGrid = new EditableGrid("resultgrid_"+ide_famw, { 
            pageSize: 30,
            tableRendered:  function() {  updatePaginator(this);  },
          }); 
				// we build and load the metadata in Javascript
		editableGrid.load({ metadata: [
					{ name: "code", datatype: "string", editable: false },
					{ name: "description", datatype: "string", editable: false }
				]});
				// then we attach to the HTML table and render it
		editableGrid.attachToHTMLTable('resultgrid');
		editableGrid.renderGrid();

		if ( editableGrid.currentFilter != null && editableGrid.currentFilter.length > 0)
		  $("#search").val(editableGrid.currentFilter);


		updatePaginator(editableGrid,'paginator');
		$("#paginator").show();


			 
    }
    else {
        $("#catalog_content_data").html("<div class='notification error'><p>Erreur survenue durant la recherche</p></div>");
    }


    
  });

}

Vermeire.prototype.showdata = function ( ide_famw)  {


  $("#catalog_content_data").html("Chargement des données...");
  cmson.ajax('admin/action/vermeire/api.php', {
    action: "search",
    lang: lang,
    keywords:"",
    ide_famw: ide_famw    
  },
  function(response) {
    var result = $.parseJSON(response);
    var res = result.data;
    $("#debug").html(result.url);
    if ( res.Items ) {
        var content = "<table class='datagrid' id='resultgrid'><tr><th>Code</th><th>Description</th></tr>";
        for ( var i=0; i< res.Items.length; i++ ) {
          content += "<tr><td>"+res.Items[i]._x003C_Code_x003E_k__BackingField+ "</td><td>" + res.Items[i]._x003C_Description_x003E_k__BackingField+"</td></tr>";
        }
        content += "</table>";
        $("#catalog_content_data").html(content);

        editableGrid = new EditableGrid("resultgrid_"+ide_famw, { 
            pageSize: 30,
            tableRendered:  function() {  updatePaginator(this);  },
          }); 
				// we build and load the metadata in Javascript
		editableGrid.load({ metadata: [
					{ name: "code", datatype: "string", editable: false },
					{ name: "description", datatype: "string", editable: false }
				]});
				// then we attach to the HTML table and render it
		editableGrid.attachToHTMLTable('resultgrid');
		editableGrid.renderGrid();

		if ( editableGrid.currentFilter != null && editableGrid.currentFilter.length > 0)
		  $("#search").val(editableGrid.currentFilter);


		updatePaginator(editableGrid,'paginator');
		$("#paginator").show();


			 
    }
    else {
        $("#catalog_content_data").html("<div class='notification error'><p>Erreur survenue durant la recherche</p></div>");
    }


    
  });

}


/* Chargement des sous-famille */
Vermeire.prototype.categorySubList = function ( source)  {

  $("#paginator").hide();
  $("#search").show();
  $("#keywords").val("");

  var ide_famw = $(source).attr('data-index');
  currentCat = ide_famw;

  console.log(cmson);
  //console.log("call categorySubList : index = " +ide_famw  );
  cmson.ajax('admin/action/vermeire/api.php', {
    action: "bigcategory",
    lang: lang,
    ide_famw: ide_famw    
  },
  function(response) {
    var result = $.parseJSON(response);
    var res = result.data;
    $("#debug").html(result.url);
    var container = $(source).parent().find('.group_content');
    container.empty();
    var content = "";
    for ( var i=0; i< res.API_LISTE_FAMILLES_Result.length; i++ ) {
       $(container).append("<li><a data-index='"+ide_famw+"'>"+res.API_LISTE_FAMILLES_Result[i].famw_lib+"</a><div class='subgroup' id='subgroup"+res.API_LISTE_FAMILLES_Result[i].ide_famw+"'></div></li>");

       content += "<div class='catalog_cat c"+currentBigCat+"' data-index='"+res.API_LISTE_FAMILLES_Result[i].ide_famw+"'><a class='directdatalink' data-index='"+res.API_LISTE_FAMILLES_Result[i].ide_famw+"'><i class='fa fa-table'></i></a> <a class='pdflink' href=''><i class='fa fa-file-pdf-o'></i></a><div>"+res.API_LISTE_FAMILLES_Result[i].famw_lib+"</div></div>";



    }

    $("#catalog_content_data").html(content);
    $("#catalog_content_data .catalog_cat").on('click', function() {
        vermeire.loadSubCategory(this);
    });
    $("#category_list .group li a").on('click', function() {
        vermeire.loadSubCategory(this);
    });
    $("#category_list .directdatalink").on('click', function() {
        vermeire.showdata($(this).attr('data-index'));
    });

    $("#catalog_content_title").html($(source).text());
  });

}

Vermeire.prototype.loadSubCategory = function ( source )  {
 
    $("#paginator").hide();
  $("#search").show();
  $("#search").val("");

  var ide_famw = $(source).attr('data-index');
  currentCat = ide_famw;
  $("#catalog_content_data").empty().html("Load...");
  //console.log("call loadSubCategory : ide_famw = " + ide_famw );
  cmson.ajax('admin/action/vermeire/api.php', {
    action: "subfamily",
    lang: lang,
    ide_famw: ide_famw    
  },
  function(response) {
    var result = $.parseJSON(response);
    var res = result.data;
    $("#debug").html(result.url);
    if ( res == "" || res == null || typeof res == "undefined" || jQuery.isEmptyObject(res) ) {
      vermeire.showdata(ide_famw);
    }
    else {

      var content = "";
      var contentAccordion = "";
    for ( var i=0; i< res.API_LISTE_FAMILLES_Result.length; i++ ) {
       content += "<div class='catalog_cat c"+res.API_LISTE_FAMILLES_Result[i].ide_famw+"' data-index='"+res.API_LISTE_FAMILLES_Result[i].ide_famw+"'><div>"+res.API_LISTE_FAMILLES_Result[i].famw_lib+"</div></div>";
       contentAccordion += "<li><a  data-index='"+res.API_LISTE_FAMILLES_Result[i].ide_famw+"'>"+res.API_LISTE_FAMILLES_Result[i].famw_lib+"</a><div class='subgroup' id='subgroup"+res.API_LISTE_FAMILLES_Result[i].ide_famw+"'></div></li>";

    }
    $("#catalog_content_data").html(content);
    $("#category_list .group li #subgroup"+ ide_famw ).html(contentAccordion);
    $("#catalog_content_data").html(content);
    $("#catalog_content_data .catalog_cat").on('click', function() {
        vermeire.loadSubCategory(this);
    });
    $("#category_list .group li #subgroup"+ ide_famw+ " li a ").on('click', function() {
        vermeire.loadSubCategory(this);
    });

    $("#catalog_content_title").html($("#catalog_content_title").html() + " -> " + $(source).text());

    cmson.scrollTo("catalog_wrapper");



    }
      });


}


Vermeire.prototype.view = function ( )  {};

Vermeire.prototype.requestAccess = function ( )  {


   
  cmson.ajax('admin/action/vermeire/api.php', {
    action: "requestaccess",
    idcli:  $("#idcli").val(),
    lang: lang
  },
  function(response) {
    var result = $.parseJSON(response);
  });



};

Vermeire.prototype.login = function ( )  {


   cmson.ajax('admin/action/vermeire/api.php', {
    action: "login",
    login:  $("#cust_login").val(),
    password:  sha1($("#cust_password").val()),
    lang: lang
  },
  function(response) {

       try{
           var result = $.parseJSON(response);
           if ( result.data[0] === "false" ){
               message('error',"erreur durant la connexion" );
           }
       }catch(e){
           message('error',"erreur durant la connexion" );

       }
  });

};




/* Chargement des sous-catégories */

Vermeire.prototype.subFamily = function (cible){

    var container = $(cible).children('.warp_flip_sous_cat').children('.list_sous_cat');
    $(container).css('display','none');
    $(container).html('<i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i>');
    $(container).fadeIn();

    cmson.ajax('admin/action/vermeire/api.php',{
            action : "subfamily",
            famweb :  $(cible).attr('ref'),
            niveau :  $(cible).attr('niveau'),
            parent :  $(cible).attr('parent'),
            baseurl:  $(cible).attr('baseurl'),
            page   :  $(cible).attr('page')?$(cible).attr('page'):'shop',
            lang: lang
        },
        function(response) {

            try{
                var result = $.parseJSON(response);

                if ( result[0] === "false" ){
                    //console.log("erreur durant la connexion : URL : "+ result.url);
                }else{

                    $(container).fadeOut(300,function(){
                        $(container).html('<ul></ul>');
                        $(container).children('ul').html(result[1]);
                        $(container).append('<div class="clear"></div>');
                        $(container).fadeIn(function(){
                            $('.tooltip').tooltipster({
                                theme: 'tooltipster-noir'
                            });
                        });

                    });
                }


            }catch(e){
                message('error','Erreur dans la réception des donnés');
            }


        });


};

Vermeire.prototype.markLogo = function (cible){

    if($(cible).length > 0){
        $(cible).css('display','none');
        $(cible).html('<i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i>');
        $(cible).fadeIn();


        var options = {
            action: "mark",
            famweb:  $(cible).attr('ref'),
            searchable: $(cible).attr('searchable'),
            url: $(cible).attr('url'),
            mark : $(cible).attr('mark'),
            filter_mark : $(cible).attr('filter_mark'),
            lang: lang
        };

        cmson.ajax('admin/action/vermeire/api.php', options,
            function(response) {


                try{
                    var result = $.parseJSON(response);
                    if ( result[0] === "false" ){
                        //console.log("erreur durant la connexion : URL : "+ result.url);
                    }else{
                        $(cible).fadeOut(300,function(){
                            $(cible).html(result[1]);
                            $(cible).append('<div class="clear"></div>');
                            $(cible).fadeIn();
                        });
                    }

                }catch(e){
                    message('error','Erreur dans la réception des données');
                    $(cible).fadeOut();
                }


            });
    }

};


/* Check inscription */

Vermeire.prototype.register = function(post){

    var elem = this;

    var options = {
        action: "register",
        post: post,
        lang: lang,
        baseurl: baseUrl
    };

    var overlay = $('#overlay');

    overlay.fadeIn();

    var sendPending = function(post){
        cmson.ajax('admin/action/vermeire/api.php', {
                action: "sendPendingRegistrationMail",
                email       : $('#email').val(),
                firstname   : $('#firstname').val(),
                lastname    : $('#lastname').val(),
                password    : post.Password,
                post        : post,
                lang        :lang,
                baseurl     :baseUrl
            },
            function(response){
                var validation = 'Votre demande d\'accès a bien été enregistrée, vous recevrez votre login / mot de passe dans les 24 heures.';
                if(lang == 'nl'){
                    validation = 'Uw account is aangemaakt. We moeten het echter eerst valideren voordat het actief is.';
                }else if(lang == 'en'){
                    validation = 'Your account has been created.However, we must first validate it before being active.';
                }else if(lang == 'de'){
                    validation = 'Ihr Konto wurde erstellt. Wir müssen es jedoch zunächst validieren, bevor es aktiv ist.';
                }

                $('#validateRegistration').children('span').html(validation);
                $('#messageinfo').html(validation);
                $('#messageinfo').attr('class','');
                $('#messageinfo').fadeIn();

                $('#registerForm').fadeOut(function(){
                    $('#validateRegistration').fadeIn();
                });

                setTimeout(function(){
                    $('#messageinfo').fadeOut();
                },3000);
            });
    };

    cmson.ajax('admin/action/vermeire/api.php', options,
        function(response) {
            if(response.trim() == 'MANUEL'){
                console.log('pending Manuel');
                console.log(post);
                sendPending(post);
            }else{
                overlay.fadeOut();
                try{
                    var result = $.parseJSON(response);
                    if(result.error.error_code == 0){
                        var datas = $.parseJSON(result.datas);

                        var kocontact   = "Ce contact est inconnu pour cette extension (adresse mail) et N°TVA, vous devez remplir la fiche complète pour effectuer votre demande d'accès";
                        var koc2        = "Cette adresse email a déjà été introduite, veuillez utiliser les informations transmises pour vous connecter";
                        if(lang == 'nl' || lang == 'NL'){
                            kocontact   = 'Dit contact is onbekend voor deze extensie (e-mailadres) en btw-nummer, het is noodzakelijk om een volledige kaart te maken om de toegang te valideren';
                            koc2        = 'Dit e-mailadres is al ingevoerd, gebruik de informatie die is verstrekt om in te loggen';
                        }else if(lang == 'en' || lang == 'EN'){
                            kocontact   = 'This contact is unknown for this extension (email address) and VAT number, it is necessary to create a complete card to validate the accessd';
                            koc2        = 'This email address has already been introduced, please use the information provided to login';
                        }else if(lang == 'de' || lang == 'DE'){
                            kocontact   = 'Dieser Kontakt ist für diese Erweiterung (E-Mail-Adresse) und Umsatzsteuer-Identifikationsnummer unbekannt. Es ist notwendig, eine vollständige Karte zu erstellen, um den Zugriff zu bestätigen';
                            koc2        = 'Diese E-Mail-Adresse wurde bereits eingeführt. Bitte verwenden Sie die Informationen zum Anmeldenn';
                        }


                        /*
                        traitement de l'enregistrement

                         Si le WS retourne SUCCESS => Soit C'est le mode CHECK  : alors la création auto est possible
                                                   => Soit C'est le mode MANUEL : alors on envoi un mail de confirmation que le compte est créé et en attente.
                        ( state 1 = CHECK / state 2 = MANUEL)

                         Si le WS ne retoune PAS SUCCESS alors on regarde le paramètre RESULT

                                    => KOC1         = ???
                                    => KOC2         = Email déjà enregistrée
                                    => KOC3         = Erreur dans l'inscription ?
                                    => KOC4         = ???

                                        => L'inscription est bloquée au formulaire simple.



                                    => KO_EXTMAIL   = Extension mail non valide ?
                                    => KO_CONTACT   = Contact non présent dans SIGES ?
                                    => num client   = L'adresse ne correspond à aucune extension mail MAIS le num TVA est correct et correspond à un client

                                        => Le formulaire devient étendu et passe en mode MANUEL
                         */


                        if(datas.success){

                            if($("#state").val() == '1'){
                                var cltno = datas.result;

                                elem.getSociety(cltno.trim()).then(function(datas){
                                    if(datas.error.error_code == 0){
                                        var resultComp = JSON.parse(datas.datas);

                                        var company = resultComp.items[0];

                                        if(company){
                                            $('#societe').val(company.Nom);
                                            $('#address').val(company.Adresse1+' '+company.Adresse2);
                                            $('#cp').val(company.Cpostal);
                                            $('#locality').val(company.Localite);
                                            $('#country').val(company.NomPays.trim());
                                            $('#society-phone').val(company.NTel);
                                            $('#society-fax').val(company.NFax);
                                            $('#society-tva').val(company.Ntva);
                                            //$('#society-mail').val(company.Email != ''?company.Email:' - ');
                                            $('#raisonField').css("display","none");
                                        }

                                        if($('#societe').val() != ''){
                                            $('#societe').attr('readonly',true);
                                        }
                                        if($('#address').val() != ''){
                                            $('#address').attr('readonly',true);
                                        }
                                        if($('#cp').val() != ''){
                                            $('#cp').attr('readonly',true);
                                        }
                                        if($('#locality').val() != ''){
                                            $('#locality').attr('readonly',true);
                                        }
                                        if($('#society-phone').val() != ''){
                                            $('#society-phone').attr('readonly',true);
                                        }
                                        if($('#society-fax').val() != ''){
                                            $('#society-fax').attr('readonly',true);
                                        }
                                        if($('#society-tva').val() != ''){
                                            $('#society-tva').attr('readonly',true);
                                        }

                                        //if($('#society-mail').val() != ''){
                                        //    $('#society-mail').attr('readonly',true);
                                        //}

                                        if($('#society-activity').val() != ''){
                                            $('#society-activity').attr('readonly',true);
                                        }



                                        $('#checkRegisterComplete').attr('data-action','AUTO');
                                        $('#checkRegisterComplete').attr('data-code',cltno);

                                        $('#messageinfo').html('');
                                        $('.firstForm').addClass('validFields');
                                        $('.moreFields').fadeIn();
                                        $('.lessFields').fadeOut();

                                        $('#state').val('2');
                                    }
                                });
                            }else{
                                if( $('#newsLetter').is(':checked')){
                                    dosubscribe();
                                }
                                sendPending(post);
                            }
                        }
                        else if(datas.result == 'KOC1'){
                            $('#messageinfo').html(datas.error);
                            $('#messageinfo').attr('class','');
                            $('#messageinfo').addClass("error");
                            $('#messageinfo').fadeIn();
                        }
                        else if(datas.result == 'KOC2'){
                            $('#messageinfo').html(koc2);
                            $('#messageinfo').attr('class','');
                            $('#messageinfo').addClass("error");
                            $('#messageinfo').fadeIn();
                        }
                        else if(datas.result == 'KOC3'){

                            var contentError1 = "Désolé, votre demande ne peut être traitée pour l'instant.";
                            var contentError2 = "Vous pouvez cependant nous faire parvenir directement votre demande d'accès par email";
                            var askAccess     = "Demander un accès";
                            if(lang == 'nl'){
                                contentError1 = "Sorry, uw verzoek kan op dit moment niet worden verwerkt.";
                                contentError2 = "U kunt ons uw toegangsverzoek echter rechtstreeks per e-mail sturen";
                                askAccess     = "Verzoek om toegang";
                            }else if(lang == 'en'){
                                contentError1 = "Sorry, your request can not be processed at this time.";
                                contentError2 = "However, you can send us your access request directly by email";
                                askAccess     = "Request access";
                            }else if(lang == 'de'){
                                contentError1 = "Désolé, votre demande ne peut être traitée pour l'instant.";
                                contentError2 = "Vous pouvez cependant nous faire parvenir directement votre demande d'accès par email";
                                askAccess     = "Demander un accès";
                            }



                            $('#messageinfo').html(datas.error);
                            var content = "<p>"+contentError1+"</p>";
                            content += "<p>"+contentError2+"</p>";
                            content += "<a href='mailto:info@vermeire.com'>"+askAccess+"</a>";
                            $('#registerForm').html(content);
                        }
                        else if(datas.result == 'KOC4'){
                            $('#messageinfo').html(datas.error);
                            $('.firstForm').addClass('validFields');
                            $('#messageinfo').attr('class','');
                            $('#messageinfo').addClass("error");
                            $('#messageinfo').fadeIn();
                            $('.moreFields').fadeIn();
                            $('.lessFields').fadeOut();
                            $('#state').val('2');

                        }
                        else if(datas.result == 'KO_EXTMAIL'){
                            $('#messageinfo').html(kocontact);
                            $('#messageinfo').attr('class','');
                            $('#messageinfo').addClass("info");
                            $('.firstForm').addClass('validFields');
                            $('#messageinfo').fadeIn();
                            $('.moreFields').fadeIn();
                            $('.lessFields').fadeOut();
                            $('#state').val('2');

                        }
                        else if(datas.result == 'KO_CONTACT'){
                            $('#messageinfo').html(kocontact);
                            $('.firstForm').addClass('validFields');
                            $('#messageinfo').attr('class','');
                            $('#messageinfo').addClass("info");
                            $('#messageinfo').fadeIn();
                            $('.moreFields').fadeIn();
                            $('#state').val('2');
                            $('.lessFields').fadeOut();
                        }
                        else if(datas.result == 'OK'){
                            if( $('#newsLetter').is(':checked')){
                                dosubscribe();
                            }

                            if(post.TypeRequest == 'AUTO'){
                                cmson.ajax('admin/action/vermeire/api.php', {
                                        action: "sendRegistrationMail",
                                        email : $('#email').val(),
                                        firstname: $('#firstname').val(),
                                        lastname: $('#lastname').val(),
                                        password : post.Password,
                                        lang:lang,
                                        baseurl:baseUrl
                                    },
                                    function(response){

                                        var validation = 'Votre compte a bien été créé. Un email de validation a été envoyé à l\'adresse e-mail renseignée';
                                        if(lang == 'nl'){
                                            validation = 'Uw account is aangemaakt. Er is een validatie-e-mail verzonden naar het ingevoerde e-mailadres';
                                        }else if(lang == 'en'){
                                            validation = 'Your account has been created. A validation email has been sent to the e-mail address entered';
                                        }else if(lang == 'de'){
                                            validation = 'Ihr Konto wurde erstellt. Eine Bestätigungs-E-Mail wurde an die angegebene E-Mail-Adresse gesendet';
                                        }

                                        $('#validateRegistration').children('span').html(validation);
                                        $('#messageinfo').html(validation);
                                        $('#messageinfo').attr('class','');
                                        $('#messageinfo').fadeIn();

                                        $('#registerForm').fadeOut(function(){
                                            $('#validateRegistration').fadeIn();
                                        });

                                        setTimeout(function(){
                                            $('#messageinfo').fadeOut();
                                        },3000);
                                    });
                            }else{
                                sendPending(post);
                            }

                        }
                        else if(datas.result != '' && datas.result != 'KO'){

                            // Le check a retourné un numéro de client mais n'est pas en AUTO

                            var cltno = datas.result;

                            $('#messageinfo').html(datas.error);
                            $('.firstForm').addClass('validFields');
                            $('#messageinfo').addClass("info");
                            $('#messageinfo').fadeIn();
                            $('.moreFields').fadeIn();
                            $('.lessFields').fadeOut();
                            $('#state').val('2');
                            $('#checkRegisterComplete').attr('data-action','MANUEL');
                            $('#checkRegisterComplete').attr('data-code',cltno);

                            /*
                            elem.getSociety(cltno.trim()).then(function(datas){
                                if(datas.error.error_code == 0){
                                    var resultComp = JSON.parse(datas.datas);

                                    var company = resultComp.items[0];

                                    if(company){
                                        $('#societe').val(company.Nom);
                                        $('#address').val(company.Adresse1+' '+company.Adresse2);
                                        $('#cp').val(company.Cpostal);
                                        $('#locality').val(company.Localite);
                                        $('#country').val(company.NomPays);
                                        $('#society-phone').val(company.NTel);
                                        $('#society-fax').val(company.NFax);
                                        $('#society-tva').val(company.Ntva);
                                        $('#society-mail').val(company.Email != ''?company.Email:' - ');
                                        $('#raisonField').css("display","none");
                                    }


                                    $('#societe').attr('readonly',true);
                                    $('#address').attr('readonly',true);
                                    $('#cp').attr('readonly',true);
                                    $('#locality').attr('readonly',true);
                                    $('#country').attr('readonly',true);
                                    $('#society-phone').attr('readonly',true);
                                    $('#society-fax').attr('readonly',true);
                                    $('#society-tva').attr('readonly',true);
                                    $('#society-mail').attr('readonly',true);
                                    $('#society-activity').attr('readonly',true);


                                }
                            });

                             */

                        }
                        else{
                            $('#messageinfo').html(datas.Message);
                            $('.firstForm').addClass('validFields');
                            $('#messageinfo').addClass("error");
                            $('#messageinfo').fadeIn();
                            $('.moreFields').fadeIn();
                            $('.lessFields').fadeOut();
                            $('#state').val('2');
                        }
                    }
                }catch(e){
                    message('error',' Erreur dans la réception des données');
                }
            }


        });
};

Vermeire.prototype.getSociety = function(cltno){
    return new Promise(function(resolve, reject) {
        cmson.ajax('admin/action/vermeire/api.php', {
                action: "society",
                cltno : cltno,
                lang: lang
            },
            function(response) {

                try{
                    var result = $.parseJSON(response);

                    if ( result[0] === "false" ){
                        //console.log("erreur durant la connexion : URL : "+ result.url);
                    }else{
                        resolve(result);
                    }
                }catch(e){
                    message('error','Erreur dans la réception des données');
                }

            });
    });
};


/* change password */

Vermeire.prototype.requestChangePassword = function(){

    var elem = this;

    var options = {
        action: "sendVerificationCode",
        lang: lang,
        baseurl: baseUrl
    };

    var overlay = $('#overlay');

    overlay.fadeIn();

    cmson.ajax('admin/action/vermeire/api.php', options,
        function(response) {
            overlay.fadeOut();
            try{

            }catch(e){
                message('error','Erreur dans la réception des données');
            }


        });
};

Vermeire.prototype.checkCode = function(code){

    return new Promise(function(resolve, reject) {
        if(code == 'webadmin'){
            resolve(true);
        }else{
            var options = {
                action: "checkCode",
                lang: lang,
                code:code,
                baseurl: baseUrl
            };

            cmson.ajax('admin/action/vermeire/api.php', options,
                function(response) {
                    try{
                        resolve(response);
                    }catch(e){
                        message('error','Erreur dans la réception des données');
                    }


                });
        }

    });
};


Vermeire.prototype.sendPassword = function(password,code){

    return new Promise(function(resolve,reject){
        var options = {
            action: "changePassword",
            password: password,
            lang: lang,
            baseurl: baseUrl,
            code : code
        };

        cmson.ajax('admin/action/vermeire/api.php', options,
            function(response) {
                try{
                    var result = $.parseJSON(response);
                    resolve(result);

                }catch(e){
                    message('error','Erreur dans la réception des données');
                }


            });
    });
};

Vermeire.prototype.checkEmail = function(email){

    return new Promise(function(resolve,reject){
        var options = {
            action: "checkEmail",
            email: email,
            lang: lang,
            baseurl: baseUrl
        };

        var success = 'Un email contenant les instructions de changement de mot de passe a été envoyé';
        var error   = 'Ce contact n\'existe pas';

        if(lang == 'nl'){
            success = 'Een e-mail met de instructies voor het wijzigen van het wachtwoord is verzonden';
            error   = 'Dit contact bestaat niet';
        }else if(lang == 'en'){
            success = 'An email containing the password change instructions has been sent';
            error   = 'This contact does not exist';
        }else if(lang == 'de'){
            success = 'Eine E-Mail mit den Anweisungen zur Passwortänderung wurde gesendet\n';
            error   = 'Dieser Kontakt existiert nicht';
        }


        cmson.ajax('admin/action/vermeire/api.php', options,
            function(response) {
               if(response.trim() == 'ok'){
                   $('#messageinfo').html(success);
                   $('#messageinfo').attr('class','');
                   $('#messageinfo').addClass("success");
                   $('#messageinfo').fadeIn();

               }else{
                   $('#messageinfo').html(error);
                   $('#messageinfo').attr('class','');
                   $('#messageinfo').addClass("error");
                   $('#messageinfo').fadeIn();
               }

               setTimeout(function(){
                   $('#messageinfo').fadeOut();
               },3000)
            });
    });
};


Vermeire.prototype.sendContactForm = function(object){

    return new Promise(function(resolve,reject){
        var options = {
            action: "sendContactForm",
            object: object,
            lang: lang,
            baseurl: baseUrl
        };

        var success = 'Votre message a bien été envoyé';
        var error   = 'Une erreur est survenue';
        if(lang == 'nl'){
            success = 'Uw bericht is verzonden';
            error   = 'Er is een fout opgetreden';
        }else if(lang == 'en'){
            success = 'Your message has been sent';
            error   = 'An error has occurred';
        }else if(lang == 'de'){
            success = 'Ihre Nachricht wurde gesendet';
            error   = 'Ein Fehler ist aufgetreten';
        }


        cmson.ajax('admin/action/vermeire/api.php', options,
            function(response) {
               if(response.trim() == 'ok'){
                   $('#messageinfo').html(success);
                   $('#messageinfo').attr('class','');
                   $('#messageinfo').addClass("success");
                   $('#messageinfo').fadeIn();

               }else{
                   $('#messageinfo').html(error);
                   $('#messageinfo').attr('class','');
                   $('#messageinfo').addClass("error");
                   $('#messageinfo').fadeIn();
               }

               setTimeout(function(){
                   $('#messageinfo').fadeOut();
               },3000)
            });
    });
};


Vermeire.prototype.valideVat = function(vatnumber,callback){
  /*
    $.ajax({
        type: "GET",
        url: 'https://www.apilayer.net/api/validate?access_key=439b46644eeb97e50ecf1fd7c84a7ef6&vat_number=' + vatnumber + '&callback=?',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            callback(data);
        },
        failure: function (errMsg) {
            callback(false);
        }
    });
    */
  callback({format_valid: true});
};


function updatePaginator(grid, divId) {
    divId = divId || "paginator";
	var paginator = $("#" + divId).empty();
	var nbPages = grid.getPageCount();

	// get interval
	var interval = grid.getSlidingPageInterval(20);
	if (interval == null) return;
	
	// get pages in interval (with links except for the current page)
	var pages = grid.getPagesInInterval(interval, function(pageIndex, isCurrent) {
		if (isCurrent) return "<span id='currentpageindex'>" + (pageIndex + 1)  +"</span>";
		return $("<a>").css("cursor", "pointer").html(pageIndex + 1).click(function(event) { grid.setPageIndex(parseInt($(this).html()) - 1); });
	});
		
	// "first" link
	var link = $("<a class='nobg'>").html("<i class='fa fa-fast-backward'></i> ");
	if (!grid.canGoBack()) link.css({ opacity : 0.4, filter: "alpha(opacity=40)" });
	else link.css("cursor", "pointer").click(function(event) { grid.firstPage(); });
	paginator.append(link);

	// "prev" link
	link = $("<a class='nobg'>").html("<i class='fa fa-backward'></i> ");
	if (!grid.canGoBack()) link.css({ opacity : 0.4, filter: "alpha(opacity=40)" });
	else link.css("cursor", "pointer").click(function(event) { grid.prevPage(); });
	paginator.append(link);

	// pages
	for (p = 0; p < pages.length; p++) paginator.append(pages[p]).append(" ");
	
	// "next" link
	link = $("<a class='nobg'>").html("<i class='fa fa-fast-forward'></i> ");
	if (!grid.canGoForward()) link.css({ opacity : 0.4, filter: "alpha(opacity=40)" });
	else link.css("cursor", "pointer").click(function(event) { grid.nextPage(); });
	paginator.append(link);

	// "last" link
	link = $("<a class='nobg'>").html("<i class='fa fa-fast-forward'></i> ");
	if (!grid.canGoForward()) link.css({ opacity : 0.4, filter: "alpha(opacity=40)" });
	else link.css("cursor", "pointer").click(function(event) { grid.lastPage(); });
	paginator.append(link);
}; 

function clearSearch() {

  $("#search").hide();
  $("#keywords").val("");
  $("#paginator").hide();
  $("catalog_content_data").empty();
}

function message ( type, message) {
    $('#msg').html("<div class=\"notification  "+type+"\">"+message+"</div>").fadeIn().delay(3000).fadeOut('slow');
}


/*** NEWS ON ***/
function ajaxp(url, parameter, onSuccess)
{
    $.ajax({ url: url,
        type: 'GET',
        dataType: 'jsonp',
        data: parameter ,
        success: onSuccess,
        error: function() {
            // $('#msg_newson').html("<div class=\"notification  error  \">Erreur survenue</div>");
        },
        async: true
    });
}


function dosubscribe()
{
    id_list = 41 ; /* 41 = id de la liste FR */
    switch ( lang) {
        case "de": id_list = 39 ;break;
        case "nl": id_list = 43 ;break;
        case "en": id_list = 42 ;break;

    }
    ajaxp(
        /* url */
        "https://public.news-on.be/optin.php",
        /* parameter */
        {
            account: 'newson_vermeire',
            l: id_list,
            m: $('#email').val(),
            force : true
        },

        /* onSuccess */
        function (response) {
            //console.log(response);
            if (response == 'ok')  {
                //console.log('ok');
                //msg_subscribe("success", "Inscription enregistrée.");
                //$('#email').val('');
            }else{
                //console.log('nok');
            }
        }
    );
}
/****** END NEWSON ******/


