// JavaScript Document

function postForm(inputObject, urlObject, formObject, divObject) {
    var iObject = "#" + inputObject;
    var fObject = "#" + formObject;
    var dObject = "#" + divObject;

    $(iObject).click(function() {
        $.ajax({
            url: urlObject,
            type: 'post',
            dataType: 'html',
            data: $(fObject).serialize(),
            success: function(data) {
                //alert(data);
                $(dObject).html(data);
            }
        });
    });

}

function postFormSimpleReturnV2(urlObject, formObject, divObject) {
   // $('#loader').show();
   
   
    //  alert(divObject + " " + urlObject + " " +  formObject);
    var fObject = "#" + formObject;
    var dObject = "#" + divObject;
	
	$("#send23").click( function (e) {
			e.preventDefault();			
			$.ajax({
				url: $(dObject).attr("action"),
				type: 'post',
				dataType: 'html',
				data: $(fObject).serialize(),
				success: function(data) {
					
					//alert(data);
					//$(dObject).html(data);
					 alert ('GR');
					var obj = jQuery.parseJSON( data);
				   
				   if(obj.errorCode == 0 ) {
					   
					   alert( obj.errorMessage );
						//  alert(data);
					$("#" + toDiv).load(urlObject);
					$('#loader').hide();
					   
				   }
				   else {
					   
					   alert( obj.errorMessage );
				   }
					
					$('#loader').hide();
				}
			});		
						return false;
	});
	
	
}

function postFormV2(inputObject, urlObject, formObject, divObject) {
    var iObject = "#" + inputObject;
    var fObject = "#" + formObject;
    var dObject = "#" + divObject;

    $(iObject).click(function() {
        $.ajax({
            url: urlObject,
            type: 'post',
            dataType: 'html',
            data: $(fObject).serialize(),
            success: function(data) {
                //alert(data);
                $(dObject).html(data);
            }
        });
    });

}

function  processFormExtendedZA(formName, toDiv, rpage) {
	//alert("SISI");
    //$('#loader').show();
    $("#" + formName).unbind('submit').bind('submit', function() {
        $.post($(this).attr("action"), $(this).serialize(), function(data) {
 
		   var obj = jQuery.parseJSON( data);
		   
		   if(obj.errorCode == 0 ) {
			   
			   alert( obj.errorMessage );
			    //  alert(data);
            $("#" + toDiv).load(rpage);
            $('#loader').hide();
			   
		   }
		   else {
			   
			   alert( obj.errorMessage );
		   }
         
        });
        return false; // prevent normal submit
    });

}

function postFormSelect(inputObject, formObject, divObject) {
    var iObject = "#" + inputObject;
    var fObject = "#" + formObject;
    var dObject = "#" + divObject;
    var pltm;
    $(dObject).empty();
    $(iObject).on("change", function(event) {

        console.log(document.getElementById("platformId").value);
        $("#module-dtls").load("do_menu_gen.php",
                {
                    "platformId": document.getElementById("platformId").value
                }
        );
        event.stopPropagation();
        // $(this).stopPropagation();
    });



    return false;
}


function postFormSelectm1(inputObject, formObject, divObject) {
    $(document).ready(function() {
        $("#myform").submit(function() {
            $.post(
                    'process.php',
                    $(this).serialize(),
                    function(data) {
                        $("#results").html(data)
                    }
            );
            return false;
        });
    });

}



function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
    var rv = -1; // Return value assumes failure.
    if (navigator.appName == 'Microsoft Internet Explorer')
    {
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
            rv = parseFloat(RegExp.$1);
    }
    return rv;
}
function checkVersion()
{
    var msg = "You're not using Internet Explorer.";
    var ver = getInternetExplorerVersion();

    if (ver > -1)
    {
        if (ver >= 8.0)
            msg = "You're using a recent copy of Internet Explorer."
        else
            msg = "You should upgrade your copy of Internet Explorer.";
    }
    alert(msg);
}


function loadPageDiv(pageName, frObject, toDiv) {
    $('#loader').show();
    var pObject = "#" + toDiv;
    var fObject = "#" + frObject;
    /*
     $(pObject).load( pageName);
     evt.preventDefault();
     */
    /*
     $.ajax({
     type: 'GET',
     url: pageName ,
     success: function(data){
     if(data != null) $(pObject).html(data);
     }
     }); */

    $(fObject).click(function() {
        $(pObject).one('load', function() {

            (this).load(pageName);

        });

    });
    // $(this).stopPropagation();


}


function loadTab(pageName, frObject, toDiv, ldata)
{
    $('#loader').show();
    var pObject = "#" + toDiv;
    var fObject = "#" + frObject;
    // alert(ldata)   ;
    // $("#preloader").show();
    $.ajax(
            {
                type: 'POST',
                url: pageName,
                cache: false,
                data: {'menuId': ldata},
                success: function(message)
                {
                    $(pObject).html(message, function() {

                        $('#loader').hide();

                    }



                    );

                    $('#loader').hide();

                    //$("#preloader").hide();             
                }
            });

}


// JavaScript Document

function addObjectBottom() {

    var elmt;

    elmt = '<select>   <option> Lire un fichier son </option>   <option> Lire un fichier son et option de réecoute </option>   <option> Lire un menu </option> </select> <br> <div id="newItem"> </div>';

    document.getElementById('newItem').innerHTML = elmt;



}



function displayRuleContent2() {
    var ruleId = document.getElementById('ruleId').value;






}

function getSmsTemplateSaved(userId) {

    window.open("showSmsTemplateSaved.php?owid=" + userId, "_blank", "width=600,height=400,scrollbars");

}





function show_sheduling(id, toDiv) {

    //alert(document.getElementById('activateShed').checked);

    if (document.getElementById(id).checked)
        document.getElementById(toDiv).style.display = 'block';
    else
        document.getElementById(toDiv).style.display = 'none';

}


function popOfferList(processFile, itemId) {
    processFile = "getOfferList.php";
    var url = "products/scm/iad/" + processFile + "?itemId=" + itemId;

    window.open(url, "", "width=550,height=300,scrollbars=yes");

}


function sendtobox(nodeId, nodeValue, nodeName) {

    var offerCodeIdBox = "offerCode" + nodeId;
    var offerCodeNameBox = "offerCode" + nodeId + "" + nodeId;
    var offerCodeControlBox = "offerCode" + nodeId + "Control";

    window.opener.document.getElementById(offerCodeIdBox).value = nodeValue;
    window.opener.document.getElementById(offerCodeNameBox).value = nodeName;
    window.opener.document.getElementById(offerCodeControlBox).checked = true;

    window.close();

}

function cleanBox(nodeId) {

    var offerCodeIdBox = "offerCode" + nodeId;
    var offerCodeNameBox = "offerCode" + nodeId + "" + nodeId;
    var offerCodeControlBox = "offerCode" + nodeId + "Control";

    document.getElementById(offerCodeIdBox).value = "";
    document.getElementById(offerCodeNameBox).value = "";
    document.getElementById(offerCodeControlBox).checked = false;

    window.close();

}



function iadEditApp(itemId) {

    window.open("iad_update_apps.php?itemId=" + itemId, "", "width=800,height=600,scrollbars=yes");

}


function iadUpdateOffer(itemId) {

    window.open("iad_update_offer.php?itemId=" + itemId, "", "width=800,height=600,scrollbars=yes");

}


function editUsers(itemId) {

    window.open("update_user.php?itemId=" + itemId, "", "width=800,height=600,scrollbars=yes");

}


function postFormSimpleReturn(urlObject, formObject, divObject) {
    $('#loader').show();
    //  alert(divObject + " " + urlObject + " " +  formObject);
    var fObject = "#" + formObject;
    var dObject = "#" + divObject;

    $.ajax({
        url: urlObject,
        type: 'post',
        dataType: 'html',
        data: $(fObject).serialize(),
        success: function(data) {
            //alert(data);
            $(dObject).html(data);
            $('#loader').hide();
        }
    });

}



function sendRequest(method, url, content, callback) {
    // additional data for the callback

    alert(content);
    var request = {
        method: method,
        url: url
    };

    $.ajax({
        type: method,
        url: url,
        data: content
    }).done(function(data, status, xhr) {
        if (callback)
            callback(xhr.status, data, request);
    }).fail(function(xhr, status) {
        if (callback)
            callback(xhr.status, xhr.response, request);
    });
}
;


function updateFromInput(lang, currentValue, pageName, refreshPage, toDiv) {


    var dObject = "#" + toDiv;
    var dWork = 0;
    var y = window.prompt(lang, currentValue);


    // alert( lang + "  "  + currentValue + "  "  + pageName + "  "  + sParams + "  "  + refreshPage + "  "  + toDiv) ;

    //alert(dObject);

    if (y) {
        $('#loader').show();
        pageName = pageName + "&cc=" + y;
        $.get(pageName, function(dWork) {
            // my_var contains whatever that request returned

            if (dWork == 1) {

                alert("MISE A JOUR REUSSIE !");
                $(dObject).load(refreshPage);

            }
            else {

                alert("IMPOSSIBLE DE FAIRE LA MISE A JOUR !");
            }

            $('#loader').hide();
        })
    }



}

function deleteSimpleLine(lang, pageName, refreshPage, toDiv) {

    var dObject = "#" + toDiv;
    var dWork = 0;
    y = window.confirm(lang);


    // alert( lang + "  "  + currentValue + "  "  + pageName + "  "  + sParams + "  "  + refreshPage + "  "  + toDiv) ;

    //alert(dObject);
    if (y) {
        $('#loader').show();
        $.get(pageName, function(dWork) {

            // my_var contains whatever that request returned

            if (dWork == 1) {

                alert("OPERATION REUSSIE !");
                $(dObject).load(refreshPage);

            }
            else {

                alert("IMPOSSIBLE DE SUPPRIMER !");
            }

            $('#loader').hide();

        });

    }


}



function addNDC(baseDir, toDiv) {

    var execPage = baseDir + "/add_ndc.php";

    var contentData = '<form method="post" id="addNDCFrm" action="' + execPage + '"  onsubmit="return false"> <table width="100%" border="0">   <tr>     <td width="26%">Nouveau</td>     <td width="17%"><input type="text" name="newNdc" id="newNdc" size="10"  /></td>     <td width="57%"><input type="submit" name="save" id="save" value="Ajouter" onclick="postFormSimpleJquery12( \'addNDCFrm\', \'' + toDiv + '\');"  /></td>  </tr></table></form>';

    $("#dynAddition").html(contentData);




}


function addShortCode(baseDir, toDiv) {

    var execPage = baseDir + "/add_shortcode.php";

    var contentData = '<form method="post" id="addNDCFrm" action="' + execPage + '"  onsubmit="return false"> <table width="100%" border="0">   <tr>     <td width="26%">Nouveau</td>     <td width="17%"><input type="text" name="newNdc" id="newNdc" size="10"  /></td>     <td width="57%"><input type="submit" name="save" id="save" value="Ajouter" onclick="postFormSimpleJquery12( \'addNDCFrm\', \'' + toDiv + '\');"  /></td>  </tr></table></form>';

    $("#dynAddition1").html(contentData);




}

function addSimpleItem(baseDir, toDiv, processFile, fromDiv) {

    var execPage = baseDir + "/" + processFile;
    var contentData = '<form method="post" id="addNDCFrm" action="' + execPage + '"  onsubmit="return false"> <table width="100%" border="0">   <tr>     <td width="26%">Nouveau</td>     <td width="17%"><input type="text" name="newNdc" id="newNdc" size="10"  /></td>     <td width="57%"><input type="submit" name="save" id="save" value="Ajouter" onclick="postFormSimpleJquery12( \'addNDCFrm\', \'' + toDiv + '\');"  /></td>  </tr></table></form>';

    $("#" + fromDiv).html(contentData);


}


function navButtonLoad(pageName, pageOption, toDiv) {
    $('#loader').show();
    var dObject = "#" + toDiv;

    pageName = pageName + "?" + pageOption;
    $.get(pageName, function(dWork) {
        // my_var contains whatever that request returned

        $(dObject).html(dWork);
        $('#loader').hide();

    })


}




function editPage(pageName, pageOption, toDiv) {
    $('#loader').show();
    var dObject = "#" + toDiv;

    pageName = pageName + "?" + pageOption;
    $.get(pageName, function(dWork) {
        // my_var contains whatever that request returned

        $(dObject).html(dWork);
        $('#loader').hide();

    })

}



function getPage(pageName, toDiv) {
    $('#loader').show();
    var dObject = "#" + toDiv;

    $.get(pageName, function(dWork) {
        // my_var contains whatever that request returned

        $(dObject).html(dWork);
        $('#loader').hide();

    })

}


function displayRuleContent(baseDir, toDiv) {
    $('#loader').show();
    var ruleId = document.getElementById('ruleId').value;
    var dObject = "#" + toDiv;
    var execPage = baseDir + "/iad_ruletoweb_gen.php?itemId=" + ruleId;

    $.get(execPage, function(dWork) {
        // my_var contains whatever that request returned

        $(dObject).html(dWork);
        $('#loader').hide();


    })


}



function getDoc(frame) {
    var doc = null;

    // IE8 cascading access check
    try {
        if (frame.contentWindow) {
            doc = frame.contentWindow.document;
        }
    } catch (err) {
    }

    if (doc) { // successful getting content
        return doc;
    }

    try { // simply checking may throw in ie8 under ssl or mismatched protocol
        doc = frame.contentDocument ? frame.contentDocument : frame.document;
    } catch (err) {
        // last attempt
        doc = frame.document;
    }
    return doc;
}

function submitComplexForm(toDiv) {
    var dObject = "#" + toDiv;
    $("#multiform").submit(function(e)
    {
        var formObj = $(this);
        var formURL = formObj.attr("action");

        if (window.FormData !== undefined)  // for HTML5 browsers
        {

            var formData = new FormData(this);
            $.ajax({
                url: formURL,
                type: "POST",
                data: formData,
                mimeType: "multipart/form-data",
                contentType: false,
                cache: false,
                processData: false,
                success: function(data, textStatus, jqXHR)
                {
                },
                error: function(jqXHR, textStatus, errorThrown)
                {
                }
            });
            e.preventDefault();
        }
        else  //for olden browsers
        {
            //generate a random id
            var iframeId = "unique" + (new Date().getTime());

            //create an empty iframe
            var iframe = $('<iframe src="javascript:false;" name="' + iframeId + '" />');

            //hide it
            iframe.hide();

            //set form target to iframe
            formObj.attr("target", iframeId);

            //Add iframe to body
            iframe.appendTo("body");
            iframe.load(function(e)
            {
                var doc = getDoc(iframe[0]);
                var docRoot = doc.body ? doc.body : doc.documentElement;
                var data = docRoot.innerHTML;

                alert(data);
                //data return from server.



            });

        }

    });
    $("#multiform").submit();

}


function ajaxComplexForm(formId, toDiv) {


    var options = {
        success: function(message)
        {

            alert("22535");
            $("#" + toDiv).html(message);
            //clear everything

        },
        complete: function(response)
        {
            alert("22535");
            $("#" + toDiv).html(response);
        }
    };

    $("#" + formId).ajaxForm(options);
}



function submitFormComplex(formId, toDiv) {

    $('#' + formId).submit();

    var options = {
        success: function()
        {


        },
        complete: function(response)
        {
            alert(response.responseText);
        }

    };

    $("#multiform").ajaxForm(options);

}



function deleteComplexLine(lang, pageName, options, refreshPage, toDiv) {

    var dObject = "#" + toDiv;
    var dWork = 0;
    y = window.confirm("Voulez-vous supprimer cette ligne?");


    // alert( lang + "  "  + currentValue + "  "  + pageName + "  "  + sParams + "  "  + refreshPage + "  "  + toDiv) ;

    //alert(dObject);

    if (y) {
        $('#loader').show();
        if (options != null)
            pageName = pageName + "?" + options;
        $.get(pageName, function(dWork) {
            // my_var contains whatever that request returned

            if (dWork == 1) {

                alert("OPERATION REUSSIE !");
                $(dObject).load(refreshPage);

            }
            else {

                alert("IMPOSSIBLE DE SUPPRIMER !");
            }

            $('#loader').hide();
        })

    }


}

function submitDefaultForm(formId, toDiv) {

    $('#' + formId).submit();

    var options = {
        success: function()
        {


        },
        complete: function(response)
        {
            alert(response.responseText);
            $('#' + toDiv).html(response.responseText);
        }

    };

    $('#' + formId).ajaxForm(options);

}




function postFormSimpleJquery(fromButton, toDiv) {

    $("form").submit(function() {
        $.post($(this).attr("action"), $(this).serialize(), function(data) {

            //alert(data);
            $("#" + toDiv).html(data);
        });
        return false; // prevent normal submit
    });

}

function postFormSimpleJquery12(fromButton, toDiv) {
	//alert("SISI");
    $('#loader').show();
    $("#" + fromButton).unbind('submit').bind('submit', function() {
        $.post($(this).attr("action"), $(this).serialize(), function(data) {

            //alert(data);
            $("#" + toDiv).html(data);
            $('#loader').hide();
        });
        return false; // prevent normal submit
    });

}


function postFormSimpleJquery1(fromButton, toDiv) {

    $("#" + fromButton).submit(function(event) {
        alert("Handler for .submit() called.");
        event.preventDefault();
    });

}


function getPageAndRefresh(pageName, toDiv) {

    var answer = confirm("Veuillez confirmer l'action ?");

    if (answer) {

        $('#loader').show();
        var dObject = "#" + toDiv;

        $.get(pageName, function(dWork) {


            $(dObject).html(dWork);
            $('#loader').hide();

        });

    }

}


function getPageAndRefreshDerived(pageName, toDiv, actionType, targetPage, targetDiv) {

    var message;
    if (actionType == -1 || actionType == 5 || actionType == 4)
        message = " Voulez-vous démarrer cette campagne ?";
    else
        message = " Voulez-vous arrêter cette campagne ?";


    var answer = confirm(message);

    if (answer) {

        $('#loader').show();
        var dObject = "#" + toDiv;
        var dtargetDiv = "#" + targetDiv;

        $.get(pageName, function(dWork) {


            $(dObject).html(dWork);

            //

            setTimeout(
                    function()
                    {
                        $(dtargetDiv).load(targetPage);
                    }, 3000);
            $('#loader').hide();





        });




    }

}



function blockUnblockUser(pageName, pageOption, actionType, toDiv) {
    var message;
    var newAction;

    if (actionType == 0) {

        message = " Voulez-vous désactiver cet utilisateur ?";
        newAction = 1;
    }
    else {

        message = " Voulez-vous activer cet utilisateur?";
        newAction = 0;
    }


    var answer = confirm(message);


    if (answer) {
        $('#loader').show();
        var dObject = "#" + toDiv;

        pageName = pageName + "?" + pageOption + "&type=" + newAction;
        $.get(pageName, function(dWork) {
            // my_var contains whatever that request returned

            $(dObject).html(dWork);
            $('#loader').hide();

        });

    }

}


function getPageFull(pageName, options, toDiv) {
    $('#loader').show();
    var dObject = "#" + toDiv;


    $.get(pageName, function(dWork) {
        // my_var contains whatever that request returned

        $(dObject).html(dWork);
        $('#loader').hide();

    })

}



function openPopupPage(filename, options) {
    var url = filename + "?" + options;

    window.open(url, "", "width=550,height=300,scrollbars=yes");

}


function sendtoboxDefault(nodeId, type, nodeValue) {

    switch (type) {

        case "append" :
            window.opener.document.getElementById(nodeId).value = window.opener.document.getElementById(nodeId).value + ";" + nodeValue;

            break;
        case "overwrite" :
            window.opener.document.getElementById(nodeId).value = nodeValue;

            break;


    }

    window.close();

}



function  processFormExtended(formName, toDiv, rpage) {

    $("#" + formName).unbind('submit').bind('submit', function() {
        $.post($(this).attr("action"), $(this).serialize(), function(data) {
 
		   var obj = jQuery.parseJSON( data);
		   
		   if(obj.errorCode == 0 ) {
			   
			   //alert( obj.errorMessage );
			 
			 //    $.alert( obj.errorMessage );
			 
			 $.alert({
					title: 'Alert!',
					content: 'Simple alert!',
				});
			    //  alert(data);
            $("#" + toDiv).load(rpage);
            $('#loader').hide();
			   
		   }
		   else {
			   
			   $.alert( obj.errorMessage );
		   }
         
        });
        return false; // prevent normal submit
    });

   
}





function  populateFieldName(page, toDiv) {
	
	var sourceId = document.getElementById("sourceId").value ;
	
	getPage(page+"?sourceId="+sourceId, toDiv) ;
	
	
}


function prep_modal(toDiv, rpage)
{
  $(".modal").each(function() {

   var element = this;
	var pages = $(this).find('.modal-split');
            
  if (pages.length != 0)
  {
    	pages.hide();
    	pages.eq(0).show();

    	var b_button = document.createElement("button");
                b_button.setAttribute("type","button");
          			b_button.setAttribute("class","btn btn-primary");
          			b_button.setAttribute("style","display: none;");
          			b_button.innerHTML = "Pr&eacute;c&eacute;dent";

    	var n_button = document.createElement("button");
                n_button.setAttribute("type","button");
          			n_button.setAttribute("class","btn btn-primary");
          			n_button.innerHTML = "Suivant";
					
	   var c_button = document.createElement("button");
                c_button.setAttribute("type","button");
          			c_button.setAttribute("class","btn close-btn");
          			c_button.innerHTML = "Fermer";

        $(this).find('.modal-footer').html("");
    	$(this).find('.modal-footer').append(c_button).append(b_button).append(n_button);
		
		


    	var page_track = 0;

    	$(n_button).click(function() {
        
        this.blur();

    		if(page_track == 0)
    		{
    			$(b_button).show();
    		}

    		if(page_track == pages.length-2)
    		{
    			$(n_button).text("Soumettre");
    		}

        if(page_track == pages.length-1)
        {
          $(element).find("form").submit();
        }

    		if(page_track < pages.length-1)
    		{
    			page_track++;

    			pages.hide();
    			pages.eq(page_track).show();
    		}


    	});

    	$(b_button).click(function() {

    		if(page_track == 1)
    		{
    			$(b_button).hide();
    		}

    		if(page_track == pages.length-1)
    		{
    			$(n_button).text("Suivant");
    		}

    		if(page_track > 0)
    		{
    			page_track--;

    			pages.hide();
    			pages.eq(page_track).show();
    		}


    	});
		
		
		$(c_button).click(function() {

    		$('#loader').loading({
		  message : "Chargement...",
		  theme : 'dark'
		  
		});
		   $("#extendedModal").modal('toggle');
		   $("#"+ toDiv).load(rpage);
           $('#loader').loading('stop');


    	});
		

  }

  });
}



function populate_select(fromId, toId, page){
	

$( "."+fromId ).change(function() {
 alert($(this).val());
});

//alert(document.getElementById('moduleId').value);
	
}



function view_ticket_details(url) {

    window.open(url, "", "scrollbars=yes");

}


function view_table_all(id) {
    
    var tdData = "";
    var separator = ',';
    var el = document.getElementById(id);
    
    $(el).find('thead').find('tr').each(function() {
					tdData += "\n";					
						$(this).find('th').each(function(index,data) {
							tdData += '"' + $(this) + '"' + separator;
							
						});
						tdData = $.trim(tdData);
						tdData = $.trim(tdData).substring(0, tdData.length -1);
					});
//console.log(tdData);
 var table = $('#'+id).DataTable();
 

 
var curData ="";
var i =0;
table.rows().data().map((row) => {
  // each row is an array where each column is an element in the array
  // as a string
  var rlen = row.length;
 // console.log("RLENGTH" +" = " + rlen);
  var sl="";
 for(var j = 0 ; j < rlen; j++){
     
     
     if(row[j].startsWith("<")){
         
         sl+=";";
     }
     else {
         sl+= row[j]+";";
     }
     
    // curData += "CELL" +j + " = " + row[j] ;
   // alert("APP" +j + " = " + row[j]);
   // console.log("APP" +j + " = " + row[j]);
 
        }
        console.log(sl);
}
);

//console.log(curData);

}
