// JavaScript Document

var _basse_urlS = "Commercial";
var _link_urlS = "requests/Requests/public_get_twoDet_pkg";
var _link_url1 = "requests/Requests/public_get_details";
var _link_url2 = "requests/Requests/public_get_twoDet_three";
var _link_url3 = "requests/Requests/public_get_twoDet";
var _link_url4 = "cpanel/Cpanel/public_get_detaild";
var _redirect_page = "http://localhost/Commercial/";

// get Data
function getDataForSelectByOne(param_one  , param_two  , param_three  , param_four  ,  param_five  , param_six  ){
	 GeneralShowloading();
	 ///
	 var linkURL = window.location.href;
 	 var URLS = linkURL.substring(linkURL.lastIndexOf("/") + 1);
	 if(isInt(URLS)){
		 var urls_links = _link_url1+'/'+param_one+'/'+param_two+'/'+param_three;
	 }else{
		 var urls_links = _basse_urlS+'/'+_link_url1+'/'+param_one+'/'+param_two+'/'+param_three;
	 }
	 ///
	 setTimeout(function() {
		$.ajax({
			url: urls_links,
			type: 'POST',
			datatype: 'json',
			success: function (data) { 
			  if(data.length ==0){
				  $('#'+param_four+' option').remove();
				  $('#'+param_four).append($('<option/>').attr("value", '').text(''));
				  $('#'+param_four).prop("selected",true);
				  $('#'+param_four).change();
				  GeneralHideloading();
			   }else{
					$('#'+param_four+' option').remove();
					$('#'+param_four).append($('<option/>').attr("value", '').text('---اختر---'));
					$.each(data,function (i,option) {
						$('#'+param_four).append($('<option/>').attr("value", eval(param_five)).text(eval(param_six)));
					})
					//$('#'+param_four).change();
					GeneralHideloading();
			   }
			 },
			error: function (jqXHR, textStatus, errorThrown) {  }
		});
     }, 500);
}

//  get Data
function getDataForSelectByTwo(param_one , param_two , param_three , param_four , param_five , param_six , param_seven  ){
	 GeneralShowloading();
	 ///
	 var linkURL = window.location.href;
 	 var URLS = linkURL.substring(linkURL.lastIndexOf("/") + 1);
	 if(isInt(URLS)){
		 var urls_links = _link_urlS+'/'+param_one+'/'+param_two+'/'+param_three+'/'+param_four;
	 }else{
		 var urls_links = _basse_urlS+'/'+_link_urlS+'/'+param_one+'/'+param_two+'/'+param_three+'/'+param_four;
	 }
	 ///
	 setTimeout(function() {
		$.ajax({
			url: urls_links,
			type: 'POST',
			datatype: 'json',
			success: function (data) { 
			  if(data.length ==0){
				  $('#'+param_five+' option').remove();
				  $('#'+param_five).append($('<option/>').attr("value", '').text(''));
				  $('#'+param_five).prop("selected",true);
				  $('#'+param_five).change();
				  GeneralHideloading();
			   }else{
					$('#'+param_five+' option').remove();
					$('#'+param_five).append($('<option/>').attr("value", '').text('---اختر---'));
					$.each(data,function (i,option) {
						$('#'+param_five).append($('<option/>').attr("value", eval(param_six)).text(eval(param_seven)));
					})
					//$('#'+param_five).change();
					GeneralHideloading();
			   }
			 },
			error: function (jqXHR, textStatus, errorThrown) {  }
		});
     }, 500);
}

//  get Data
function getDataForSelectByThree(param_one , param_two , param_three , param_four , param_five , param_six , param_seven , param_egiht){
	 GeneralShowloading();
	 ///
	 var linkURL = window.location.href;
 	 var URLS = linkURL.substring(linkURL.lastIndexOf("/") + 1);
	 if(isInt(URLS)){
		 var urls_links = _link_url2+'/'+param_one+'/'+param_two+'/'+param_three+'/'+param_four+'/'+param_five;
	 }else{
		 var urls_links = _basse_urlS+'/'+_link_url2+'/'+param_one+'/'+param_two+'/'+param_three+'/'+param_four+'/'+param_five;
	 }
	 ///
	 setTimeout(function() {
		$.ajax({
			url: urls_links,
			type: 'POST',
			datatype: 'json',
			success: function (data) { 
			  if(data.length ==0){
				  $('#'+param_six+' option').remove();
				  $('#'+param_six).append($('<option/>').attr("value", '').text(''));
				  $('#'+param_six).prop("selected",true);
				  $('#'+param_six).change();
				  GeneralHideloading();
			   }else{
					$('#'+param_six+' option').remove();
					$('#'+param_six).append($('<option/>').attr("value", '').text('---اختر---'));
					$.each(data,function (i,option) {
						$('#'+param_six).append($('<option/>').attr("value", eval(param_seven)).text(eval(param_egiht)));
					})
					//$('#'+param_six).change();
					GeneralHideloading();
			   }
			 },
			error: function (jqXHR, textStatus, errorThrown) {  }
		});
     }, 500);
}

//  get Data
function getDataForSelectByTwoValidate(param_one , param_two , param_three , param_four , param_five , param_six , param_seven , param_eight , param_nine , param_ten , param_elev  ){
	 GeneralShowloading();
	 ///
	 var linkURL = window.location.href;
 	 var URLS = linkURL.substring(linkURL.lastIndexOf("/") + 1);
	 if(isInt(URLS)){
		 var urls_links = _link_urlS+'/'+param_one+'/'+param_two+'/'+param_three+'/'+param_four;
	 }else{
		 var urls_links = _basse_urlS+'/'+_link_urlS+'/'+param_one+'/'+param_two+'/'+param_three+'/'+param_four;
	 }
	 ///
	 setTimeout(function() {
		$.ajax({
			url: urls_links,
			type: 'POST',
			datatype: 'json',
			success: function (data) { 
			   if(data.length ==0){
					  $('#'+param_five+' option').remove();
					  $('#'+param_five).append($('<option/>').attr("value", '').text(''));
					  $('#'+param_five).prop("selected",true);
					  $('#'+param_five).change();
					  GeneralHideloading();
			   }else{
					$('#'+param_five+' option').remove();
					$('#'+param_five).append($('<option/>').attr("value", '').text('---اختر---'));
					$.each(data,function (i,option) {
						if(eval(param_eight) == eval(param_elev)){
							$.ajax({
								url: _basse_urlS+'/'+_link_urlS+'/'+param_one+'/'+param_two+'/'+param_nine+'/'+eval(param_ten),
								type: 'POST',
								datatype: 'json',
								success: function (datas) { 
								  if(datas.length ==0){
									  $('#'+param_five+' option').remove();
									  $('#'+param_five).append($('<option/>').attr("value", '').text(''));
									  $('#'+param_five).prop("selected",true);
									  $('#'+param_five).change();
								   }else{
										$('#'+param_five+' option').remove();
										$('#'+param_five).append($('<option/>').attr("value", '').text('---اختر---'));
										$.each(datas,function (i,option) {
											$('#'+param_five).append($('<option/>').attr("value", eval(param_six)).text(eval(param_seven)));
										})
										//$('#'+param_five).change();
										GeneralHideloading();
								   }
								 },
								error: function (jqXHR, textStatus, errorThrown) {  }
							});
						}
					})
					//$('#'+param_five).change();
					GeneralHideloading();
			   }
			 },
			error: function (jqXHR, textStatus, errorThrown) {  }
		});
     }, 500);
}

// get Data from API
function getDataBySSN(ssn , arr){
	GeneralShowloading();
	// Get Last component URL
	var linkURL = window.location.href;
 	var URLS = linkURL.substring(linkURL.lastIndexOf("/") + 1);
	/// check
	if (checkidno(ssn)){
		$.ajax({
			url: 'https://im-server.gedco.ps:8001/apis/GetData/'+ssn,
			type: 'POST',
			datatype: 'json',
			success: function (data) { 
			  if(data.length ==0){ GeneralHideloading(); }else{
				 var obj = $.parseJSON(data);
				 $(obj).each(function(i,val){
					  $.each(val.DATA,function(k,element){ 
					   	  if(element.DETH_DT == null){
							  var FULL_NAME = element.FNAME_ARB+" "+element.SNAME_ARB+" "+element.TNAME_ARB+" "+element.LNAME_ARB;
							  for(var i = 0 ; i < arr.length ; i++){
								  $('#'+arr[i]).val(FULL_NAME);
							  }
							  $('#TXT_RELATIONSHIP').val(element.SOCIAL_STATUS);
							  // check
							  if(URLS == 'CreateRequest'){ // اشتراك جديد
								$('#TXT_ID').val(ssn);
							  }
							  ///
							  $('#TXT_NAME_Free_FIRST').val(element.SNAME_ARB);
							  $('#TXT_NAME_Free_TWO').val(element.TNAME_ARB);
							  $('#TXT_NAME_Free_FOUR').val(element.LNAME_ARB);
						  }else{
							  	var FULL_NAME = element.FNAME_ARB+" "+element.SNAME_ARB+" "+element.TNAME_ARB+" "+element.LNAME_ARB;
								swal.fire(
									"رقم الهويةالمدرج صاحبه متوفى", 
									"بتاريخ"+element.DETH_DT+"وعليه يلزم تقديم معاملة تغيير اسم ", 
									"error");
								for(var i = 0 ; i < arr.length ; i++){
									$('#'+arr[i]).val(FULL_NAME);
								}
								$('#TXT_RELATIONSHIP').val('متوفى');
						  }
					  })
				 })
				 GeneralHideloading();
			   }
			 },
			error: function (jqXHR, textStatus, errorThrown) {  }
		});
		/// فحص طبيعة العمل
		$.ajax({
			url: _basse_urlS+'/'+_link_url1+'/SERVICE_NEW/GOV_GAZA_2022_v_GET/'+ssn,
			type: 'POST',
			datatype: 'json',
			success: function (data) { 
			  if(data.length ==0){ GeneralHideloading(); }else{
				  $("select[name='DL_APPLICANT_JOB']").val(1).prop('selected',true);
				  $("select[name='DL_APPLICANT_JOB']").change();
			  }
			}
		});
	}
}

//function 
function fetchDataFromSql(param_one  , param_two  , param_three  , param_four ){
	 GeneralShowloading();
	 ///
	 var linkURL = window.location.href;
 	 var URLS = linkURL.substring(linkURL.lastIndexOf("/") + 1);
	 if(isInt(URLS)){
		 var urls_links = _link_url1+'/'+param_one+'/'+param_two+'/'+param_three;
	 }else{
		 var urls_links = _basse_urlS+'/'+_link_url1+'/'+param_one+'/'+param_two+'/'+param_three;
	 }
	 ///
	 setTimeout(function() {
			 $.ajax({
                url: urls_links,
                type: 'POST',
                datatype: 'json',
                success: function (data) { 
                          if(data.length ==0){ GeneralHideloading(); 
						  		for(var i = 0 ; i < param_four.length ; i++){
									$.each(param_four[i],function(k,element){
										$('#'+k).val('');
									})
								}
						  }else{
							    for(var i = 0 ; i < param_four.length ; i++){
									$.each(param_four[i],function(k,element){
										$('#'+k).val(eval(element));
									})
								}
								GeneralHideloading();
                           }
                 },
                error: function (jqXHR, textStatus, errorThrown) {  }
            });
		 
     }, 500);
}
//function 
function fetchDataFromSqlByServiceType(param_one  , param_two  , param_three  , param_four , param_five ){
	 GeneralShowloading();
	 ///
	 var linkURL = window.location.href;
 	 var URLS = linkURL.substring(linkURL.lastIndexOf("/") + 1);
	 if(isInt(URLS)){
		 var urls_links =  _link_url1+'/'+param_one+'/'+param_two+'/'+param_three;
	 }else{
		 var urls_links =  _basse_urlS+'/'+_link_url1+'/'+param_one+'/'+param_two+'/'+param_three;
	 }
	 ///
	 setTimeout(function() {
			 $.ajax({
                url: urls_links,
                type: 'POST',
                datatype: 'json',
                success: function (data) { 
                          if(data.length ==0){ GeneralHideloading(); }else{
							    for(var i = 0 ; i < param_four.length ; i++){
									$.each(param_four[i],function(k,element){
										if(k == 'DL_PHASE'){
											$('#'+k).val(eval(element));
										    getDataForSelectByTwo('TSG_SETTING_PKG' , 'SERVICES_GET_BY_TYPEPHASE' ,
										    eval(element) , param_five , 'DL_SERVICE_ID' , 'option.SERVICE_ID' ,
											'option.SERVICE_NAME');
										}else{
											$('#'+k).val(eval(element));
										}
									})
								}
								GeneralHideloading();
                           }
                 },
                error: function (jqXHR, textStatus, errorThrown) {  }
            });
		 
     }, 500);
}
//function change display
function changeCssDisplay(arr , type , display){
	GeneralShowloading();
	for(var i = 0 ; i < arr.length ; i++){
		if(type == 'class'){
			if(display == 'block'){ console.log($('.'+arr[i]).css('display','block')); }else if(display == 'none'){ $('.'+arr[i]).css('display','none'); }
			
		}else if(type == 'id'){
			if(display == 'block'){ $('#'+arr[i]).css('display','block'); }else if(display == 'none'){ $('#'+arr[i]).css('display','none'); }
		}
	}
	GeneralHideloading();
}

//load function
function GeneralShowloading(){
	KTApp.block('.kt-portlet__body', { overlayColor: '#000000', type: 'v2', state: 'primary', message: 'جاري جلب البيانات...' });
	KTApp.block('.card-body', { overlayColor: '#000000', type: 'v2', state: 'primary', message: 'جاري جلب البيانات...' });
}

function GeneralShowMaploading(){
	KTApp.block('#MapView', { overlayColor: '#000000', type: 'v2', state: 'primary', message: 'جاري جلب البيانات...' });
//	KTApp.block('.card-body', { overlayColor: '#000000', type: 'v2', state: 'primary', message: 'جاري جلب البيانات...' });
}

//Hide load function
function GeneralHideloading(){
	KTApp.unblock('.kt-portlet__body');
	KTApp.unblock('.card-body');
}
function GeneralHideMaploading(){
	KTApp.unblock('#MapView');
}

// Function Check SSN 
function checkidno(idno){
	MultID  = [1,2,1,2,1,2,1,2];
	SumID=0;i=0;X=0;
		r = ""+idno;//.replace(/\s/g,'');
		intRegex = /^\d+$/;
		if (r.length==9 && (intRegex.test(r)) )
		{
			for (var i=0;i<MultID.length;i++)
			{ 
				x=MultID[i] * r[i];
				if (x>9)
					x=parseInt(x.toString()[0]) + parseInt(x.toString()[1]);
				SumID=SumID+x;	
			}
			if (SumID % 10 != 0)
				SumID = ( 10 * (Math.floor(SumID / 10) + 1 )) - SumID
			else
				SumID = 0;
			if (SumID == r[8])
				return true;
			else
				return false;	
		}
		else	
			return false;
}
/// function get Data From Services
function getDataFromService(SSN , REQUEST){
   // Remove Tr
   $(".Lists table tbody tr").remove();
   $(".Lists1 table tbody tr").remove();
   $(".Lists2 table tbody tr").remove();
   $(".Lists3 table tbody tr").remove();
   ///
   var linkURL = window.location.href;
   var URLS = linkURL.substring(linkURL.lastIndexOf("/") + 1);
   if(isInt(URLS)){
		 var urls_links =  _link_url1+'/EBLLC_PKG/SUBSCRIBERS_TB_GET_ID';
		 var urls_links1 = _link_url1+'/EBLLC_PKG/SUBSCRIBERS_TB_GET_ID';
   }else{
		 var urls_links =  _basse_urlS+'/'+_link_url1+'/EBLLC_PKG/SUBSCRIBERS_TB_GET_ID';
		 var urls_links1 = _basse_urlS+'/'+_link_url1+'/EBLLC_PKG/SUBSCRIBERS_TB_GET_ID';
   }
   ///
   $.ajax({
		url: 'https://im-server.gedco.ps:8001/apis/GetFullData/'+SSN,
		type: 'POST',
		datatype: 'json',
		success: function (data) { 
				  if(data.length ==0){ }else{
						 var json = $.parseJSON(data);
						 $(json).each(function(i,val){
						    $.each(val.DATA,function(k,element){
							   var name = element.FNAME_ARB+" "+element.SNAME_ARB+" "+element.TNAME_ARB+" "+element.LNAME_ARB;
							   if(element.RELATIVE_CD == 1 || element.RELATIVE_CD == 2){	
								  $.ajax({
									url: urls_links+'/'+element.IDNO_RELATIVE,
									type: 'POST',
									datatype: 'json',
									success: function (datasERdRE) { 
										 if(datasERdRE.length ==0){ 
											 $(".Lists tbody").append(GetTableRowAdoptTaft([],
											   [0,element.IDNO_RELATIVE,name,element.PREV_LNAME_ARB,element.MOTHER_ARB,element.BIRTH_DT,
											   element.DETH_DT,element.SEX,element.SOCIAL_STATUS]));
										 }else{
											$(".Lists tbody").append(GetTableRowAdoptTaft([],
											   [datasERdRE[0].NO,element.IDNO_RELATIVE,name,element.PREV_LNAME_ARB,element.MOTHER_ARB,
											   element.BIRTH_DT,element.DETH_DT,element.SEX,element.SOCIAL_STATUS]));
										 }
								     },
									 error: function (jqXHR, textStatus, errorThrown) {  }
									});
							   }
									if(element.RELATIVE_CD == 1){
									  $.ajax({
										url: 'https://im-server.gedco.ps:8001/apis/GetFullData/'+element.IDNO_RELATIVE,
										type: 'POST',
										datatype: 'json',
										success: function (dataSA) { 
											if(dataSA.length ==0){ }else{
											   var subscchildren = 0 ;
                                               var subscchildren3 = 0 ;
                                               var json1 = $.parseJSON(dataSA);
                                               $(json1).each(function(i1,val1){
                                                 $.each(val1.DATA,function(k1,element1){
                                                 var name1 = element1.FNAME_ARB+" "+element1.SNAME_ARB+" "+element1.TNAME_ARB+" "+element1.LNAME_ARB;	
													 if(element1.RELATIVE_CD == 3 && element1.SEX_CD == 1){
														 $.ajax({
															url: urls_links1+'/'+element1.IDNO_RELATIVE,
															type: 'POST',
															datatype: 'json',
															success: function (datasERd) { 
																 if(datasERd.length ==0){  
																	  $(".Lists3 tbody").append(GetTableRowAdoptTaft([],
																	   [0,element1.IDNO_RELATIVE,name1,element1.PREV_LNAME_ARB,
																	   element1.MOTHER_ARB,element1.BIRTH_DT,
																	   element1.DETH_DT,element1.SEX,element1.SOCIAL_STATUS]));
																 }else{ 
																	 $(".Lists3 tbody").append(GetTableRowAdoptTaft([],
																	   [datasERd[0].NO,element1.IDNO_RELATIVE,name1,element1.PREV_LNAME_ARB,
																	   element1.MOTHER_ARB,element1.BIRTH_DT,
																	   element1.DETH_DT,element1.SEX,element1.SOCIAL_STATUS]));
																 }
															 },
															 error: function (jqXHR, textStatus, errorThrown) {  }
														});
													 }else if(element1.RELATIVE_CD == 1){
														 $.ajax({
															url: urls_links1+'/'+element1.IDNO_RELATIVE,
															type: 'POST',
															datatype: 'json',
															success: function (datasERd) { 
																 if(datasERd.length ==0){  
																	  $(".Lists4 tbody").append(GetTableRowAdoptTaft([],
																	   [0,element1.IDNO_RELATIVE,name1,element1.PREV_LNAME_ARB,
																	   element1.MOTHER_ARB,element1.BIRTH_DT,element1.DETH_DT,element1.SEX,
																	   element1.SOCIAL_STATUS]));
																 }else{ 
																	 $(".Lists4 tbody").append(GetTableRowAdoptTaft([],
																	   [datasERd[0].NO,element1.IDNO_RELATIVE,name1,element1.PREV_LNAME_ARB,
																	   element1.MOTHER_ARB,element1.BIRTH_DT,element1.DETH_DT,element1.SEX,
																	   element1.SOCIAL_STATUS]));
																 }
															 },
															 error: function (jqXHR, textStatus, errorThrown) {  }
														 });
													 }
												 });
											   });
																		
											}
										 },
										 error: function (jqXHR, textStatus, errorThrown) {  }
									  });
									}else if(element.RELATIVE_CD == 3){
										$.ajax({
											url: urls_links+'/'+element.IDNO_RELATIVE,
											type: 'POST',
											datatype: 'json',
											success: function (datasERd1) { 
												if(datasERd1.length ==0){
                                                      $(".Lists2 tbody").append(GetTableRowAdoptTaft([],[0,element.IDNO_RELATIVE,
													  name,element.PREV_LNAME_ARB,element.MOTHER_ARB,element.BIRTH_DT,
                                                      element.DETH_DT,element.SEX,element.SOCIAL_STATUS]));
                                                 }else{
                                                      $(".Lists2 tbody").append(GetTableRowAdoptTaft([],
                                                       [datasERd1[0].NO,element.IDNO_RELATIVE,name,
													   element.PREV_LNAME_ARB,element.MOTHER_ARB,element.BIRTH_DT,
                                                       element.DETH_DT,element.SEX,element.SOCIAL_STATUS]));
                                                 }
											 },
											 error: function (jqXHR, textStatus, errorThrown) {  }
										});
									}else if(element.RELATIVE_CD == 4){
										
										$.ajax({
											url: urls_links+'/'+element.IDNO_RELATIVE,
											type: 'POST',
											datatype: 'json',
											success: function (datasERd123) { 
												if(datasERd123.length ==0){
                                                      $(".Lists1 tbody").append(GetTableRowAdoptTaft([],[0,element.IDNO_RELATIVE,
													  name,element.PREV_LNAME_ARB,element.MOTHER_ARB,element.BIRTH_DT,
                                                      element.DETH_DT,element.SEX,element.SOCIAL_STATUS]));
                                                 }else{
                                                      $(".Lists1 tbody").append(GetTableRowAdoptTaft([],
                                                       [datasERd123[0].NO,element.IDNO_RELATIVE,name,
													   element.PREV_LNAME_ARB,element.MOTHER_ARB,element.BIRTH_DT,
                                                       element.DETH_DT,element.SEX,element.SOCIAL_STATUS]));
                                                 }
											 },
											 error: function (jqXHR, textStatus, errorThrown) {  }
										});
										
									}
								
							});
						 });
						
				   }
		 },
		 error: function (jqXHR, textStatus, errorThrown) {  }
	});
   if(isInt(URLS)){  
	   <!----------// Insert Into DataBase //----------------->
	   $.post('requests/Requests/subCheckSSNSelect/'+SSN+'/'+REQUEST,$("#Form_Table_"+table).serializeArray(),'','json');
   }else{
	   <!----------// Insert Into DataBase //----------------->
	   $.post(_basse_urlS+'/requests/Requests/subCheckSSNSelect/'+SSN+'/'+REQUEST,$("#Form_Table_"+table).serializeArray(),'','json');   
   }
}
///
function isDoubleClicked(element) {
    //if already clicked return TRUE to indicate this click is not allowed
    if (element.data("isclicked")) return true;

    //mark as clicked for 1 second
    element.data("isclicked", true);
    setTimeout(function () {
        element.removeData("isclicked");
    }, 20000);

    //return FALSE to indicate this click was allowed
    return false;
}
///
function ShowMessageConfirmPost(){
	swal.fire({
		title: 'هل أنت متأكد من حفظ البيانات المدرجة',
		text: "عزيزي المستخدم, في حال قمت بالضغط على زر التأكيد ,سيقوم النظام بإدراج البيانات",
		type: 'warning',
		showCancelButton: true,
		confirmButtonText: 'تأكيد'
	}).then(function(result) {
		if(result.value){
			return true;
		}else{
			return false;
		}
	});
}
///
function ShowSuccessMessage(){
	swal.fire({
		title: 'جاري حفظ البيانات!',
		text: 'يرجى الإنتظار لمدة 2 ثانية',
		timer: 2000,
		onOpen: function() {
			swal.showLoading()
		}
	}).then(function(result) {
		if (result.dismiss === 'timer') {
			swal.fire({
				position: 'top-left',
				type: 'success',
				title: 'تمت الإضافة والتعديل بنجاح',
				showConfirmButton: false,
				timer: 1500
			});
		}
	})	
}
//
function add_note_req_check(id , subsc , notes){
    $('#TXT_REQUEST_APP_SERIAL_NOTE').val(id);
    $('#TXT_SUBSCRIBER_NOTE').val(subsc);
    $('#TXT_NOTE_LAST').val(notes);
    $('#TXT_NOTE_DET').val('');
    $(".ModalNotes").modal('show');
}
//
function add_note_req_check_pmeter(id , subsc , notes){
    $('#TXT_REQUEST_APP_SERIAL_NOTE1').val(id);
    $('#TXT_SUBSCRIBER_NOTE1').val(subsc);
    $('#TXT_NOTE_LAST1').val(notes);
    $('#TXT_NOTE_DET1').val('');
    $(".ModalNotesPmeter").modal('show');
}

///
function save_notes(){
	if (isDoubleClicked($(this))) return;
	swal.fire({
		title: 'هل أنت متأكد من حفظ البيانات المدرجة',
		text: "عزيزي المستخدم, في حال قمت بالضغط على زر التأكيد ,سيقوم النظام بإدراج البيانات",
		type: 'warning',
		showCancelButton: true,
		confirmButtonText: 'تأكيد'
	}).then(function(result) {
		if(result.value){
			$.post($('#Note_Table_Modals').attr('action'),$('#Note_Table_Modals').serialize(), function(r){
				$(r).each(function(index, element) {
					if(element['o_success'] == 0){
						 danger_msg('تحذير..',element['o_msgtxt']);
					}
					if(element['o_success'] == 1){
						 ShowSuccessMessage();
						 $(".ModalNotes").modal('hide');
					}
				})
			},'json');
			return false;
		}
	});
}
///
function save_notes_pmeter(){
	if (isDoubleClicked($(this))) return;
	swal.fire({
		title: 'هل أنت متأكد من حفظ البيانات المدرجة',
		text: "عزيزي المستخدم, في حال قمت بالضغط على زر التأكيد ,سيقوم النظام بإدراج البيانات",
		type: 'warning',
		showCancelButton: true,
		confirmButtonText: 'تأكيد'
	}).then(function(result) {
		if(result.value){
			$.post($('#Note_Table_Modals_Pmeter').attr('action'),$('#Note_Table_Modals_Pmeter').serialize(), function(r){
				$(r).each(function(index, element) {
					if(element['o_success'] == 0){
						 danger_msg('تحذير..',element['o_msgtxt']);
					}
					if(element['o_success'] == 1){
						 ShowSuccessMessage();
						 $(".ModalNotesPmeter").modal('hide');
					}
				})
			},'json');
			return false;
		}
	});
}
///
function save_returns(){
	if (isDoubleClicked($(this))) return;
	swal.fire({
		title: 'هل أنت متأكد من ارجاع المعاملة',
		text: "عزيزي المستخدم, في حال قمت بالضغط على زر التأكيد ,سيقوم النظام بارجاع المعاملة",
		type: 'warning',
		showCancelButton: true,
		confirmButtonText: 'تأكيد'
	}).then(function(result) {
		if(result.value){
			$.post(_basse_urlS+'/requests/Requests/ReturnReq1',$('#Return_Table_Modals').serialize(), function(r){
				$(r).each(function(index, element) {
					if(element['o_success'] == 0){
						 danger_msg('تحذير..',element['o_msgtxt']);
					}
					if(element['o_success'] == 1){
						 ShowSuccessMessage();
						 $(".ModalReturns").modal('hide');
					}
				})
			},'json');
			return false;
		}
	});
}
///
function save_returns_pmeter(){
	if (isDoubleClicked($(this))) return;
	swal.fire({
		title: 'هل أنت متأكد من ارجاع المعاملة',
		text: "عزيزي المستخدم, في حال قمت بالضغط على زر التأكيد ,سيقوم النظام بارجاع المعاملة",
		type: 'warning',
		showCancelButton: true,
		confirmButtonText: 'تأكيد'
	}).then(function(result) {
		if(result.value){
			$.post(_basse_urlS+'/pmeterrequest/PmeterRequest/return_request',$('#Return_Table_Modals_Pmeter').serialize(), function(r){
				$(r).each(function(index, element) {
					if(element['o_success'] == 0){
						 danger_msg('تحذير..',element['o_msgtxt']);
					}
					if(element['o_success'] == 1){
						 ShowSuccessMessage();
						 $(".ModalReturnsPmeter").modal('hide');
						 get_to_link(window.location.href);
					}
				})
			},'json');
			return false;
		}
	});
}
///
function get_technical(param_one , param_two , param_three ){
	 GeneralShowloading();
	 ///
	 var linkURL = window.location.href;
 	 var URLS = linkURL.substring(linkURL.lastIndexOf("/") + 1);
	 if(isInt(URLS)){
		 var urls_links =  _link_url3+'/CONSTANTS_DETAIL_BRANCH_GET/28/'+param_two;
		 var urls_links1 =  _link_url1+'/SERVICES_PKG/TECHNICAL_TEAMS_TB_GET_BY_DATE/'+param_one;
	 }else{
		 var urls_links =  _basse_urlS+'/'+_link_url3+'/CONSTANTS_DETAIL_BRANCH_GET/28/'+param_two;
		 var urls_links1 =  _basse_urlS+'/'+_link_url1+'/SERVICES_PKG/TECHNICAL_TEAMS_TB_GET_BY_DATE/'+param_one;
	 }
	 ///
	 setTimeout(function() {
		$.ajax({
			url: urls_links,
			type: 'POST',
			datatype: 'json',
			success: function (datas) { 
			  if(datas.length ==0){ GeneralHideloading();  }else{
				$.ajax({
					url: urls_links1,
					type: 'POST',
					datatype: 'json',
					success: function (data) { 
					   $(".ListIns tbody tr").remove();
					   if(data.length ==0){ GeneralHideloading(); }else{
							  $(data).each(function(index, element) {
								 if(element.DEPT_NO == datas[0].VID  && element.ACTIVE == 2 && element.BRANCH_ID == param_three){
								   $(".ListIns tbody").append(GetTableRowsTechnical([],
								   [element.TECHNICAL_TEAM_ID,element.TECHNICAL_TEAM_MANAGER_NAME,element.F_DATE,element.T_DATE]));
								 }
								
							  });
							GeneralHideloading();
							/// Show Modal
							$(".ModalTechTeam").modal('show');
					   }
					 },
					error: function (jqXHR, textStatus, errorThrown) {  }
				});
			   }
			   
			 },
			error: function (jqXHR, textStatus, errorThrown) {  }
		});
     }, 500);
}
function _showReport(url, top) {

	var mModal = top ? '#top_modal' : '#report';
	console.log('', mModal);
	if (url.indexOf('reports?report=') > -1 || url.indexOf('reports?type=') > -1) {

		$(mModal + ' .modal-dialog').width(window.screen.width - 60);
		$(mModal + ' .modal-dialog').height('90%');

	}


	$(mModal + ' .modal-body').html('<iframe width="100%" height="100%" frameborder="0"   allowtransparency="true" src="' + url + '"></iframe>');
	$(mModal).modal();
}
function _showReport1(url, top,subscriber) {

	var mModal = top ? '#top_modal' : '#report';
	console.log('', subscriber);
	url+=subscriber+""
	if (url.indexOf('reports?report=') > -1 || url.indexOf('reports?type=') > -1) {

		$(mModal + ' .modal-dialog').width(window.screen.width - 60);
		$(mModal + ' .modal-dialog').height('90%');

	}


	$(mModal + ' .modal-body').html('<iframe width="100%" height="100%" frameborder="0"   allowtransparency="true" src="' + url + '"></iframe>');
	$(mModal).modal();
}
//
$('#kt_maxlength_41').on('change',function(){
    var NewVal = $(this).val();
	$(".FormCheckIsRequestModal").find("input[name='TXT_INTERNAL_APPLICANT_ID']").val(NewVal);
	$(".FormCheckIsRequestModal table tbody tr").remove();
    /// Show Modal
    $(".ModalCheckIsRequest").modal('show');
});
///// GET IS REQUESTS LAST
function Search_CheckIsRequest(){
   var APPLICANT_ID = $(".FormCheckIsRequestModal").find("input[name='TXT_INTERNAL_APPLICANT_ID']").val();
   var APPLICANT_NAME = $(".FormCheckIsRequestModal").find("input[name='TXT_INTERNAL_APPLICANT_NAME']").val();
   var PKG = 'SERVICE_NEW';
   var PROCEDURE = 'REQUEST_APP_WITHOUT_ROW';
   $(".FormCheckIsRequestModal table tbody tr").remove();
   var newArr = {PKG:PKG,PROCEDURE:PROCEDURE,APPLICANT_ID:APPLICANT_ID,APPLICANT_NAME:APPLICANT_NAME}
   get_data(_basse_urlS+'/'+_link_url4,newArr ,function(data){
	 $(data).each(function(index, element) {
		   $(".FormCheckIsRequestModal table tbody").append(GetTableRowsCheckISRequests([],[element.REQUEST_APP_SERIAL,element.SUBSCRIBER,element.APPLICANT_NAME,element.BRANCH_ID_NAME,element.SERVICE_TYPE_NAME,element.PHASE_TYPE_NAME,element.SERVICE_ID_NAME,element.STAGE_DEFINITION_ID_NAME,element.REQUEST_APP_DATE,element.MAX_DATE1,element.STATUS_NAME]));
	  })
   },'json');
		
}
// عرض مودال إلغاء الطلب
function close_rquest(NewVal){
	GeneralShowloading();
    setTimeout(function() {
    	GeneralHideloading();
        $('#CONS_N_CLOSE').val(NewVal);
        $('#TXT_REQ_STATUS_CLOSE').val(3);
        /// Show Modal
        $(".Modal2General").modal('show');
    }, 500); 
}
/// إلغاء الطلب
function CloseRequestGeneral(){
	if (isDoubleClicked($(this))) return;
    swal.fire({
        title: 'هل أنت متأكد من إلغاء الطلب',
        text: "عزيزي المستخدم, في حال قمت بالضغط على زر التأكيد ,سيقوم النظام بتغيير حالة المعاملة",
        type: 'warning',
        showCancelButton: true,
        confirmButtonText: 'تأكيد'
    }).then(function(result) {
        if(result.value){
			$.post(_basse_urlS+'/requestaction/RequestAction/closeFunction',$("#Form_Table2").serializeArray(),
			    function(r){
					$(r).each(function(index, element) {
						if(element['o_success'] == 0){
							 danger_msg('تحذير..',element['o_msgtxt']);
						}
						if(element['o_success'] == 1){
							 success_msg('رسالة','تم إلغاء الطلب بنجاح ..');
							 /// Show Modal
							 $(".Modal2General").modal('hide');
						}
			   		})
		   		},'json');
		   	    return false;
        }
    });
}
/// عرض مودال استكمال الطلب
function complete_rquest(NewVal){
	GeneralShowloading();
    setTimeout(function() {
    	GeneralHideloading();
        $('#CONS_N_WILL').val(NewVal);
        $('#TXT_REQ_STATUS_WILL').val(1);
        /// Show Modal
        $(".Modal5General").modal('show');
    }, 500);
}
// استكمال الطلب
function WILLRequestGeneral(){
	if (isDoubleClicked($(this))) return;
    swal.fire({
        title: 'هل أنت متأكد من استكمال الطلب',
        text: "عزيزي المستخدم, في حال قمت بالضغط على زر التأكيد ,سيقوم النظام بإستكمال الطلب",
        type: 'warning',
        showCancelButton: true,
        confirmButtonText: 'تأكيد'
    }).then(function(result) {
        if(result.value){
               $.post(_basse_urlS+'/requestaction/RequestAction/WillFunction',$("#Form_Table5").serializeArray(),
               function(r){
                    $(r).each(function(index, element) {
                        if(element['o_success'] == 0){
                             danger_msg('تحذير..',element['o_msgtxt']);
                        }
                        if(element['o_success'] == 1){
                             success_msg('رسالة','تم  بنجاح ..');
                             //// اكمال المعاملة وفحص اذا كان في الاستقبال
							 var reqest_ret = $("#Form_Table5").find("input[name='CONS_N_WILL']").val();
							 ReCompleteFunction(reqest_ret);
                        }
                    })
               },'json');
               return false;
        }
    });
}
// when click new request button
function CompleteRequestGeneral(){
	var APPLICANT_ID = $(".FormCheckIsRequestModal").find("input[name='TXT_INTERNAL_APPLICANT_ID']").val();
	var APPLICANT = $(".Requests_form").find("select[name='DL_APPLICANT']").val();
    if(APPLICANT == 1 ){
    	var textField = ["TXT_APPLICANT_NAME", "txt_fname", "txt_fname_BEN"];
    }else{
    	var textField = ["TXT_APPLICANT_NAME"];
    }
    getDataBySSN(APPLICANT_ID , textField);
	/// Hide Modal
    $(".ModalCheckIsRequest").modal('hide');
}
/// show note of request from any actions
function note_action_rquest(NewVal){
	GeneralShowloading();
	$(".ListIns_INTERNAL32 tbody tr").remove();
	$.ajax({
        url: _basse_urlS+'/'+_link_url1+'/SERVICE_NEW/REQUEST_APP_HINTS_TB_GET/'+NewVal,
        type: 'POST',
        datatype: 'json',
        success: function (data) { 
            if(data.length ==0){  
                GeneralHideloading();
            }else{ 
                $(data).each(function(index, element) {
                	$(".ListIns_INTERNAL32 tbody").append(GetTableRowAdoptTaft([],
                    [element.REQUEST_APP_SERIAL,element.HINTS,element.ENTRY_DATE,element.ENTRY_USER_NAME]));
                });
                GeneralHideloading();
                /// Show Modal
                $(".Modal321_Free").modal('show');
            }

         },
        error: function (jqXHR, textStatus, errorThrown) {  }
    }); 
}
/// Re Complete Request Selected
function ReCompleteFunction(reqest_ret){
	// Get Last component URL
	var linkURL = window.location.href;
 	var URLS = linkURL.substring(linkURL.lastIndexOf("/") + 1);
	$.ajax({
        url: _basse_urlS+'/'+_link_url1+'/SERVICES_PKG/REQUEST_APP_TB_GET/'+reqest_ret,
        type: 'POST',
        datatype: 'json',
        success: function (data) { 
            if(data.length ==0){  
                GeneralHideloading();
            }else{ 
                if(data[0].STAGE_DEFINITION_ID == 1){
					// check
					if(URLS == 'CreateRequest'){ // اشتراك جديد
						location.replace(_redirect_page+"EditRequest/"+reqest_ret);
					}else if(URLS == 'CreateLargeAmpir'){ // تكبير / نقل اشتراك
						location.replace(_redirect_page+"EditLargeAmpir/"+reqest_ret);
					}else if(URLS == 'CreateSubscriberAct'){ // تفعيل - إيقاف اشتراك 
						location.replace(_redirect_page+"EditSubscriberAct/"+reqest_ret);
					}else if(URLS == 'CreateCounterChange'){ // تغيير عداد
						location.replace(_redirect_page+"EditCounterChange/"+reqest_ret);
					}else if(URLS == 'CreateRequestUpdate'){ // خدمة تعديل اشتراك 
						location.replace(_redirect_page+"EditRequestUpdate/"+reqest_ret);
					}else if(URLS == 'CreateChangePayment'){ // تغيير آلية السداد 
						location.replace(_redirect_page+"EditChangePayment/"+reqest_ret);
					}else if(URLS == 'CreatePowerLine'){ //  خط كهرباء إضافي 
						location.replace(_redirect_page+"EditPowerLine/"+reqest_ret);
					}else if(URLS == 'CreateChangeConnect'){ // تعديل برمجة عداد ذكي 
						location.replace(_redirect_page+"EditChangeConnect/"+reqest_ret);
					}else if(URLS == 'CreateEnergy'){ //  ارجاع فائض الطاقة 
						location.replace(_redirect_page+"EditEnergy/"+reqest_ret);
					}else if(URLS == 'CreateClearanceRequest'){ //  خلو طرف 
						location.replace(_redirect_page+"EditClearanceRequest/"+reqest_ret);
					}else if(URLS == 'CreateCommercialGenerator'){ //   ترخيص مولد تجاري  
						location.replace(_redirect_page+"EditCommercialGenerator/"+reqest_ret);
					}
				}else{
					danger_msg('تحذير..','الطلب في مرحلة متقدمة عن مرحلة الإستقبال');
				}
            }

         },
        error: function (jqXHR, textStatus, errorThrown) {  }
    });
}
//
$('#Request_Mahmoud a').on('click',function(){
    if (isDoubleClicked($(this))) return;
});
// test url
function isInt(value) {
    var er = /^-?[0-9]+$/;
    return er.test(value);
}
/// عرض مودال تقديم طلب استثناء
function add_exception_manual(REQ,SUBSC){
	GeneralShowloading();
    setTimeout(function() {
    	GeneralHideloading();
        $(".Form_ADD_EXCEPTION").find("input[name='TXT_REQUEST_APP_SERIAL_MODAL']").val(REQ);
        $(".Form_ADD_EXCEPTION").find("input[name='TXT_SUBSCRIBER_MODAL']").val(SUBSC);
        /// Show Modal
        $(".Free_MODAL_ADD_EXCEPTION").modal('show');
    }, 500);
}
//
function SAVE_ADD_EXCEPTION(){
	if (isDoubleClicked($(this))) return;
	swal.fire({
		title: 'هل أنت متأكد من حفظ البيانات المدرجة',
		text: "عزيزي المستخدم, في حال قمت بالضغط على زر التأكيد ,سيقوم النظام بإدراج البيانات",
		type: 'warning',
		showCancelButton: true,
		confirmButtonText: 'تأكيد'
	}).then(function(result) {
		if(result.value){
			$.post('/Commercial/requestexception/AdminExceptionGeneral/createAdminExceptionGeneral',
			$('#Form_ADD_EXCEPTION').serialize(), function(r){
				$(r).each(function(index, element) {
					if(element['o_success'] == 0){
						 danger_msg('تحذير..',element['o_msgtxt']);
					}
					if(element['o_success'] == 1){
						 ShowSuccessMessage();
						 $(".Free_MODAL_ADD_EXCEPTION").modal('hide');
					}
				})
			},'json');
			return false;
		}
	});
}
/// عرض مودال تقديم طلب افادة فنية
function req_technical_tip(REQ,SUBSC){
	GeneralShowloading();
    setTimeout(function() {
    	GeneralHideloading();
        $(".Form_TECHNICAL_TIP").find("input[name='TXT_REQUEST_APP_SERIAL_MODAL_TIP']").val(REQ);
        $(".Form_TECHNICAL_TIP").find("input[name='TXT_SUBSCRIBER_MODAL_TIP']").val(SUBSC);
        /// Show Modal
        $(".Free_MODAL_TECHNICAL_TIP").modal('show');
    }, 500);
}
//
function SAVE_ADD_EXCEPTION_TIP(){
	if (isDoubleClicked($(this))) return;
	swal.fire({
		title: 'هل أنت متأكد من حفظ البيانات المدرجة',
		text: "عزيزي المستخدم, في حال قمت بالضغط على زر التأكيد ,سيقوم النظام بإدراج البيانات",
		type: 'warning',
		showCancelButton: true,
		confirmButtonText: 'تأكيد'
	}).then(function(result) {
		if(result.value){
			$.post('/Commercial/requestexception/AdminExceptionGeneral/createTechnicalException',
			$('#Form_TECHNICAL_TIP').serialize(), function(r){
				$(r).each(function(index, element) {
					if(element['o_success'] == 0){
						 danger_msg('تحذير..',element['o_msgtxt']);
					}
					if(element['o_success'] == 1){
						 ShowSuccessMessage();
						 $(".Free_MODAL_TECHNICAL_TIP").modal('hide');
					}
				})
			},'json');
			return false;
		}
	});


}
// function general scan file from printer 
function scan_file(RequestAppSerial,BranchID){
	  window.open("http://localhost:9009/Acquire?guid="+RequestAppSerial+"&uploadUrl=http://localhost/Commercial/Scan/"+BranchID);
    
}

/** General GIS **/

// Define array
var general_libarary_array =
	[
		"esri/rest/find",
		"esri/rest/support/FindParameters",
		"esri/widgets/FeatureTable",
		"esri/layers/FeatureLayer",
		"esri/portal/Portal",
		"esri/identity/OAuthInfo",
		"esri/identity/IdentityManager",
		"esri/Graphic",
		"esri/geometry/Point",
		"esri/Map",
		"esri/views/MapView",
		"esri/widgets/Search",
		"esri/rest/support/Query",
		"esri/layers/GraphicsLayer",
		"esri/widgets/Feature",
		"esri/Basemap",
		"esri/layers/VectorTileLayer"
	];
function addsubscriberMap(SUBSCRIBER,url1,url2,BRANCH_ID,ServiceID,SUBSCRIBER_NAME,DISTRICT,ADDRESS,USER_ENTRY,REQUEST_APP_SERIAL,flag,MPOINT){
	/** Begin Block Require **/
	require(general_libarary_array,function(find, FindParameters,FeatureTable,FeatureLayer,Portal, OAuthInfo, esriId,Graphic,Point,Map,MapView,Search,Query,GraphicsLayer,Feature,Basemap,VectorTileLayer){

		const featureLayer = new FeatureLayer({
			url: url1,
			id:"1",
			outFields: ["*"]

		}); 
		const process_popup = {
			"title": "اشتراك",
			"content": "<b>رقم الاشتراك:</b> {SUBSCRIPTION_NO}<b> المستخدم</b>{CREATED_USER_N}"
		}
		const featureLayer2 = new FeatureLayer({
			url: url2,
			id:"2",
			outFields: ["*"],
			popupTemplate:process_popup

		});


		if(flag==2) {
            const basemap = new Basemap({
				baseLayers: [
					new VectorTileLayer({
						portalItem: {
							id: "20a3164c08584c35b6f3f25a5b255eaf" // Forest and Parks Canvas style
						}
					})
				]
			});
			const map = new Map({
				basemap: basemap,
				layers: [featureLayer2]
			});

			const view = new MapView({
				container: "viewDiv",
				center: [31.521338, 34.443680],
				zoom: 7,
				map: map
			});
			// Calling Show Loading
			GeneralShowMaploading();
			//لما يبحث برقم المشترك هيتحرك ف الخريطة اللي تحت ع موقع المشترك وازا ما في فيتشرز هيطلب اضافة فيتشر
			/******************
			 *
			 * listener on change
			 *
			 ***/

			view.whenLayerView(featureLayer2).then((layerView) => {
				// Calling Hide Loading
				GeneralHideMaploading();

			});
			/** Begin Block Subscriber Change **/
			///  When Change Text Field Before Insert Subscriber No
			$("#TXT_SUBSCRIBER_GIS").change(function () {
				var NewVal = $(this).val();
				// Define New Query And Create Object From Query
				const query = new Query({
					outFields: ["*"],
					where: "SUBSCRIPTION_NO = " + NewVal,
					returnGeometry: true
				});
				// Calling Show Loading
				GeneralShowMaploading();
				/// fetch query from feature layer
				featureLayer.queryFeatures(query)
					.then(function (response) {
						var feature = response.features[0];
						if (response.features.length > 0) {
							// Calling Hide Loading
							GeneralHideMaploading();
							// Define New Graphics And Create Object From Graphics
							var graphicsLayer = new GraphicsLayer();
							// Insert Layer Into Map
							map.layers.add(graphicsLayer);
							// Define Point from map
							var point = {
								type: "point",
								longitude: feature.geometry.longitude,
								latitude: feature.geometry.latitude
							};

							var simpleMarkerSymbol = {
								type: "simple-maker",
								color: [219, 245, 219], // orange
								size: 40,
								style: "circle",
								outline: {
									color: [219, 245, 219], // white
									width: 5
								}
							};
							let symbol = {
								type: "simple-marker",  // autocasts as new SimpleMarkerSymbol()
								style: "square",
								color: "blue",
								size: "40px",  // pixels
								outline: {  // autocasts as new SimpleLineSymbol()
									color: [255, 255, 0],
									width: 3  // points
								}
							};
							var pointGraphic = new Graphic({
								geometry: point,
								symbol: symbol
							});
							// Add Point Into Graphic layers
							graphicsLayer.add(pointGraphic);
							// بعد ما تم اضافة البوينت على الخريطة, اذهب الى المكان على الخريطة
							view.goTo(
								{
									target: feature.geometry,
									tilt: 70,
									zoom: 20
								},
								{
									duration: 2000,
									easing: "in-out-expo"
								}
							).catch((error) => {
								if (error.name != "AbortError") {
									//console.error(error);
								}
							});

						} else {
							danger_msg("خطأ", "لا يوجد معلومات في GIS يرجى اضافة معلومات بالبحث عن اقرب معلم وتحديد على الخريطة");
						}

					});

			});
			/** End Block Subscriber Change **/
			/**************
			 *
			 *
			 * بالعنوان بحث على جوجل ماب
			 *
			 *
			 * @type {google.maps.Geocoder}
			 */
			const input = document.getElementById("pac-input");
			const searchBox = new google.maps.places.SearchBox(input);
			let markers = [];
			/// Begin Listener when search
			searchBox.addListener("places_changed", () => {
				//  Get Places
				const places = searchBox.getPlaces();
				// IF NULL
				if (places.length == 0) {
					return;
				}
				//  تعريف الحدود حسب خط العرض وخط الطول
				const bounds = new google.maps.LatLngBounds();
				// Begin Fetch Places
				places.forEach((place) => {
					if (!place.geometry || !place.geometry.location) {
						console.log("Returned place contains no geometry");
						return;
					}

					// Create icon.
					const icon = {
						url: place.icon,
						size: new google.maps.Size(71, 71),
						origin: new google.maps.Point(0, 0),
						anchor: new google.maps.Point(17, 34),
						scaledSize: new google.maps.Size(25, 25),
					};

					// Create a marker for each place. // انشاء العلامة على الخريطة
					markers.push(
						new google.maps.Marker({
							map,
							icon,
							title: place.name,
							position: place.geometry.location,
						})
					);
					// المكود الجغرافي
					var geocoder = new google.maps.Geocoder();
					// Begin Create geocoder ( خاص بتحويل ال خط الطول والعرض الى اكس و واي الخاص بالجي اي اس)
					geocoder.geocode({
						'address': "address"
					}, function (results, status) {

						if (status == google.maps.GeocoderStatus.OK) {
							var latitude = results[0].geometry.location.lat();
							var longitude = results[0].geometry.location.lng();
						}
					});
					// End Create geocoder
					// اذهب للمكان
					view.goTo(
						{
							target: [place.geometry.location.lng(), place.geometry.location.lat()],
							tilt: 70,
							zoom: 20
						},
						{
							duration: 2000,
							easing: "in-out-expo"
						}
					).catch((error) => {
						if (error.name != "AbortError") {
							//console.error(error);
						}
					});
					//
					point = place.geometry.location;
					MAP_WIDTH = 1379;
					MAP_HEIGHT = 1000;
					/// Begin Add Graphics into view
					view.graphics.add({
						symbol: {
							type: "text",
							color: "#48e331",
							text: "\ue61d", // esri-icon-map-pin
							font: {
								size: 30,
								family: "CalciteWebCoreIcons"
							}
						},
						geometry: {
							type: "point",
							longitude: place.geometry.location.lng(),
							latitude: place.geometry.location.lat()
						}
					});
					/// End Add Graphics into view


				});
				// End Fetch Places

			});
			/// End Listener when search
			/******************
			 *
			 * listener
			 *
			 * **/
			let feature;
			view.on("click", (event) => {
				var point = event.mapPoint.clone();
				point.z = undefined;
				point.hasZ = false;
				view.hitTest(event).then((response) => {
					if (response.results.length > 0 && response.results[0].graphic.attributes['OBJECTID'] != null) {
						const editThisAction = {
							title: "تعديل",
							id: "edit-this",
							className: "esri-icon-edit"
						};
						var flag = 0;
						view.popup.on("trigger-action", (event) => {
							if (event.action.id === "edit-this" && flag != 1) {
								//console.log(results_clicks["OBJECTID"]);
								updateFeature1(results_clicks["OBJECTID"], "olalfi");
								flag = 1;

							}
						});

					} else {
						if (confirm("هل تريد اضافة مشترك جديد في هذه النقطة؟")) {
							var attributes = [
								{
									"attributes": {
										"SUBSCRIPTION_NO": SUBSCRIBER,
										"CUSTOMER_NAME": SUBSCRIBER_NAME,
										"SUBSCRIPTION_TYPE": ServiceID,
										"NOTES": "إضافة نقطة جديدة لمشترك جديد",
										"STREET_NAME": ADDRESS,
										"DISTRICT_NUMBER": DISTRICT,
										"BRANCH": BRANCH_ID,
										"CREATED_USER": USER_ENTRY,

									}
								}
							];
							editFeature = new Graphic({
								geometry: point,
								attributes: attributes
							});
							const edits = {
								addFeatures: [editFeature]
							};
							addFeatures(point, SUBSCRIBER, BRANCH_ID);
							insertDataPointIntoDB(point, attributes);
						}
					}

				});
				/** End Block Require **/
			});
		}else{
             addFeatures_withoutMap(MPOINT,SUBSCRIBER,BRANCH_ID,USER_ENTRY); 
		}
		/** **/
		function addFeatures(point,subsc,bran_id){ 
			// data to be added to the map
			const data = [
				{
					SUBSCRIPTION_NO: subsc,
					BRANCH: bran_id
				}
			];

			// create an array of graphics based on the data above
			var graphics = [];
			var graphic = new Graphic({
				geometry: point,
				attributes: data[0]
			});
			graphics.push(graphic);


			// addEdits object tells applyEdits that you want to add the features
			const addEdits = {
				addFeatures: graphics
			};

			// apply the edits to the layer
			applyEditsToLayer(addEdits);
		}
		function addFeatures_withoutMap(point,subsc,bran_id,USER_ENTRY){
			// data to be added to the map
            var p=new Point(point.latitude,point.longitude); 
			////
			if(bran_id==1)
				bran_id=2;
			const data = [
				{
					SUBSCRIPTION_NO: subsc,
					BRANCH: bran_id,
					CREATED_USER_N :USER_ENTRY,
					CREATED_DATE_N :new Date()
				}
			];
 			// create an array of graphics based on the data above
			var graphics = [];
			var graphic = new Graphic({
				geometry: p,
				attributes: data[0]
			});
			////
			graphics.push(graphic);
            // addEdits object tells applyEdits that you want to add the features
			const addEdits = {
				addFeatures: graphics
			};
            // apply the edits to the layer
			applyEditsToLayer(addEdits);
		}
		/** **/
		function applyEditsToLayer(edits) {
			featureLayer2.applyEdits(edits).then((results) => {
				// if edits were removed
				if (results.deleteFeatureResults.length > 0){
					console.log(
						results.deleteFeatureResults.length,
						"features have been removed"
					);
				}
				// if features were added - call queryFeatures to return
				//    newly added graphics
				if (results.addFeatureResults.length > 0){
					var objectIds = [];
					results.addFeatureResults.forEach((item) => {

						objectIds.push(item.objectId);
						console.log(item.objectId);
					});
					// query the newly added features from the layer
					featureLayer2
						.queryFeatures({
							objectIds: objectIds
						})
						.then((results) => {

							console.log(
								results.features,
								"features have been added."
							);

							if(results.features.length>0){
								//setTimeout(ShowSuccessMessage,40000);
								//window.close();


							}

						})
				}
			})
				.catch((error) => {
					console.error();
				});
		}
		/** insertDataPointIntoDB Function **/
		function insertDataPointIntoDB(points , attr){
			var  SUBSCRIPTION_NO_V; var  CUSTOMER_NAME_V; var  SUBSCRIPTION_TYPE_V; var  NOTES_V; 
			var  STREET_NAME_V; var  DISTRICT_NUMBER_V;
			var  BRANCH_V; var  CREATED_USER_V;
			var  X_POINT = points.x;
			var  Y_POINT = points.y;
			var  Z_POINT = points.z;
			var  latitude = points.latitude;
			var  longitude = points.longitude;

			for (var key in attr[0].attributes){
				SUBSCRIPTION_NO_V = attr[0].attributes['SUBSCRIPTION_NO'];
				CUSTOMER_NAME_V = attr[0].attributes['CUSTOMER_NAME'];
				SUBSCRIPTION_TYPE_V = attr[0].attributes['SUBSCRIPTION_TYPE'];
				NOTES_V = attr[0].attributes['NOTES'];
				STREET_NAME_V = attr[0].attributes['STREET_NAME'];
				DISTRICT_NUMBER_V = attr[0].attributes['DISTRICT_NUMBER'];
				BRANCH_V = attr[0].attributes['BRANCH'];
				CREATED_USER_V = attr[0].attributes['CREATED_USER'];
			}
			var attributes_arr = {REQUEST_APP_SERIAL : REQUEST_APP_SERIAL , SUBSCRIPTION_NO_V : SUBSCRIPTION_NO_V , CUSTOMER_NAME_V : CUSTOMER_NAME_V , SUBSCRIPTION_TYPE_V:SUBSCRIPTION_TYPE_V , NOTES_V:NOTES_V , STREET_NAME_V:STREET_NAME_V , DISTRICT_NUMBER_V:DISTRICT_NUMBER_V , BRANCH_V:BRANCH_V , CREATED_USER_V:CREATED_USER_V , X_POINT:X_POINT,Y_POINT:Y_POINT,Z_POINT:Z_POINT,latitude:latitude,longitude:longitude };

			$.post('/Commercial/customer_gis_map/GIS_MAP/create',attributes_arr,function(r){
				//setTimeout(ShowSuccessMessage,40000);
				//window.close();
				$(r).each(function(index, element) {
					if(element['o_success'] == 0){
						danger_msg('تحذير..',element['o_msgtxt']);
					}
					if(element['o_success'] == 1){
						ShowSuccessMessage();
						setTimeout(function(){
							//window.close();
						},4000);
					}
				});
			},'json');
			return false;
		}



		/** end require **/
	});}

///
function show_file_scan(param_one){
	 GeneralShowloading();
	 ///
	 var linkURL = window.location.href;
 	 var URLS = linkURL.substring(linkURL.lastIndexOf("/") + 1);
	 if(isInt(URLS)){
		 var urls_links1 = _link_url1+'/SERVICE_NEW/SCAN_TSG_FILE_TB_GET/'+param_one;
	 }else{
		 var urls_links1 = _basse_urlS+'/'+_link_url1+'/SERVICE_NEW/SCAN_TSG_FILE_TB_GET/'+param_one;
	 }
	 /// 
	 $(".ListIns_SCAN_FILE tbody tr").remove();
	 ///
	 setTimeout(function() {
		$.ajax({
			url: urls_links1,
			type: 'POST',
			datatype: 'json',
			success: function (data) { 
			  if(data.length ==0){ GeneralHideloading();  }else{
				  $(data).each(function(index, element) {
					 $(".ListIns_SCAN_FILE tbody").append(GetTableRows_INTERNALS([],
					 [element.SER,element.REQUEST_APP_SERIAL,element.BRANCH_NAME,element.FILE_NAME]));
					
				  });
				  GeneralHideloading();
				  /// Show Modal
				  $(".Modal_SCAN_FILE").modal('show');
			   }
			   
			 },
			error: function (jqXHR, textStatus, errorThrown) {  }
		});
     }, 500);
}
/////
function get_scanning_file(NoFind){ 
	/*$.post('/Commercial/archive/Service/DownloadsFileInlineScanning/'+NoFind,
	$('#Return_Table_Modals_Pmeter').serialize(), function(r){
		$(r).each(function(index, element) {
			if(element['o_success'] == 0){
				 danger_msg('تحذير..',element['o_msgtxt']);
			}
			if(element['o_success'] == 1){
				 ShowSuccessMessage();  
			}
		})
	},'json');
	return false;*/
	
	window.open("http://localhost/Commercial/archive/Service/DownloadsFileInlineScanning/"+NoFind, "_blank");
}
function GetTableRows_INTERNALS(requiredFields,element)
{
	output = "<tr>";
	ID = -1;
	for (var key in element) {
		if ($.inArray(key,requiredFields)){
			if (ID == -1){
				ID = element[key];
			}
			output += "<td>";
			output+=element[key];
			output += "</td>";			
		}
	};				
	output += "<td>";	
	output += "<a href='javascript:get_scanning_file("+ID+");' class='btn btn-sm btn-clean btn-icon btn-icon-md' title='اختيار'><i class='flaticon2-chat-2' data-pk='"+ID+"'></i></a>";
	output += "</td>";
	output += "</tr>";
	ID = -1;
	return output;
}

/// عرض مودال تقييم الطلب
function add_request_evaluation(NewVal){
	GeneralShowloading();
    setTimeout(function() {
    	GeneralHideloading();
        $(".Form_EVALUATION").find("input[name='TXT_H_REQ_APP_SERIAL']").val(NewVal);
		$('.rating , .rating1 , .rating2').starRating(
			  {
				starSize: 1.5,
				showInfo: true
			  }
		);  
        /// Show Modal
        $(".Free_MODAL_EVALUATION").modal('show');
    }, 500);
}
$(document).on('change', '.rating', function (e, stars, index) {
	//alert("Thx for "+stars+" stars!");
	$("input[name='TXT_H_EVAL_ONE']").val(stars); 
});
$(document).on('change', '.rating1', function (e, stars, index) {
	//alert("Thx for "+stars+" stars!");
	$("input[name='TXT_H_EVAL_TWO']").val(stars);
});
$(document).on('change', '.rating2', function (e, stars, index) {
	//alert("Thx for "+stars+" stars!");
	$("input[name='TXT_H_EVAL_THREE']").val(stars);
});



