<?php
define('TITLE',$_SESSION['TITLE']);
$URL = $_SESSION['sURL'];
$userID = getUser();
$LAST_NOTICE =  $_SESSION['sLAST_NOTICE'];
$resellerID = getReseller();
global $LANG; 
global $server;
?>
function loadDashboardSMSGraph(period) {
                    $("#chart1").html("<center><h1>&nbsp;</h1><h3><i class='fa fa-spin fa-spinner'></i>Loading...</h3></enter>");
                    var formData = {
                           'loadDashboardSMSGraph'    : period
                     };
                     $.ajax({
                           type        : 'POST', 
                           url         : 'API', 
                           data        : formData, 
                           dataType    : 'json',
                           encode      : true
                     }).done(function(data) {
                     		$('#sms_chart_desc').text(data.header);
                     		var data1 = data.datas;
                     		 $("#chart1").empty();
                             Morris.Area({
                              element: 'chart1',				  
                              data: data1,
                              xkey: 'x',
                              pointSize: 3,
                              fillOpacity: 0,
                              ykeys: ['Sent', 'Failed'],
                              labels: ['Sent SMS', 'Failed SMS'],
                              pointStrokeColors: ['#003300', '#FF3300'],
                              lineColors: ['#003300', '#FF3300'],
                              gridLineColor: '#e0e0e0',
                              lineWidth: 1,
                              parseTime: false,
                              hideHover: 'auto',
                              resize: true
                            }).on('click', function(i, row){  });
                      }).fail(function (jqXHR,status,err) {
                          swal("Oops!", 'Connection error: '+status+" \n Please check your network and try again", "warning");
                    });	
                }
function loadChat(number) {
			localStorage.setItem("lastNumber", number);
			var instanse = false;
			$('#chat_int').hide();
			$('#chat_messages').show();
			var pre = '<div id="chat_preloader2"><?=$LANG['Loading messages']?><div class="progress"><div class="indeterminate"></div></div></div>';
			$('#chat_messages').html(pre);
			$('#chat_preloader').show();
			$('#receiver2').val(number);
			$('#chating_with').text(number);

			setInterval(function(){
			    number = localStorage.getItem("lastNumber");
				instanse = true;
				$.ajax({
					type: "POST",
					url: 'API?fetch_chats', 
					data: {'number': number},
					success: function(data) { 
						if(data){	
							var chats = data.split(':<<:')[1];
							var sender = data.split(':<<:')[0];
							$('#chat_messages').html(chats);
							$('#chat_preloader').hide();
							$('#sender2').val(sender);
							$('#chat_composer').show();
							var d = $('#chat_messages');
							d.scrollTop(d.prop("scrollHeight"));
						} 
						instanse = false;
					}
				});
			}, 10000);	

		}	
	Simditor.locale = 'en-US';
	//================== Custom scripts  ===============//
		//show messages 
		<?php
		if(isset($_GET['err'])) {
			$message = $_SESSION['message']; $cl = 'success'; $hd = 'Done!';
			if($_GET['err']>0) {
				$cl = 'warning'; $hd = 'Oops!';
			}
			echo 'swal("'.$hd.'", "'.$message.'", "'.$cl.'");';
		}
		?>
		//do select all check tricks
		$(document).ready(function(){
		    $('#selectall').click(function(event) { 
				if(this.checked) { 
					$('.bulk').each(function() { 
						this.checked = true; 
					});
				}else{
					$('.bulk').each(function() { 
						this.checked = false; 
					});         
				}
			});
			$('#selectall2').click(function(event) { 
				if(this.checked) { 
					$('.bulk2').each(function() { 
						this.checked = true; 
					});
				}else{
					$('.bulk2').each(function() { 
						this.checked = false; 
					});         
				}
			});
		});
		//do bulk action submit
			function bulkaction(action,form,conf) {
				document.getElementById('bulkaction').value = action; 
				if(confirm(conf)) {
					document.getElementById(form).submit();	
				} else {
					return false;	
				}
			}
			function bulkaction2(action,form,conf) {
				document.getElementById('bulkaction2').value = action; 
				if(confirm(conf)) {
					document.getElementById(form).submit();	
				} else {
					return false;	
				}
			}
		//file uploader 
		var Upload = function (file) {
			this.file = file;
		};
		Upload.prototype.getType = function() {
			return this.file.type;
		};
		Upload.prototype.getSize = function() {
			return this.file.size;
		};
		Upload.prototype.getName = function() {
			return this.file.name;
		};
		//print stuffs
<?php if($URL=='inbox' || $URL=='ainbox') { ?>
		function loadConas(number,customer) {
			var formData = {
				'number'  :  number,
				'customer_id'  :  customer,
				'user' : '<?=$userID?>'
			};
			$('#conersr').show();
			$('#numbs').text(number);
			var loader = '<div id="chat_preloader"><?=$LANG['Loading messages']?><div class="progress"><div class="indeterminate"></div></div></div>';
			$('#chat_messages').html(loader);
			$.ajax({
				type        : 'POST', 
				url         : 'API?loadConas',
				data        : formData, 
			}).done(function(data) {
				$('#chat_messages').html(data);
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#conersr').hide();
			});
		};		
						
	<?php } ?>		
		function Print(elem) {
			var divElements = document.getElementById(elem).innerHTML;
			var oldPage = document.body.innerHTML;
			document.body.innerHTML = '<html><head><title>Report</title></head><body style="background-image:none;">' + divElements + "</body></html>";	
			window.print();
			document.body.innerHTML = oldPage;
		}
		//Set page title
		$(document).ready(function(){
			var pageTitle = '<?=$LANG[TITLE]?>';
			$('#page-title').text(pageTitle);
			document.title = pageTitle;
		});
		function number_format(number, decimals, dec_point, thousands_sep) {
			var n = !isFinite(+number) ? 0 : +number, 
				prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
				sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
				dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
				toFixedFix = function (n, prec) {
					var k = Math.pow(10, prec);
					return Math.round(n * k) / k;
				},
				s = (prec ? toFixedFix(n, prec) : Math.round(n)).toString().split('.');
			if (s[0].length > 3) {
				s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
			}
			if ((s[1] || '').length < prec) {
				s[1] = s[1] || '';
				s[1] += new Array(prec - s[1].length + 1).join('0');
			}
			return s.join(dec);
		}
		<?php if($URL=='dashboard'){?>
			$(document).ready(function(){
				setTimeout(function(){ Materialize.toast('<?=$LANG['Hey']?> <?=userData(getUser(),'first_name')?> <?=userData(getUser(),'last_name')?>! <?=$LANG['Its good to have you back. You last login was on']?> <?=date('F d, Y h:iA',$_SESSION['last_login'])?>', 10000) }, 3000);
		    	<?php if(countNotice($userID)>0) { ?>
				setTimeout(function(){ Materialize.toast('<?=$LANG['You have']?> <?=countNotice($userID)?> <?=$LANG['new notifications']?>', 4000) }, 14000);
				<?php } ?>

				<?php 
				$queryString = (isset($_SERVER['HTTPS'])?"https":"http")."://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
				$queryString = explode('?',$queryString);
				$queryString = @$queryString[1];
				?>
				
                loadDashboardSMSGraph('day');
			<?php if(userRole()>2) { ?>	
				//SMS Chat by Country
				 var flot2 = function () {
					 <?=countryChatData(0)?>
					var dataset = [{
						data: data,
						color: "#096"
					}];
					var options = {
						series: {
							bars: {
								show: true,
								fill: 1
							}
						},
						bars: {
							align: "center",
							barWidth: 0.3
						},
						xaxis: {
							ticks: ticks,
							tickLength: 0
						},
						legend: {
							show: false
						},
						grid: {
							color: "#AFAFAF",
							hoverable: true,
							borderWidth: 0,
							backgroundColor: '#FFF'
						},
						tooltip: true,
						tooltipOpts: {
							content: "%x: %y",
							defaultTheme: false
						}
					};
					$.plot($("#flot1"), dataset, options);
				};			
				flot2();	
			<?php } ?>	
				// Peity Chart
				$.fn.peity.defaults.pie = {
					delimiter: null,
					fill: ["#26A69A", "#e0e0e0", "#b2dfdb"],
					height: null,
					radius: 10,
					width: null
				};
				$("span.pie").peity("pie")
			});
		
		//detect page change
		var oldURL = location.href;
		setInterval(function() {
			  if(location.href != oldURL) {
				   location.reload();
				   oldURL = location.href
			  }
		  }, 1000); 
		<?php } ?>
		<?php if($URL=='fund'){?>
		$('#sms_pack').select2();
		$('#credits').change(function () {
			var credits = $('#credits').val();
			var rate = '1'; //detault price
			<?php if(checkBillingModel($userID)=='unit') {
				$costTable2 = getSetting('advancedUnitPricing');
				$customer_pricing = userData($userID,'advancedUnitPricing');
				if(!empty($customer_pricing)) {
					$costTable2 = $customer_pricing;
				}
				$reseller = userData($userID,'reseller');
				if($reseller > 0) {
					$costTable2 = getSetting('advancedUnitPricing',$reseller);
				}
				$searchKeys = array('\r\n','\n',"\n","\r\n");
				$replaceKeys = array("<br />","<br />","<br />","<br />");
				$costTable2 = str_replace( $searchKeys , $replaceKeys , $costTable2);
				$costTable = explode("<br />",$costTable2);
				$unitcost=0;
				for($i=0; $i<count($costTable); $i++){
					$x=explode("-",$costTable[$i]);
					$y=explode("=",$x[1]);
					echo "if(credits >= $x[0] && credits <= $y[0]) { var rate = '$y[1]'; }";
					if( $qty >= $x[0] && $qty <= $y[0]) $unitcost = $y[1];
				}
			}
			?>			
			var to_pay = number_format(credits.replace(/,/g,'')*rate,<?=userCurrencyZero($userID)?>,'.',',');
			var credits = number_format(credits,<?=userCurrencyZero($userID)?>,'.',',');
			$('#credit_val').text(credits);
			$('#total_val').text(to_pay);
		});
		$('#credits').on('keyup', function(){
			var credits = $('#credits').val();
			var rate = '1'; //default price
			//get custom prices if any
			 <?php $query="SELECT * FROM dynamic_credit_cost WHERE reseller_id = '$resellerID' AND max_order > 0";
                   $result = mysqli_query($server,$query) or die(mysqli_error($server));
                   while ($rows = mysqli_fetch_assoc($result)) { 
				   		echo "if(credits >= $rows[min_order] && credits <= $rows[max_order]) { var rate = '$rows[cost]'; }";
				   }
			?>				
			var to_pay = number_format(credits.replace(/,/g,'')*rate,<?=userCurrencyZero($userID)?>,'.',',');
			var credits = number_format(credits,<?=userCurrencyZero($userID)?>,'.',',');
			$('#credit_val').text(credits);
			$('#total_val').text(to_pay);
		}); 
		$('#payment_opt').change(function () {
			var gateway_val = $("#payment_opt option:selected").text();
			$('#gateway_val').text(gateway_val);
		});
		//package stuffs
		$('#sms_pack').change(function () {
			var exrate = '<?=userExchangeRate($userID)?>';
			var sms_pack = $("#sms_pack").val();
			var to_pay = number_format(((sms_pack.split(':')[1])*exrate),<?=userCurrencyZero($userID)?>,'.',',');
			var credits = number_format(((sms_pack.split(':')[2])*exrate),<?=userCurrencyZero($userID)?>,'.',',');
			$('#credit_val').text(credits);
			$('#total_val').text(to_pay);
		});
		$('#payment_opt2').change(function () {
			var gateway_val = $("#payment_opt2 option:selected").text();
			$('#gateway_val').text(gateway_val);
		});
		//voucher stuffs
		$('#voucher').on('keyup', function(){
			$('#credit_val').text(0.00);
			$('#total_val').text(0.00);
			var voucher = $('#voucher').val();
			var exrate = '<?=userExchangeRate($userID)?>';
			$('#gateway_val').text('<?=$LANG['SMS Voucher']?>');
			if(voucher.length >= 18) { 
				$.ajax({url: "API?voucher_pin="+voucher, success: function(result){
					var status = result.split(':')[0];					
					var price = result.split(':')[2]
					var price =  number_format((price*exrate),<?=userCurrencyZero($userID)?>,'.',',');
					var credits = result.split(':')[1]
					var credits = number_format((credits*exrate),<?=userCurrencyZero($userID)?>,'.',',');
					if(status.replace(/\s+/g, '') == 'success') {
						$('#credit_val').text(credits);
						$('#total_val').text(price);
					} else {
						swal("Oops!", status, "warning");
					}
				}});
			}
		});
		$('#voucher-form').submit(function (event) {
			event.preventDefault();	  
			$('#voucher-button').hide();
			$('#voucher-spin').show();
			var voucher = $('#voucher').val();
			var exrate = '<?=userExchangeRate($userID)?>';
			$.ajax({url: "API?voucher_load="+voucher, success: function(result){
				var status = result.split(':')[0];
				var price = result.split(':')[2]
				var price =  number_format((price*exrate),<?=userCurrencyZero($userID)?>,'.',',');
				var credits = result.split(':')[1]
				var credits = number_format((credits*exrate),<?=userCurrencyZero($userID)?>,'.',',');
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Congratulations']?>",   
						text: "<?=$LANG['Your account has been credited with']?> "+credits+" <?=userCurrencyCode($userID)?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = 'index.php'; 
					});
				} else {
					swal("Oops!", status, "warning");
					$('#voucher-button').show();
					$('#voucher-spin').hide();
				}
			},error: function(XMLHttpRequest, textStatus, errorThrown) { 
				swal("Oops!", errorThrown, "warning");
				$('#voucher-button').show();
				$('#voucher-spin').hide();
			}
			});
		});
		//credit stuffs again
		$('#credit-button').click(function (event) {
			event.preventDefault();	  
			$('#credit-button').hide();
			$('#credit-spin').show();
			var credits = $('#credits').val();
			var gateway = $('#payment_opt').val();
			var user = '<?=getUser();?>';
			$.ajax({url: "API?buy_credit="+credits+"&gateway="+gateway+"&user="+user, success: function(result){
				var status = result.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					window.location = 'fund?confirm'; 
				} else {
					swal("Oops!", status, "warning");
					$('#credit-button').show();
					$('#credit-spin').hide();
				}
			},error: function(XMLHttpRequest, textStatus, errorThrown) { 
				swal("Oops!", errorThrown, "warning");
				$('#credit-button').show();
				$('#credit-spin').hide();
			}   
			});
		});
		//plan stuffs again
		$('#plan-button').click(function (event) {
			event.preventDefault();	  
			$('#plan-button').hide();
			$('#plan-spin').show();
			if($('#sms_pack').val() !== null && $('#sms_pack').val() !== '') {
				var plan = $('#sms_pack').val().split(':')[0];
			} else {
				var plan = '';	
			}
			var gateway = $('#payment_opt2').val();
			var user = '<?=getUser();?>';
			$.ajax({url: "API?buy_plan="+plan+"&gateway="+gateway+"&user="+user, success: function(result){
				var status = result.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					window.location = 'fund?confirm'; 
				} else {
					swal("Oops!", status, "warning");
					$('#plan-button').show();
					$('#plan-spin').hide();
				}
			},error: function(XMLHttpRequest, textStatus, errorThrown) { 
				swal("Oops!", errorThrown, "warning");
				$('#plan-button').show();
				$('#plan-spin').hide();
			}   
			});
		});
		
		//cancel invoice
		$('#cancel_inv').click(function (event) {
			event.preventDefault();	  
			$('#cancel_inv').hide();
			$('#cancin-spin').show();
			var cancel_inv = '<?=@$_SESSION['reference']?>';
			var user = '<?=getUser()?>';
			$.ajax({url: "API?cancel_inv="+cancel_inv+"&user="+user, success: function(result){
				var status = result.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['OK']?>",   
						text: "<?=$LANG['You have successfully canceled invoice']?> #"+cancel_inv,   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = 'fund?confirm'; 
					});
				} else {
					swal("Oops!", status, "warning");
					$('#cancel_inv').show();
					$('#cancin-spin').hide();
				}
			},error: function(XMLHttpRequest, textStatus, errorThrown) { 
				swal("Oops!", errorThrown, "warning");
				$('#cancel_inv').show();
				$('#cancin-spin').hide();
			}
			});
		});
		<?php if(isset($_GET['confirm']) && is_numeric($_GET['confirm'])) { ?>
		//Popu
			<?php if($_GET['confirm']==0) { ?>
			swal("Oops!", "<?=trim(preg_replace('/\s\s+/',' ',str_replace('"','',$_SESSION['message'])))?>", "warning");
			<?php } if($_GET['confirm']==1) { ?>
			swal("<?=$LANG['Congratulations']?>", "<?=$LANG['Your payment was successful and your account has been credited']?>", "success");
			<?php } ?>
		<?php } ?> 	
	<?php } ?>
	
	<?php if($URL=='compose' || $URL=='acompose') { ?>
		$(document).ready(function() {
			$('#compose-btn').hide();
			$('#file_lab').hide();
			$(".masked").inputmask();
			$('#s_gateway_id').select2(); $('#sender_id2').select2(); $('#country').select2(); $('#marketing_list').select2({ placeholder: '<?=$LANG['Choose Marketing Lists']?>'}); $('#addressbook').select2({placeholder: '<?=$LANG['Choose Addressbooks']?>'});
						
			$('.datepicker').pickadate({
				selectMonths: true, // Creates a dropdown to control month
				selectYears: 15 // Creates a dropdown of 15 years to control year
			});
			$('#sch_swit').click(function() {
				if($('#schedule').is(":checked")){
				  $('#sch_date').show('slow');
				  $('#sch_time').show('slow');
				  $('#rep_b').show('slow');
				} else {
					$('#sch_date').hide('slow');
					$('#sch_time').hide('slow');
					$('#rep_b').hide('slow');
				}
			});
			if($('#message_type').val() == 'voice') {
				$('.show-voice').show();
				$('#composers_lab').text('<?=$LANG['Voice Message']?>');
				$('#ms_typ').text('<?=$LANG['Voice Message']?>');
			} else {
				$('.show-voice').hide();
			}
			if($('#message_type').val() == 'sms') {
				$('#composers_lab').text('<?=$LANG['Text Message']?>');
				$('#ms_typ').text('<?=$LANG['Text Message']?>');
				$('.show-voice').hide();
				$('.show-mms').hide();
				$('.show-whatsapp').hide();
				$('.show-flash').hide();
			} 
			if($('#message_type').val() == 'mms') {
				$('.show-mms').show();
				$('#composers_lab').text('<?=$LANG['Multimedia Message']?>');
				$('#ms_typ').text('<?=$LANG['Multimedia Message']?>');
			} else {
				$('.show-mms').hide();
				if($('#message_type').val() == 'whatsapp') {
					$('.show-whatsapp').show();
				}
			}
			if($('#message_type').val() == 'whatsapp') {
				$('.show-whatsapp').show();
				$('#composers_lab').text('<?=$LANG['WhatsApp Message']?>');
				$('#ms_typ').text('<?=$LANG['WhatsApp Message']?>');
			} else {
				$('.show-whatsapp').hide();
				if($('#message_type').val() == 'mms') {
					$('.show-mms').show();
				}
			}
			if($('#message_type').val() == 'unicode') {
				$('.show-unicode').show();
				$('#composers_lab').text('<?=$LANG['Unicode Message']?>');
				$('#ms_typ').text('<?=$LANG['Unicode Message']?>');
			} else {
				$('.show-unicode').hide();
			}
			if($('#message_type').val() == 'flash') {
				$('.show-flash').show();
				$('#composers_lab').text('<?=$LANG['Flash Message']?>');
				$('#ms_typ').text('<?=$LANG['Flash Message']?>');
			} else {
				$('.show-flash').hide();
			}
			
		});
		
		//set msg typs
		$('#message_type').change(function () {
			var type = $('#message_type').val(); 
			$("#message").blur();
			if(type == 'voice') { 
				$('.show-voice').show();
				$('#composers_lab').text('<?=$LANG['Voice Message']?>');
				$('#ms_typ').text('<?=$LANG['Voice Message']?>');
				$('#mess_lab').text('<?=$LANG['Message (Type some message to use Text-to-Speech)']?>');
			} else {
				$('.show-voice').hide();
				$('#mess_lab').text('<?=$LANG['Message']?>');
			}
			if(type == 'sms') {
				$('#composers_lab').text('<?=$LANG['Text Message']?>');
				$('#ms_typ').text('<?=$LANG['Text Message']?>');
				$('.show-voice').hide();
				$('.show-mms').hide();
				$('.show-whatsapp').hide();
				$('.show-flash').hide();
			} 
			if(type == 'mms') {
				$('.show-mms').show();
				$('#composers_lab').text('<?=$LANG['Multimedia Message']?>');
				$('#ms_typ').text('<?=$LANG['Multimedia Message']?>');
			} else {
				$('.show-mms').hide();
				if($('#message_type').val() == 'whatsapp') {
					$('.show-whatsapp').show();
				}
			}
			if(type == 'whatsapp') {
				$('.show-whatsapp').show();
				$('#composers_lab').text('<?=$LANG['WhatsApp Message']?>');
				$('#ms_typ').text('<?=$LANG['WhatsApp Message']?>');
			} else {
				$('.show-whatsapp').hide();
				if($('#message_type').val() == 'mms') {
					$('.show-mms').show();
				}
			}
			if(type == 'unicode') {
				$('.show-unicode').show();
				$('#composers_lab').text('<?=$LANG['Unicode Message']?>');
				$('#ms_typ').text('<?=$LANG['Unicode Message']?>');
			} else {
				$('.show-unicode').hide();
			}
			if(type == 'flash') {
				$('.show-flash').show();
				$('#composers_lab').text('<?=$LANG['Flash Message']?>');
				$('#ms_typ').text('<?=$LANG['Flash Message']?>');
			} else {
				$('.show-flash').hide();
			}			
		});
		//validate fields
		$('#time').change(function () {
			var time = $('#time').val();
			if(time.split(':')[0] > 23) {
				swal("Oops!", "<?=$LANG['wrong_time']?>", "warning");
				time.val('');
			}
			if(time.split(':')[1] > 59) {
				swal("Oops!", "<?=$LANG['wrong_time']?>", "warning");
				time.val('');
			}
		});
		
		//recipient stuffs
		$('#country').change(function () {
			var country = $('#country').val();
			if(country<1) {
				$('#to_lab').text("<?=$LANG['type_recipinet_notice2']?>");
			} else {
				$('#to_lab').text("<?=$LANG['type_recipinet_notice']?>");
			}
		});
		 function hideTL(){
			 $('#to_lab').hide();
		 }
		 function showTL(){
			 $('#to_lab').show();
		 }
		  function hideFL(){
			 $('#file_lab').hide();
		 }
		 function showFL(){
			 $('#file_lab').show();
		 }
		 $('#addressbook').change(function () {
			$("#message").blur();
		});
		$('#marketing_list').change(function () {
			$("#message").blur();
		});
		$('#s_gateway_id').change(function () {
			$("#message").blur();
		});

		//show page and cost
		$('#message').blur(function(){ 
			var addressbook = [];
			$('#addressbook :selected').each(function(i, selected){
					addressbook[i] = $(selected).val();
			});
			var addressbook = JSON.stringify(addressbook)
			var marketing_list = [];
			$('#marketing_list :selected').each(function(i, selected){
					marketing_list[i] = $(selected).val();
			});
			var marketing_list = JSON.stringify(marketing_list)
			var formData = {
				'message_type'  : $('#message_type').val(),
				'sender_id'  : $('#sender_id').val(),
				's_gateway_id'  : $('#s_gateway_id').val(),
				'to'    : $('#to').val(),
				'country'  : $('#country').val(),
				'addressbook'  : addressbook,
				'marketing_list'  : marketing_list,
				'message'  : $('#message').val(),
				'duration'  : $('#duration').val(),
				'files' : $('#files_holder').val(),
				'voice_file'  : $('#voice_holder').val(),
				'media_file'  : $('#media_holder').val(),
				'date'  : $('#date').val(),
				'time'  : $('#time').val(),
				'repeats'  : $('#repeats').val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?message_stats',
				data        : formData, 
			}).done(function(result) {
				var exrate = '<?=userExchangeRate($userID)?>';
				var status = result.split(':')[0];	
				var char_count = result.split(':')[1]
				var to_count = result.split(':')[2]				
				var pg_count = result.split(':')[3]
				var credits = result.split(':')[4]
				var ext_cost = number_format((credits),<?=userCurrencyZero($userID)?>,'.',',');
				if(status.replace(/\s+/g, '') == 'success') {
					$('#char_count').text(char_count);
					$('#to_count').text(to_count);
					$('#pg_count').text(pg_count);
					$('#ext_cost').text(ext_cost);
				} else {
					swal("Oops!", "<?=$LANG['Unable to communicate with SMS server. Page and cost information may not be available']?>", "warning");
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
			});			
		});
		$('#to').blur(function(){ 
			var addressbook = [];
			$('#addressbook :selected').each(function(i, selected){
					addressbook[i] = $(selected).val();
			});
			var addressbook = JSON.stringify(addressbook)
			var marketing_list = [];
			$('#marketing_list :selected').each(function(i, selected){
					marketing_list[i] = $(selected).val();
			});
			var formData = {
				'message_type'  : $('#message_type').val(),
				'sender_id'  : $('#sender_id').val(),
				's_gateway_id'  : $('#s_gateway_id').val(),
				'to'    : $('#to').val(),
				'country'  : $('#country').val(),
				'addressbook'  : addressbook,
				'marketing_list'  : marketing_list,
				'message'  : $('#message').val(),
				'duration'  : $('#duration').val(),
				'files' : $('#files_holder').val(),
				'voice_file'  : $('#voice_holder').val(),
				'media_file'  : $('#media_holder').val(),
				'date'  : $('#date').val(),
				'time'  : $('#time').val(),
				'repeats'  : $('#repeats').val(),
				'user' : '<?=$userID?>'
			};
	
			$.ajax({
				type        : 'POST', 
				url         : 'API?message_stats',
				data        : formData, 
			}).done(function(result) { 
				var exrate = '<?=userExchangeRate($userID)?>';
				var status = result.split(':')[0];	
				var char_count = result.split(':')[1]
				var to_count = result.split(':')[2]				
				var pg_count = result.split(':')[3]
				var credits = result.split(':')[4]
				var ext_cost = number_format((credits),<?=userCurrencyZero($userID)?>,'.',',');
				if(status.replace(/\s+/g, '') == 'success') {
					$('#char_count').text(char_count);
					$('#to_count').text(to_count);
					$('#pg_count').text(pg_count);
					$('#ext_cost').text(ext_cost);
				} else {
					swal("Oops!", "<?=$LANG['Unable to communicate with SMS server. Page and cost information may not be available']?>", "warning");
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
			});
		});
		$(document).ready(function() {
		  $("#to").on('keyup', function() {
			  this.value = $.map(this.value.split(","), $.trim).join(", ");
		  });
		}); 
		
		//save message
		$('#save-button').click(function(event) { 
			event.preventDefault();	  
			$('#save-button').hide();
			$('#save-spin').show();
			var message = $('#message').val();
			if(message.length < 1){
				swal("Oops!", "<?=$LANG['You cannot save a blank message']?>", "warning");
				$('#save-button').show();
				$('#save-spin').hide();
				return false;
			}
			var addressbook = [];
			$('#addressbook :selected').each(function(i, selected){
					addressbook[i] = $(selected).val();
			});
			var addressbook = JSON.stringify(addressbook)
			var marketing_list = [];
			$('#marketing_list :selected').each(function(i, selected){
					marketing_list[i] = $(selected).val();
			});
			var formData = {
				'message_type'  : $('#message_type').val(),
				'sender_id'  : $('#sender_id').val(),
				'sender_id2'  : $('#sender_id2').val(),
				's_gateway_id'  : $('#s_gateway_id').val(),
				'to'    : $('#to').val(),
				'country'  : $('#country').val(),
				'addressbook'  : addressbook,
				'marketing_list'  : marketing_list,
				'message'  : $('#message').val(),
				'duration'  : $('#duration').val(),
				'files' : $('#files_holder').val(),
				'voice_file'  : $('#voice_holder').val(),
				'media_file'  : $('#media_holder').val(),
				'language'  : $('#language').val(),
				'date'  : $('#date').val(),
				'time'  : $('#time').val(),
				'repeats'  : $('#repeats').val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?save_message',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];	
				if(status.replace(/\s+/g, '') == 'success') {
					swal("<?=$LANG['Done']?>!", '<?=$LANG['Your_message_saved']?>', "success");
					$('#save-button').show();
					$('#save-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to save message']?> '+status, "warning");
					$('#save-button').show();
					$('#save-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#save-button').show();
				$('#save-spin').hide();
			});
		});		
		
		//send message
		$('#send-button').click(function (event) {
			event.preventDefault();
			var time = $('#time').val();
			$('#send-button').hide();
			$('#send-spin').show();
			var meType = $('#message_type').val();
			var meDuration =  $('#duration').val();
			if( (time.split(':')[1] > 59) || (time.split(':')[1]=="") || (time.split(':')[0] > 23) || (time.split(':')[0]=="")){
				swal("Oops!", "<?=$LANG['wrong_time']?>", "warning");
				$('#send-button').show();
				$('#send-spin').hide();
			} else if(meType == "voice" && meDuration < 1) {
				swal("Oops!", "<?=$LANG['wrong_duration']?>", "warning");
				$('#send-button').show();
				$('#send-spin').hide();
			} else {
				var addressbook = [];
				$('#addressbook :selected').each(function(i, selected){
						addressbook[i] = $(selected).val();
				});
				var addressbook = JSON.stringify(addressbook);
				var marketing_list = [];
				$('#marketing_list :selected').each(function(i, selected){
						marketing_list[i] = $(selected).val();
				});
				var marketing_list = JSON.stringify(marketing_list);
				
				var formData = {
					'message_type'  : $('#message_type').val(),
					'sender_id'  : $('#sender_id').val(),
					'sender_id2'  : $('#sender_id2').val(),
					's_gateway_id'  : $('#s_gateway_id').val(),
					'to'    : $('#to').val(),
					'country'  : $('#country').val(),
					'addressbook'  : addressbook,
					'marketing_list'  : marketing_list,
					'message'  : $('#message').val(),
					'duration'  : $('#duration').val(),
					'files' : $('#files_holder').val(),
					'voice_file'  : $('#voice_holder').val(),
					'media_file'  : $('#media_holder').val(),
					'language'  : $('#language').val(),
					'date'  : $('#date').val(),
					'time'  : $('#time').val(),
					'repeats'  : $('#repeats').val(),
					'user' : '<?=$userID?>'
				};
				
				$.ajax({
					type        : 'POST', 
					url         : 'API?send_message',
					data        : formData, 
				}).done(function(data) { 
					var status = data.split(':')[0];	
					var scheduled = data.split(':')[1];	
					if(status.replace(/\s+/g, '') == 'success') {
						if(scheduled == 1) {
							swal("<?=$LANG['Done']?>!", '<?=$LANG['Your_message_scheduled']?>', "success");
						} else if (scheduled == 2) {
							swal("<?=$LANG['Done']?>!", '<?=$LANG['Your_message_sent']?>', "success");
						} else {
							swal("<?=$LANG['Done']?>!", '<?=$LANG['Your_message_queued']?>', "success");
						}
						$('#send-button').show();
						$('#send-spin').hide();
						$("#composer-form").trigger('reset');
					} else {
						swal("Oops!", '<?=$LANG['Unable to send message']?> '+status, "warning");
						$('#send-button').show();
						$('#send-spin').hide();	
					}
				}).fail(function (jqXHR,status,err) {
					swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
					$('#send-button').show();
					$('#send-spin').hide();
				});
			}						
		});
		//alert old schools guys
		if(window.FormData === undefined){
			alert('sorry buddy you\'re browsers too old! You may not be able to use our portal om your current browser');
		}

		//upload contact files
		Upload.prototype.doUpload = function (holder,requests) {
			$('#send-button').hide();
			$('#save-button').hide();
			$('#upload-spin').show();
			var that = this;
			var formData = new FormData();
			formData.append("file", this.file, this.getName());
			formData.append("upload_file", true);
			$.ajax({
				type: "POST",
				url: "API?"+requests,
				xhr: function () {
					var myXhr = $.ajaxSettings.xhr();
					if (myXhr.upload) {
						myXhr.upload.addEventListener('progress', that.progressHandling, false);
					}
					return myXhr;
				},
				success: function (data) {
					var status = data.split(':')[0];
					var file_url = data.split(':')[1];
					if(status.replace(/\s+/g, '') == 'success') {
						$('#'+holder).val(file_url);
					} else {
						swal("Oops!", data.split(':')[0], "warning");
					}
					$('#save-button').show();
					$('#send-button').show();
					$('#upload-spin').hide();
				},
				error: function (error) {
					var err = '<?=$LANG['Unable to upload your file']?>'+' '+error;
					swal("Oops!", err, "warning");
					$('#save-button').show();
					$('#send-button').show();
					$('#upload-spin').hide();
				},
				async: true,
				data: formData,
				cache: false,
				contentType: false,
				processData: false,
				timeout: 60000
			});
		};
		Upload.prototype.progressHandling = function (event) {
			var percent = 0;
			var position = event.loaded || event.position;
			var total = event.total;
			var progress_bar_id = "#progress-wrp";
			if (event.lengthComputable) {
				percent = Math.ceil(position / total * 100);
			}
			$(progress_bar_id).text(percent + "%");
		};
		//upload contact files
		$("#files").on("change", function (e) {
			var file = $(this)[0].files[0];
			var fileSize = file.size/1024;
			var max_upload = <?=getSetting('maxFileLimit',0)>0?getSetting('maxFileLimit',0)*1024:'3072'?>;
			if(fileSize > max_upload) {
				maxoad = Math.ceil(max_upload/1024)
				swal("Oops!", '<?=$LANG['Your file is too large. Please choose a file below']?> '+maxoad+' MB', "warning");
			} else {
				var upload = new Upload(file);
				upload.doUpload('files_holder','uploadfileCon');
			}
		});
		//upload audio
		$("#voice_file").on("change", function (e) {
			var file = $(this)[0].files[0];
			var fileSize = file.size/1024;
			var max_upload = <?=getSetting('maxFileLimit',0)>0?getSetting('maxFileLimit',0)*1024:'3072'?>;
			if(fileSize > max_upload) {
				maxoad = Math.ceil(max_upload/1024)
				swal("Oops!", '<?=$LANG['Your file is too large. Please choose a file below']?> '+maxoad+' MB', "warning");
			} else {
				var upload = new Upload(file);
				upload.doUpload('voice_holder','uploadfileAud');
			}
		});
		//upload multimedia
		$("#media_file").on("change", function (e) {
			var file = $(this)[0].files[0];
			var fileSize = file.size/1024;
			var max_upload = <?=getSetting('maxFileLimit',0)>0?getSetting('maxFileLimit',0)*1024:'3072'?>;
			if(fileSize > max_upload) {
				maxoad = Math.ceil(max_upload/1024)
				swal("Oops!", '<?=$LANG['Your file is too large. Please choose a file below']?> '+maxoad+' MB', "warning");
			} else {
				var upload = new Upload(file);
				upload.doUpload('media_holder','uploadfileMM');
			}
		});
	<?php } ?>
	<?php if($URL=='sent' || $URL=='rsent' || $URL=='asent'){?>
			$(document).ready(function(){
			// Peity Chart
				$.fn.peity.defaults.pie = {
					delimiter: null,
					fill: ["#26A69A", "#CC6633", "#b2dfdb"],
					height: null,
					radius: 8,
					width: null
				};
				$("span.pie").peity("pie")
				//show graph
				if($('#shown').is(":checked")){
				  $('#sent_graph').show('slow');
				} else {
					$('#sent_graph').hide('slow');
				}
			});
			$('#graph_swit').click(function() {
				if($('#shown').is(":checked")){
				  $('#sent_graph').show('slow');
				} else {
					$('#sent_graph').hide('slow');
				}
			});
			<?php if(isset($_GET['view'])) { ?>	
			var ctx4 = document.getElementById("chart4").getContext("2d");
			var data4 = [
				{
					value: <?=countSMS('1970-01-01 00:00:00',date('Y-m-d H:i:s'),'','queued',$_GET['view'])?>,
					color:"#2196f3",
					highlight: "#0d47a1",
					label: "Pending"
				},
				{
					value: <?=countSMS('1970-01-01 00:00:00',date('Y-m-d H:i:s'),'','canceled',$_GET['view'])?>,
					color:"#424242",
					highlight: "#212121",
					label: "Canceled"
				},
				{
					value: <?=countSMS('1970-01-01 00:00:00',date('Y-m-d H:i:s'),'','sent',$_GET['view'])?>,
					color: "#4caf50 ",
					highlight: "#1b5e20",
					label: "Sent"
				},
				{
					value: <?=countSMS('1970-01-01 00:00:00',date('Y-m-d H:i:s'),'','failed',$_GET['view'])?>,
					color: "#f44336",
					highlight: "#b71c1c",
					label: "Failed"
				}
			];
		
			var myPieChart = new Chart(ctx4).Pie(data4,{
				segmentShowStroke : true,
				segmentStrokeColor : "#fff",
				segmentStrokeWidth : 2,
				animationSteps : 100,
				animationEasing : "easeOutBounce",
				animateRotate : true,
				animateScale : false,
				responsive: true,
				tooltipCornerRadius: 2
			});
		<?php } ?>
	  <?php } ?>
	  <?php if($URL=='report' || $URL=='aeport'){?>		
			//main graphs
				var url = window.location.href;
				var queryString = url.split('#')[1]; 
                
				<?php 
				$queryString = (isset($_SERVER['HTTPS'])?"https":"http")."://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
				$queryString = explode('?',$queryString);
				$queryString = @trim($queryString[1]);
				if(empty($queryString) || strlen($queryString) < 2) { ?>
				    $('#sms_chart_desc').text('<?=$LANG['Showing stats for today']?>');
	    			var data1 =  [<?=smsChatData(1)?>] ;
				<?php } 
				if($queryString=='day') { ?>
					var data1 = [ <?=smsChatData(1)?> ];
					$('#sms_chart_desc').text('<?=$LANG['Showing stats for today']?>');
				<?php }
				if($queryString=='week') { ?>
					var data1 = [ <?=smsChatData(7)?> ];
					$('#sms_chart_desc').text('<?=$LANG['Showing stats for last 7 days']?>');
				<?php }
				if($queryString=='month') { ?>
					var data1 = [ <?=smsChatData(31)?> ];
					$('#sms_chart_desc').text('<?=$LANG['Showing stats for this month']?>');						
				<?php }
				if($queryString=='months') { ?>
					var data1 = [ <?=smsChatData(30)?> ];
					$('#sms_chart_desc').text('<?=$LANG['Showing stats for last 30 days']?>');						
				<?php }
				if($queryString=='quater') { ?>
					var data1 = [ <?=smsChatData(3)?> ];
					$('#sms_chart_desc').text('<?=$LANG['Showing stats for last 3 months']?>');						
				<?php }
				if($queryString=='half') { ?>
					var data1 = [ <?=smsChatData(6)?> ];
					$('#sms_chart_desc').text('<?=$LANG['Showing stats for last 6 months']?>');						
				<?php }
				if($queryString=='year') { ?>
					var data1 = [ <?=smsChatData(12)?> ];
					$('#sms_chart_desc').text('<?=$LANG['Showing stats for this year']?>');						
				<?php } ?>
				Morris.Area({
				  element: 'chart1',				  
				  data: data1,
				  xkey: 'x',
				  pointSize: 2,
				  ykeys: ['Sent', 'Failed'],
				  labels: ['Sent SMS', 'Failed SMS'],
				  lineColors: ['#003300', '#FF3300'],
				  parseTime: false,
				  hideHover: 'auto',
				  resize: true
				}).on('click', function(i, row){
				  
				});
				
				//SMS Chat by Country
				 var ctx2 = document.getElementById("chart2").getContext("2d");
					var data2 = {
						<?=countryChatData2(0)?>
					};
				
					var chart2 = new Chart(ctx2).Bar(data2, {
						scaleBeginAtZero : true,
						scaleShowGridLines : true,
						scaleGridLineColor : "rgba(0,0,0,.05)",
						scaleGridLineWidth : 1,
						scaleShowHorizontalLines: true,
						scaleShowVerticalLines: false,
						barShowStroke : true,
						barStrokeWidth : 2,
						barDatasetSpacing : 1,
						responsive: true,
						scaleOverride: false,
						scaleSteps: 6,
						scaleStepWidth: 50,
						scaleStartValue: 0,
						barValueSpacing: 20,
						tooltipCornerRadius: 2
					});
					
				//detect page change
				var oldURL = location.href;
				setInterval(function() {
					  if(location.href != oldURL) {
						   location.reload();
						   oldURL = location.href
					  }
				  }, 1000); 

	<?php } ?>	

		function ediCon(fname,lname,phone,dob,id) {
			$('#fname').val(fname);  $("#fname" ).focus();
			$('#lname').val(lname);  $("#lname" ).focus();
			$('#phone').val(phone);  $("#phone" ).focus();
			$('#updateCon').val(id);
			$('#files_holder').val('');
			$('#dob').val(dob);  $("#dob" ).focus();
			$('#add_new').show('slow');
			if(id>0) {
				$('#bulk_cont').addClass("disabled");
			}
		}

		function resCode(code) {
			$('#add_new2').show('slow');
			$('#shortcode2').val(code);
			$('#senderid2').val(code);
		}
<?php if(userRole()!=4) { ?>
		function eddiCurr(id,title,code,rate,symbol,zeros) {
			$('#add_new2').show('slow');
			$('#title').val(title); $("#title" ).focus();
			$('#code').val(code); $("#code" ).focus();
			$('#rate').val(rate); $("#rate" ).focus();
			$('#zeros').val(zeros); $("#zeros" ).focus();
			$('#symbul').val(symbol); $("#symbul" ).focus();
			$('#currency_id').val(id);
		}
<?php } ?>		
		function addPB() {
			$('#add_new').show('slow');
		}
		function addCusRate() { 
			$('#add_new2').show('slow');
		}	
		function addCusRoute() { 
			$('#add_new2R').show('slow');
		}	
		function addCredit() { 
			$('#add_new3').show('slow');
		}
<?php if(userRole()!=4) { ?>
		function editCode(code,customer,shortcode,price) {
			$("#shortcode_id").val(code);
			$("#customer_id").val(customer);
			$("#shortcode").val(shortcode);  $("#shortcode" ).focus();
			$("#price").val(price);  $("#price" ).focus();
			$('#add_new').show('slow');
		}		
<?php } ?>
<?php if(userRole()<3) { ?>
		//edit gateway
		function editSMSG(result) {
			var gateway_id = result;	
			if(gateway_id < 1) {
				swal("Oops!", '<?=$LANG['Unable to load SMS gateway data']?> ', "warning");
			} else {
				$.ajax({url: "API?load_sms_gateways&id="+gateway_id, success: function(result){ 
				var result = JSON.parse(result);
				
				$('#sgateway_id').val(result.id)
				$('#sgtype').val(result.type);
					if(result.alias == 'custom') {
						$('.show-custom').show();
					} else {
						$('.show-custom').hide();
					}
					setup_text = result.setup_text;
					if(setup_text != '') {
						$('.show-text').show();
						$('#setup_text').html(setup_text);
					} else {
						$('.show-text').hide();	
					}
					if(result.type == 'voice') {
						$('.show-voice').show();
					} else {
						$('.show-voice').hide();
						if(result.type == 'mms') {
							$('.show-mms').show();
						}
					}
					if(result.type == 'mms') {
						$('.show-mms').show();
					} else {
						if(result.type != 'voice') {
							$('.show-mms').hide();
						}
					}
					if(result.type == '2way') {
						$('.hide-2way').hide();
						$('.show-2way').show();
					} else {
						$('.show-2way').hide();
						$('.hide-2way').show();
					}
					if(result.alias != 'custom') {
						if(result.authentication == '0') {
							$('.show-auth').hide();
						} else {
							$('.show-auth').show();
						}
					} else {
						$('.show-auth').hide();	
					}
					if(result.alias != 'custom') {
						if(result.param1_value != '') {
							$('.show_p1').show();
							$('#param1_value').val(result.param1_value);
						} else {
							$('.show_p1').hide(); 
						}
						if(result.param2_value != '') {
							$('.show_p2').show();
							$('#param2_value').val(result.param2_value);
						} else {
							$('.show_p2').hide();
						}
						if(result.param3_value != '') {
							$('.show_p3').show();
							$('#param3_value').val(result.param3_value);
						} else {
							$('.show_p3').hide();
						}
						if(result.param4_value != '') {
							$('.show_p4').show();
							$('#param4_value').val(result.param4_value);
						} else {
							$('.show_p4').hide();
						}
						$('#request_type').val(result.request_type);

					} else {
						$('.show_p1').show();
						$('#label_p1').text('<?=$LANG['Parameter 1 Value']?>');
						$('.show_p2').show();
						$('#label_p2').text('<?=$LANG['Parameter 2 Value']?>');
						$('.show_p3').show();
						$('#label_p3').text('<?=$LANG['Parameter 3 Value']?>');
						$('.show_p4').show();
						$('#label_p4').text('<?=$LANG['Parameter 4 Value']?>');
						$('#param1_value').val(result.param1_value);  $("#param1_value" ).focus();
						$('#param2_value').val(result.param2_value);  $("#param2_value" ).focus();
						$('#param3_value').val(result.param3_value); $("#param3_value" ).focus();
						$('#param4_value').val(result.param4_value); $("#param4_value" ).focus();
						$('#param1_field').val(result.param1_field); $("#param1_field" ).focus();
						$('#param2_field').val(result.param2_field); $("#param2_field" ).focus();
						$('#param3_field').val(result.param3_field); $("#param3_field" ).focus();
						$('#param4_field').val(result.param4_field); $("#param4_field" ).focus();
					}
					$("#cusType").val(result.type);
					$('#sgtitle').val(result.title);
					$('#base_url').val(result.base_url); $("#base_url" ).focus();
					$('#success_word').val(result.success_word); $("#success_word" ).focus();
					$('#success_logic').val(result.success_logic); $("#success_logic" ).focus();
					$('#authentication').val(result.authentication); $("#authentication" ).focus();
					$('#username').val(result.username); $("#username" ).focus();
					$('#password').val(result.password); $("#password" ).focus();
					$('#sender_field').val(result.sender_field); $("#sender_field" ).focus();
					$('#recipient_field').val(result.recipient_field); $("#recipient_field" ).focus();
					$('#message_field').val(result.message_field); $("#message_field" ).focus();
					$('#audio_field').val(result.audio_field); $("#title" ).focus();
					$('#timeout_field').val(result.timeout_field); $("#timeout_field" ).focus();
					$('#language_field').val(result.language_field); $("#language_field" ).focus();
					$('#hour_limit').val(result.hour_limit); $("#hour_limit" ).focus();
					$('#cutting_percent').val(result.cutting_percent); $("#cutting_percent" ).focus();
					$('#cutting_limit').val(result.cutting_limit); $("#cutting_limit" ).focus();
					$('#json_encode').val(result.json_encode); $("#json_encode" ).focus();
					$('#base64_encode').val(result.base64_encode); $("#base64_encode" ).focus();
					$('#sgtype').val(result.type); $("#type" ).focus();
					$('#balance_url').val(result.balance_url); $("#balance_url" ).focus();
					$('#alias').val(result.alias); 
					$('#alias').prepend('<option selected value="'+result.alias+'">'+result.alias+'</option>');
					$('#add_sms_pop').show('slow');	 $("#title" ).focus();
					$('#alias').select2('open').select2('close');
				}});
			}
		}
<?php } ?>		
		//edit payment gateway
<?php if(userRole()!=4) { ?>		
		function editPayG(gtype,gtitle,param1,param2,param3,minimum_order,charge_type,charges_perc,charges_fix,text,genabled,gateway_id) {
			$('#add_gateway_pop').show('slow');	
			$("#gtype").val(gtype).change();
			$("#gtype option[value="+gtype+"]").prop('selected', 'selected');
			$("#gtitle").val(gtitle); $("#gtitle" ).focus();
			$("#param1").val(param1); $("#param1" ).focus();
			$("#param2").val(param2); $("#param2" ).focus();
			$("#param3").val(param3); $("#param3" ).focus();
			$("#minimum_order").val(minimum_order); $("#minimum_order" ).focus();
			$("#charge_type").val(charge_type).change();
			$("#charge_type option[value="+charge_type+"]").prop('selected', 'selected');
			$("#charges_perc").val(charges_perc); $("#charges_perc" ).focus();
			$("#charges_fix").val(charges_fix); $("#charges_fix" ).focus();
			$("#text").val(text); $("#text" ).focus();
			$("#genabled").val(genabled).change();
			$("#genabled option[value="+genabled+"]").prop('selected', 'selected');
			$("#gateway_id").val(gateway_id);
			
			if(aka == 'percent') {
				$('#hide_pec').hide();
			} else {
				$('#hide_pec').show();
			}
			if(aka == 'fixed') {
				$('#hide_fix').hide();
			} else {
				$('#hide_fix').show();
			}
		}
<?php } ?>			
$(document).ready(function(){
	<?php if($URL=='phonebook' || $URL=='aphonebook'){?>		
	<?php if($URL == 'aphonebook' && isset($_GET['view'])) { ?>
		$('#member').select2();
	<?php } ?>
	//Update phonebook
		$('#updateP-button').click(function(event) { 
			event.preventDefault();	  
			$('#updateP-button').hide();
			$('#save-spin').show();
			
			var formData = {
				'title'  : $('#title').val(),
				'phonebook_id'  : $('#phonebook_id').val(),
				'description'  : $('#description').val(),
				'message'  : $('#message').val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?save_phonebook',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal("<?=$LANG['Done']?>!", '<?=$LANG['Your_phonebook_update']?>', "success");
					$('#updateP-button').show();
					$('#save-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to save changes']?> '+status, "warning");
					$('#updateP-button').show();
					$('#save-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#updateP-button').show();
				$('#save-spin').hide();
			});
		});	
		//save phonebopok
		$('#phon-button').click(function(event) { 
			event.preventDefault();	  
			$('#phon-button').hide();
			$('#phon-spin').show();
			
			var formData = {
				'title'  : $('#title').val(),
				'phonebook_id'  : $('#phonebook_id').val(),
				'description'  : $('#description').val(),
				'message'  : $('#message').val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?save_phonebook',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['Your_phonebook_update']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>'; 
					});
					$('#phon-button').show();
					$('#phon-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to save changes']?> '+status, "warning");
					$('#phon-button').show();
					$('#phon-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#phon-button').show();
				$('#phon-spin').hide();
			});
		});	
	
		//save contact
		$('#cont-button').click(function(event) { 
			event.preventDefault();	  
			$('#cont-button').hide();
			$('#cont-spin').show();
			var updating = $('#updateCon').val();
			var upload_now = $('#upload_now');
			if (upload_now.is(':checked')) {
				var upload_now = '1';
			} else {
				var upload_now = '0';
			}
			var formData = {
				'fname'  : $('#fname').val(),
				'lname'  : $('#lname').val(),
				'updateCon'  : $('#updateCon').val(),
				'phonebook_id'  : $('#phonebook_id2').val(),
				'files' : $('#files_holder').val(),
				'upload_now' : upload_now,
				'phone'  : $('#phone').val(),
				'dob'  : $('#dob').val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?save_contact',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					var contact_saved = "<?=$LANG['contact_saved']?>";
					var upload_now = $('#upload_now');
					if (upload_now.is(':checked')) {				
						var contact_saved = "<?=$LANG['contact_queued']?>";
					}
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: contact_saved,   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>?view=<?=@$_GET['view']?>'; 
					});
					$('#cont-button').show();
					$('#cont-spin').hide();
					$('#add_new').hide('slow');
				} else {
					swal("Oops!", '<?=$LANG['Unable to save changes']?> '+status, "warning");
					$('#cont-button').show();
					$('#cont-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#cont-button').show();
				$('#cont-spin').hide();
			});
		});	
		//Upload contact
		//alert old schools guys
		if(window.FormData === undefined){
			alert('sorry buddy you\'re browsers too old! You may not be able to use our portal om your current browser');
		}

		//upload contact files
		Upload.prototype.doUpload = function (holder,requests) {
			$('#cont-button').hide();
			$('#upload-spin').show();
			var that = this;
			var formData = new FormData();
			formData.append("file", this.file, this.getName());
			formData.append("upload_file", true);
			$.ajax({
				type: "POST",
				url: "API?"+requests,
				xhr: function () {
					var myXhr = $.ajaxSettings.xhr();
					if (myXhr.upload) {
						myXhr.upload.addEventListener('progress', that.progressHandling, false);
					}
					return myXhr;
				},
				success: function (data) {
					var status = data.split(':')[0];
					var file_url = data.split(':')[1];
					if(status.replace(/\s+/g, '') == 'success') {
						$('#'+holder).val(file_url);
					} else {
						swal("Oops!", data.split(':')[0], "warning");
					}
					$('#cont-button').show();
					$('#upload-spin').hide();
				},
				error: function (error) {
					var err = '<?=$LANG['Unable to upload your file']?>'+' '+error;
					swal("Oops!", err, "warning");
					$('#cont-button').show();
					$('#upload-spin').hide();
				},
				async: true,
				data: formData,
				cache: false,
				contentType: false,
				processData: false,
				timeout: 60000
			});
		};
		Upload.prototype.progressHandling = function (event) {
			var percent = 0;
			var position = event.loaded || event.position;
			var total = event.total;
			var progress_bar_id = "#progress-wrp";
			if (event.lengthComputable) {
				percent = Math.ceil(position / total * 100);
			}
			$(progress_bar_id).text(percent + "%");
		};
		//upload contact files
		$("#files").on("change", function (e) {
			var file = $(this)[0].files[0];
			var fileSize = file.size/1024;
			var max_upload = <?=getSetting('maxFileLimit',0)>0?getSetting('maxFileLimit',0)*1024:'3072'?>;
			if(fileSize > max_upload) {
				maxoad = Math.ceil(max_upload/1024)
				swal("Oops!", '<?=$LANG['Your file is too large. Please choose a file below']?> '+maxoad+' MB', "warning");
			} else {
				var upload = new Upload(file);
				upload.doUpload('files_holder','uploadfileCon');
			}
		});
		//share list
		$('#share-button').click(function(event) { 
			event.preventDefault();	  
			$('#share-button').hide();
			$('#share-spin').show();
			
			var formData = {
				'member'  : $('#member').val(),
				'phonebook_id'  : $('#phonebookid').val(),
				'user' : '<?=$userID?>'
			};

			$.ajax({
				type        : 'POST', 
				url         : 'API?share_phonebook',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['Your_list_shared']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>?view=<?=@$_GET['view']?>'; 
					});
					$('#share-button').show();
					$('#share-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to share addressbook']?> '+status, "warning");
					$('#share-button').show();
					$('#share-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#share-button').show();
				$('#share-spin').hide();
			});
		});	
	<?php } ?>	
	<?php if($URL=='marketinglist' || $URL=='amarketinglist'){?>		
	<?php if($URL == 'amarketinglist' && isset($_GET['view'])) { ?>
		$('#member').select2();
	<?php } ?>
	//Update marketinglist
		$('#updateP-button').click(function(event) { 
			event.preventDefault();	  
			$('#updateP-button').hide();
			$('#save-spin').show();
			
			var formData = {
				'title'  : $('#title').val(),
				'optout_key'  : $('#optout_key').val(),
				'optin_key'  : $('#optin_key').val(),
				'optout_sms'  : $('#optout_sms').val(),
				'optin_sms'  : $('#optin_sms').val(),
				<?php if(isAdmin($userID)) { ?>
				'is_public'  : $('#is_public').val(),
				'cost'  : $('#cost').val(),
				<?php } ?>
				'shortcode'  : $('#shortcode').val(),
				'default_sender_id'  : $('#default_sender_id').val(),
				'phonebook_id'  : $('#phonebook_id').val(),
				'description'  : $('#description').val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?save_marketinglist',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal("<?=$LANG['Done']?>!", '<?=$LANG['Your_marketinglist_update']?>', "success");
					$('#updateP-button').show();
					$('#save-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to save changes']?> '+status, "warning");
					$('#updateP-button').show();
					$('#save-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#updateP-button').show();
				$('#save-spin').hide();
			});
		});	
		//save marketinglist
		$('#phon-button').click(function(event) { 
			event.preventDefault();	  
			$('#phon-button').hide();
			$('#phon-spin').show();
			
			var formData = {
				'title'  : $('#title').val(),
				'optout_key'  : $('#optout_key').val(),
				'optin_key'  : $('#optin_key').val(),
				'optout_sms'  : $('#optout_sms').val(),
				'optin_sms'  : $('#optin_sms').val(),
				'shortcode'  : $('#shortcode').val(),
				'default_sender_id'  : $('#default_sender_id').val(),
				'phonebook_id'  : $('#phonebook_id').val(),
				'description'  : $('#description').val(),
				<?php if(isAdmin($userID)) { ?>
				'is_public'  : $('#is_public').val(),
				'cost'  : $('#cost').val(),
				<?php } ?>
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?save_marketinglist',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['Your_phonebook_update']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>'; 
					});
					$('#phon-button').show();
					$('#phon-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to save changes']?> '+status, "warning");
					$('#phon-button').show();
					$('#phon-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#phon-button').show();
				$('#phon-spin').hide();
			});
		});	
		//share list
		$('#share-button').click(function(event) { 
			event.preventDefault();	  
			$('#share-button').hide();
			$('#share-spin').show();
			
			var formData = {
				'member'  : $('#member').val(),
				'phonebook_id'  : $('#phonebookid').val(),
				'user' : '<?=$userID?>'
			};

			$.ajax({
				type        : 'POST', 
				url         : 'API?share_marketinglist',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['Your_list_shared']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>?view=<?=@$_GET['view']?>'; 
					});
					$('#share-button').show();
					$('#share-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to share list']?> '+status, "warning");
					$('#share-button').show();
					$('#share-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#share-button').show();
				$('#share-spin').hide();
			});
		});	
		
		//save contact
		$('#cont-button').click(function(event) { 
			event.preventDefault();	  
			$('#cont-button').hide();
			$('#cont-spin').show();
			var updating = $('#updateCon').val();
			var upload_now = $('#upload_now');
			if (upload_now.is(':checked')) {
				var upload_now = '1';
			} else {
				var upload_now = '0';
			}
			var formData = {
				'fname'  : $('#fname').val(),
				'updateCon'  : $('#updateCon').val(),
				'phonebook_id'  : $('#phonebook_id2').val(),
				'files' : $('#files_holder').val(),
				'upload_now' : upload_now,
				'phone'  : $('#phone').val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?save_marketinglistcontact',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					var contact_saved = "<?=$LANG['contact_saved']?>";
					var upload_now = $('#upload_now');
					if (upload_now.is(':checked')) {				
						var contact_saved = "<?=$LANG['contact_queued']?>";
					}
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: contact_saved,   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>?view=<?=@$_GET['view']?>'; 
					});
					$('#cont-button').show();
					$('#cont-spin').hide();
					$('#add_new').hide('slow');
				} else {
					swal("Oops!", '<?=$LANG['Unable to save changes']?> '+status, "warning");
					$('#cont-button').show();
					$('#cont-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#cont-button').show();
				$('#cont-spin').hide();
			});
		});	
		//Upload contact
		//alert old schools guys
		if(window.FormData === undefined){
			alert('sorry buddy you\'re browsers too old! You may not be able to use our portal om your current browser');
		}

		//upload contact files
		Upload.prototype.doUpload = function (holder,requests) {
			$('#cont-button').hide();
			$('#upload-spin').show();
			var that = this;
			var formData = new FormData();
			formData.append("file", this.file, this.getName());
			formData.append("upload_file", true);
			$.ajax({
				type: "POST",
				url: "API?"+requests,
				xhr: function () {
					var myXhr = $.ajaxSettings.xhr();
					if (myXhr.upload) {
						myXhr.upload.addEventListener('progress', that.progressHandling, false);
					}
					return myXhr;
				},
				success: function (data) {
					var status = data.split(':')[0];
					var file_url = data.split(':')[1];
					if(status.replace(/\s+/g, '') == 'success') {
						$('#'+holder).val(file_url);
					} else {
						swal("Oops!", data.split(':')[0], "warning");
					}
					$('#cont-button').show();
					$('#upload-spin').hide();
				},
				error: function (error) {
					var err = '<?=$LANG['Unable to upload your file']?>'+' '+error;
					swal("Oops!", err, "warning");
					$('#cont-button').show();
					$('#upload-spin').hide();
				},
				async: true,
				data: formData,
				cache: false,
				contentType: false,
				processData: false,
				timeout: 60000
			});
		};
		Upload.prototype.progressHandling = function (event) {
			var percent = 0;
			var position = event.loaded || event.position;
			var total = event.total;
			var progress_bar_id = "#progress-wrp";
			if (event.lengthComputable) {
				percent = Math.ceil(position / total * 100);
			}
			$(progress_bar_id).text(percent + "%");
		};
		//upload contact files
		$("#files").on("change", function (e) {
			var file = $(this)[0].files[0];
			var fileSize = file.size/1024;
			var max_upload = <?=getSetting('maxFileLimit',0)>0?getSetting('maxFileLimit',0)*1024:'3072'?>;
			if(fileSize > max_upload) {
				maxoad = Math.ceil(max_upload/1024)
				swal("Oops!", '<?=$LANG['Your file is too large. Please choose a file below']?> '+maxoad+' MB', "warning");
			} else {
				var upload = new Upload(file);
				upload.doUpload('files_holder','uploadfileCon');
			}
		});
	<?php } ?>	
	<?php if($URL=='blacklist' || $URL=='ablacklist') { ?>
	//save contact
		$('#cont-button').click(function(event) { 
			event.preventDefault();	  
			$('#cont-button').hide();
			$('#cont-spin').show();
			var formData = {
				'phone'  : $('#phone').val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?save_blacklist',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['contact_saved']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>'; 
					});
					$('#cont-button').show();
					$('#cont-spin').hide();
					$('#add_new').hide('slow');
				} else {
					swal("Oops!", '<?=$LANG['Unable to save changes']?> '+status, "warning");
					$('#cont-button').show();
					$('#cont-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#cont-button').show();
				$('#cont-spin').hide();
			});
		});	

	<?php } ?>
	<?php if($URL=='shortcodes' || $URL=='ashortcodes') { ?>
	//buy shortcode
		<?php if($URL=='shortcodes') { ?>
		$('#shortcode').select2();  <?php } else {?>
		$('#capability').select2(); 
		<?php } ?>
		$('#customer_id').select2(); 
		$('#cont-button').click(function(event) { 
			event.preventDefault();	  
			$('#cont-button').hide();
			$('#cont-spin').show();
			var shortcode = $("#shortcode").val();
			if(shortcode !== null && shortcode !== '') {
				var number = shortcode.split(':')[0];
			} else {
				var number = '';	
			}
			var formData = {
				'phone'  : number,
				'data'	: $("#shortcode").val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?buy_shortcode',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['shortcode_saved']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>'; 
					});
					$('#cont-button').show();
					$('#cont-spin').hide();
					$('#add_new').hide('slow');
				} else {
					swal("Oops!", '<?=$LANG['Unable to purchase shortcode']?> '+status, "warning");
					$('#cont-button').show();
					$('#cont-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#cont-button').show();
				$('#cont-spin').hide();
			});
		});	
		
		$('#acont-button').click(function(event) { 
			event.preventDefault();	  
			$('#acont-button').hide();

			$('#acont-spin').show();
			
			var formData = {
				'customer_id'	: $("#customer_id").val(),
				'shortcode'	: $("#shortcode").val(),
				'shortcode_id'	: $("#shortcode_id").val(),
				'price'	: $("#price").val(),
				'capability' : $("#capability").val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?add_shortcode',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['ashortcode_saved']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>'; 
					});
					$('#acont-button').show();
					$('#acont-spin').hide();
					$('#add_new').hide('slow');
				} else {
					swal("Oops!", '<?=$LANG['Unable to purchase shortcode']?> '+status, "warning");
					$('#acont-button').show();
					$('#acont-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#acont-button').show();
				$('#acont-spin').hide();
			});
		});	
		
		$('#sha-button').click(function(event) { 
			event.preventDefault();	  
			$('#sha-button').hide();
			$('#sha-spin').show();
			var shortcode = $("#shortcode2").val();
			
			var formData = {
				'shortcode'  : shortcode,
				'customer'	: $("#customer_id").val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?share_shortcode',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['shortcode_shared']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = 'shortcodes'; 
					});
					$('#sha-button').show();
					$('#sha-spin').hide();
					$('#add_new2').hide('slow');
				} else {
					swal("Oops!", '<?=$LANG['Unable to share shortcode']?> '+status, "warning");
					$('#sha-button').show();
					$('#sha-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#sha-button').show();
				$('#sha-spin').hide();
			});
		});	

		<?php if($URL=='shortcodes') { ?>
		$('#shortcode').change(function () {
			var exrate = '<?=userExchangeRate($userID)?>';
			var number = $("#shortcode").val();
			var to_pay = number_format(((number.split(':')[1])*exrate),<?=userCurrencyZero($userID)?>,'.',',');
			var cycle = number.split(':')[2];
			if(cycle==1) var period = '<?=$LANG['Monthly']?>';
			var price = to_pay+' '+period;
			$('#price').val(price);
		});
		<?php } ?>
	<?php } ?>
	<?php if($URL=='senderid' || $URL=='asenderid') { ?>
	//buy shortcode
		$('#shortcode').select2(); 
		<?php if($URL=='asenderid') { ?>
		 $('#customer_id').select2(); customer_id
		<?php } ?> 
		$('#cont-button').click(function(event) { 
			event.preventDefault();	  
			$('#cont-button').hide();
			$('#cont-spin').show();			
			var formData = {
				'type'	: $("#type").val(),
				'customer': $("#customer_id").val(),
				'senderid'	: $("#sender").val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?add_senderid',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						<?php if(isAdmin(getUser())) { ?>
						text: "<?=$LANG['senderid_added']?>",   
						<?php } else {?>
						text: "<?=$LANG['senderid_saved']?>",   
						<?php } ?>
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>'; 
					});
					$('#cont-button').show();
					$('#cont-spin').hide();
					$('#add_new').hide('slow');
				} else {
					swal("Oops!", '<?=$LANG['Unable to create sender ID']?> '+status, "warning");
					$('#cont-button').show();
					$('#cont-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#cont-button').show();
				$('#cont-spin').hide();
			});
		});	
		$('#sha-button').click(function(event) { 
			event.preventDefault();	  
			$('#sha-button').hide();
			$('#sha-spin').show();
			var senderid = $("#senderid2").val();
			
			var formData = {
				'senderid'  : senderid,
				'customer'	: $("#customer_id").val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?share_senderid',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['sender_shared']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = 'senderid'; 
					});
					$('#sha-button').show();
					$('#sha-spin').hide();
					$('#add_new2').hide('slow');
				} else {
					swal("Oops!", '<?=$LANG['Unable to share Sender ID']?> '+status, "warning");
					$('#sha-button').show();
					$('#sha-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#sha-button').show();
				$('#sha-spin').hide();

			});
		});		
		
	<?php } ?>
	<?php if($URL=='share') { ?>
	//transfer credit
		$('#share-button').click(function(event) { 
			event.preventDefault();	  
			$('#share-button').hide();
			$('#share-spin').show();
			
			var formData = {
				'credit'  :  $("#credit").val(),
				'member'	: $("#member").val(),
				'pass'	: $("#pass").val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?share_credit',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['credit_shared']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = 'share'; 
					});
					$('#share-button').show();
					$('#share-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to complete action']?> '+status, "warning");
					$('#share-button').show();
					$('#share-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#share-button').show();
				$('#share-spin').hide();
			});
		});	
		
	<?php } ?>
    <?php if($URL=='apis' || $URL=='aapis') { ?>
	//enable feature
		$('#api-button').click(function(event) { 
			event.preventDefault();	  
			$('#api-button').hide();
			$('#api-spin').show();
			
			var formData = {
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?enable_api',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['api_enabled']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>'; 
					});
					$('#api-button').show();
					$('#api-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to complete action']?> '+status, "warning");
					$('#api-button').show();
					$('#api-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#api-button').show();
				$('#api-spin').hide();
			});
		});	
		$('#apis-button').click(function(event) { 
			event.preventDefault();	  
			$('#apis-button').hide();
			$('#apis-spin').show();
			
			var formData = {
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?enable_api',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['apis_enabled']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>'; 
					});
					$('#apis-button').show();
					$('#apis-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to complete action']?> '+status, "warning");
					$('#apis-button').show();
					$('#apis-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#apis-button').show();
				$('#apis-spin').hide();
			});
		});	
		
	<?php } ?>
	<?php if($URL=='ticket' || $URL=='rticket' || $URL=='aticket') { ?>
		$( document ).ready(function() {
			<?php if($URL!='ticket' && !isset($_GET['ti'])) { ?>
			$('#customer').select2();
			<?php } ?>
			 jQuery.fn.extend({
				toggleText: function (a, b){
					var that = this;
					if (that.text() != a && that.text() != b){
						that.text(a);
					}
					else
						if (that.text() == a){
							that.text(b);
						}
					else
						if (that.text() == b){
							that.text(a);
						}
					return this;
				}
			});
			var editor = new Simditor({
				textarea: $('#message'),
				toolbar: [
				 'title',
				  'bold',
				  'italic',
				  'underline',
				  'strikethrough',
				  'fontScale',
				  'color',
				  'ol',            
				  'ul',            
				  'blockquote',
				  'code',        
				  'table',
				  'link',
				  'image',
				  'hr',            
				  'indent',
				  'outdent',
				  'alignment'
				]
			});
		});
		
		//upload contact files
		Upload.prototype.doUpload = function (holder,requests) {
			$('#send-button').hide();
			$('#send-spin').show();
			var that = this;
			var formData = new FormData();
			formData.append("file", this.file, this.getName());
			formData.append("upload_file", true);
			$.ajax({
				type: "POST",
				url: "API?"+requests,
				xhr: function () {
					var myXhr = $.ajaxSettings.xhr();
					if (myXhr.upload) {
						myXhr.upload.addEventListener('progress', that.progressHandling, false);
					}
					return myXhr;
				},
				success: function (data) {
					var status = data.split(':')[0];
					var file_url = data.split(':')[1];
					if(status.replace(/\s+/g, '') == 'success') {
						$('#'+holder).val(file_url);
					} else {
						swal("Oops!", data.split(':')[0], "warning");
					}
					$('#send-button').show();
					$('#send-spin').hide();
				},
				error: function (error) {
					var err = '<?=$LANG['Unable to upload your file']?>'+' '+error;
					swal("Oops!", err, "warning");
					$('#send-button').show();
					$('#send-spin').hide();
				},
				async: true,
				data: formData,
				cache: false,
				contentType: false,
				processData: false,
				timeout: 60000
			});
		};
		Upload.prototype.progressHandling = function (event) {
			var percent = 0;
			var position = event.loaded || event.position;
			var total = event.total;
			var progress_bar_id = "#progress-wrp";
			if (event.lengthComputable) {
				percent = Math.ceil(position / total * 100);
			}
			$(progress_bar_id).text(percent + "%");
		};
		//upload contact files
		$("#files").on("change", function (e) {
			var file = $(this)[0].files[0];
			var fileSize = file.size/1024;
			var max_upload = <?=getSetting('maxFileLimit',0)>0?getSetting('maxFileLimit',0)*1024:'3072'?>;
			if(fileSize > max_upload) {
				maxoad = Math.ceil(max_upload/1024)
				swal("Oops!", '<?=$LANG['Your file is too large. Please choose a file below']?> '+maxoad+' MB', "warning");
			} else {
				var upload = new Upload(file);
				upload.doUpload('files_holder','uploadfileMM');
			}
		});
		
		$('#send-button').click(function(event) { 
			event.preventDefault();	  
			$('#send-button').hide();
			$('#send-spin').show();
			
			var formData = {
				'customer'  :  $("#customer").val(),
				'subject'  :  $("#subject").val(),
				'ticket'  :  $("#ticket").val(),
				'message'  :  $("#message").val(),
				'attach'  : $("#files_holder").val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?post_ticket',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['post_ticket']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>'; 
					});
					$('#send-button').show();
					$('#send-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to complete action']?> '+status, "warning");
					$('#send-button').show();
					$('#send-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#send-button').show();
				$('#send-spin').hide();
			});
		});
		
	<?php } ?>
	<?php if($URL=='rcustomer' || $URL=='acustomer' || $URL=='user') { ?>
		$('.js-states').select2(); 
	<?php if($URL == 'acustomer') { ?> 	
		if($('#billingModel').val() == 'unit') {
			$('#show_advancedUnitPricing').show();
		} else {
			$('#show_advancedUnitPricing').hide();
		}	
	  $('#billingModel').change(function(){
			if($('#billingModel').val() == 'unit') {
				$('#show_advancedUnitPricing').show();
			} else {
				$('#show_advancedUnitPricing').hide();
			}	
		});
		
		$('#route-button').click(function(event) { 
			event.preventDefault();	  
			$('#route-button').hide();
			$('#route-spin').show();
			
			var formData = {
				'customer_id'  :  $("#customer_id2R").val(),
				'country'  :  $("#country_code2").val(),
				'operator'  :  $("#operator_code2").val(),
				'gateway_id'  :  $("#gateway_id").val(),
				'group_id'  :  $("#group_id").val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?add_route',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['Your changes have been saved']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>?v='+$("#customer_id2R").val(); 
					});
					$('#route-button').show();
					$('#route-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to complete action']?> '+status, "warning");
					$('#route-button').show();
					$('#route-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#route-button').show();
				$('#route-spin').hide();
			});
		});
	<?php } ?>	
	  $('#cus-button').click(function(event) { 
			event.preventDefault();	  
			$('#cus-button').hide();
			$('#cus-spin').show();
			var formData = {
				'customer_id'  : $('#customer_id').val(),
				'first_name'  : $('#fname').val(),
				'last_name'  : $('#lname').val(),
				'email'    : $('#email').val(),
				'phone'  : $('#phone').val(),
				'country_id'  : $('#country').val(),
				'password'  : $('#password').val(),
				'default_sender_ID'  : $('#default_sender_ID').val(),
				'currency_id'  : $('#currency').val(),
				'language_id'  : $('#language_id').val(),
				<?php if($URL == 'acustomer') { ?> 
				'account_manager'  : $('#account_manager').val(),
				'advancedUnitPricing'  : $('#advancedUnitPricing').val(),
				'billingModel'  : $('#billingModel').val(),
                'reseller'  : $('#reseller_id').val(),
				<?php } ?>
				<?php if($URL != 'user') { ?> 
				'no_tax'    : $('#no_tax').val(),
				'min_order'  : $('#min_order').val(),
				'birthday'  : $('#birthday').val(),
				//Do Custom Fields
				<?php $reseller = resellerByDomain() ?>
				<?=loadCustomFormFields($reseller,$userID,0) ?>
				<?php } ?>
				'address'  : $('#address').val(),
				'city'  : $('#city').val(),
				'state'  : $('#state').val(),
				<?php if($URL=='acustomer' || $URL == 'user') { ?>
				'role_id'  : $('#role_id').val(),
				<?php } ?>
				'add_customer'	: '1',
				'user' : '<?=$userID?>'
			};
	
			$.ajax({
				type        : 'POST', 
				url         : 'API',
				data        : formData, 
				dataType    : 'json',
				encode      : true
			}).done(function(data) { 
				if ( ! data.success) { 
					if (data.errors) {
						swal("Oops!", data.errors, "warning");
						$('#cus-button').show();
						$('#cus-spin').hide();
					}
				} else { 
					swal({   
						title: "<?=$LANG['Done']?>!",  
						<?php if($URL == 'user') { ?> 
						text: "<?=$LANG['user_created']?>",   
						<?php } else { ?>
						text: "<?=$LANG['cus_created']?>",   
						<?php } ?>
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){ 
						<?php if(isset($_GET['v'])) { ?> 
						window.location = '<?=$URL.'?v='.$_GET['v']?>'; 
						<?php } else { ?>
						window.location = '<?=$URL?>'; 
						<?php } ?>
					});
				}
				}).fail(function (jqXHR,status,err) {
					swal("Oops!", "<?=$LANG['Unable to establish connection to server']?>! "+err, "warning");
					$('#cus-button').show();
					$('#cus-spin').hide();
				});
		});		
		$('#rate-button').click(function(event) { 
			event.preventDefault();	  
			$('#rate-button').hide();
			$('#rate-spin').show();
			
			var formData = {
				'customer'  :  $("#customer_id2").val(),
				'country'  :  $("#country_code").val(),
				'operator'  :  $("#operator_code").val(),
				'gateway'  :  $("#gateway").val(),
				'type'  :  $("#type").val(),
				'rate'  :  $("#rate").val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?add_rate',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['cu_rate_saved']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL.'?v='.@$_GET['v']?>'; 
					});
					$('#rate-button').show();
					$('#rate-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to complete action']?> '+status, "warning");
					$('#rate-button').show();
					$('#rate-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#rate-button').show();
				$('#rate-spin').hide();
			});
		});
		
		$('#role-button').click(function(event) { 
			event.preventDefault();	  
			$('#role-button').hide();
			$('#role-spin').show();
			var formData = $('#add_nrole').serialize();
						
			$.ajax({
				type        : 'POST', 
				url         : 'API?add_admin_role',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['role__saved']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL.'?v='.@$_GET['v']?>'; 
					});
					$('#role-button').show();
					$('#role-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to complete action']?> '+status, "warning");
					$('#role-button').show();
					$('#role-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#role-button').show();
				$('#role-spin').hide();
			});
		});

		//alert old schools guys
		if(window.FormData === undefined){
			alert('sorry buddy you\'re browsers too old! You may not be able to use our portal om your current browser');
		}
		//upload from files
		Upload.prototype.doUpload = function (holder,requests) {
			$('#imp-button').hide();
			$('#upload-spin').show();
			var that = this;
			var formData = new FormData();
			formData.append("file", this.file, this.getName());
			formData.append("upload_file", true);
			$.ajax({
				type: "POST",
				url: "API?"+requests,
				xhr: function () {
					var myXhr = $.ajaxSettings.xhr();
					if (myXhr.upload) {
						myXhr.upload.addEventListener('progress', that.progressHandling, false);
					}
					return myXhr;
				},
				success: function (data) {
					var status = data.split(':')[0];
					var file_url = data.split(':')[1];
					if(status.replace(/\s+/g, '') == 'success') {
						$('#'+holder).val(file_url);
					} else {
						swal("Oops!", data.split(':')[0], "warning");
					}
					$('#imp-button').show();
					$('#upload-spin').hide();
				},
				error: function (error) {
					var err = '<?=$LANG['Unable to upload your file']?>'+' '+error;
					swal("Oops!", err, "warning");
					$('#imp-button').show();
					$('#upload-spin').hide();
				},
				async: true,
				data: formData,
				cache: false,
				contentType: false,
				processData: false,
				timeout: 60000
			});
		};
		Upload.prototype.progressHandling = function (event) {
			var percent = 0;
			var position = event.loaded || event.position;
			var total = event.total;
			var progress_bar_id = "#progress-wrp";
			if (event.lengthComputable) {
				percent = Math.ceil(position / total * 100);
			}
			$(progress_bar_id).text(percent + "%");
		};
		//upload contact files
		$("#files").on("change", function (e) {
			var file = $(this)[0].files[0];
			var fileSize = file.size/1024;
			var max_upload = <?=getSetting('maxFileLimit',0)>0?getSetting('maxFileLimit',0)*1024:'3072'?>;
			if(fileSize > max_upload) {
				maxoad = Math.ceil(max_upload/1024)
				swal("Oops!", '<?=$LANG['Your file is too large. Please choose a file below']?> '+maxoad+' MB', "warning");
			} else {
				var upload = new Upload(file);
				upload.doUpload('files_holder','uploadfileCon');
			}
		});	
		
		//do actuall upload
		$('#imp-button').click(function(event) { 
			event.preventDefault();	  
			$('#imp-button').hide();
			$('#imp-spin').show();
			
			var formData = {
				'files'  :  $("#files_holder").val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?upload_customer',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['cuss_saved']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>'; 
					});
					$('#imp-button').show();
					$('#imp-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to complete action']?> '+status, "warning");
					$('#imp-button').show();
					$('#imp-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#imp-button').show();
				$('#imp-spin').hide();
			});
		});
		
		//Add credits
		$('#creditcus-button').click(function(event) { 
			event.preventDefault();	  
			$('#creditcus-button').hide();
			$('#creditcus-spin').show();
			
			var formData = {
				'credits'  :  $("#credits").val(),
				'password'  :  $("#passworda").val(),
				'customer_id'  :  $("#customer_id3").val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?credit_customer',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['credit_added']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL.'?v='.@$_GET['v']?>'; 
					});
					$('#creditcus-button').show();
					$('#creditcus-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to complete action']?> '+status, "warning");
					$('#creditcus-button').show();
					$('#creditcus-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#creditcus-button').show();
				$('#creditcus-spin').hide();
			});
		});
	<?php } ?>
	<?php if($URL=='rsetting' || $URL=='setting' || $URL=='paysetting' || $URL=='smsetting') { ?>
	  $('.js-states').select2({}).focus(function () { $(this).select2('focus'); });
	  if($('#billingModel').val() == 'unit') {
			$('#show_advancedUnitPricing').show();
		} else {
			$('#show_advancedUnitPricing').hide();
		}	
	  $('#billingModel').change(function(){
			if($('#billingModel').val() == 'unit') {
				$('#show_advancedUnitPricing').show();
			} else {
				$('#show_advancedUnitPricing').hide();
			}	
		});
		
	  $('#cus-button').click(function(event) { 
			event.preventDefault();	  
			$('#cus-button').hide();
			$('#cus-spin').show();
			var formData = {
				'businessName'  : $('#businessName').val(),
				'companyAddress'  : $('#companyAddress').val(),
				'companyEmail'  : $('#companyEmail').val(),
				'companyPhone'    : $('#companyPhone').val(),
				'companyWebsite'  : $('#companyWebsite').val(),
				'resellerDomain'  : $('#resellerDomain').val(),
				'invoiceSignature'  : $('#invoiceSignature').val(),
				'siteBackground'  : $('#siteBackground').val(),
				'siteLogo'    : $('#siteLogo').val(),
				'backgroundColor'  : $('#backgroundColor').val(),
				'headerColor'  : $('#headerColor').val(),
				'redirectToSite'  : $('#redirectToSite').val(),
				'billingModel'  : $('#billingModel').val(),
				'advancedUnitPricing'  : $('#advancedUnitPricing').val(),
				'taxAmount'  : $('#taxAmount').val(),
				'vatAmount'  : $('#vatAmount').val(),
				'smtpServer'    : $('#smtpServer').val(),
				'smtpUsername'  : $('#smtpUsername').val(),
				'smtpPassword'  : $('#smtpPassword').val(),
				'smtpPort'  : $('#smtpPort').val(),
				'smsSender' : $('#smsSender').val(),
				'smtpSecurity'  : $('#smtpSecurity').val(),
				'google_recaptcha_sitekey'  : $('#google_recaptcha_sitekey').val(),
				'google_recaptcha_secret'  : $('#google_recaptcha_secret').val(),
				'email_verify'  :  $('#email_verify').val(),
				'phone_verify'  : $('#phone_verify').val(),
				'disableUserRegistrationPage'  : $('#disableUserRegistrationPage').val(),
				
				<?php if(isAdmin(getUser())) { ?>					
					'stripAllSpecialCha'  :  $('#stripAllSpecialCha').val(),
                    'maxFileLimit'  :  $('#maxFileLimit').val(),
					'timeZone'  :  $('#timeZone').val(),
					'defaultSMSNoticeRoute'  :  $('#defaultSMSNoticeRoute').val(),
					'buycreditDisabled'  : $('#buycreditDisabled').val(),
					'phpErrorReporting'  : $('#phpErrorReporting').val(),
					'deleteOldBackup'  : $('#deleteOldBackup').val(),
					'deleteOldMessages'  : $('#deleteOldMessages').val(),
					'backupSettings'  : $('#backupSettings').val(),
					'senderIDLimit'  : $('#senderIDLimit').val(),
					'audioAlerts'  : $('#audioAlerts').val(),
					'defaultCurrency'  : $('#defaultCurrency').val(),
					'defaultCountry'  : $('#defaultCountry').val(),
					'facebook_secrete'    : $('#facebook_secrete').val(),
					'facebook_api'  : $('#facebook_api').val(),
					'affiliateEnabled'  : $('#affiliateEnabled').val(),
					'affiliatePayType'  : $('#affiliatePayType').val(),
					'affiliatePayValue'  : $('#affiliatePayValue').val(),
					'saleContactEnabled'  : $('#saleContactEnabled').val(),
					'dynamicSenderEnabled'  : $('#dynamicSenderEnabled').val(),
					'2wayEnabled'  : $('#2wayEnabled').val(),
					'voiceEnabled'  : $('#voiceEnabled').val(),
					'unicodeEnabled'  : $('#unicodeEnabled').val(),
					'MMSEnabled'  : $('#MMSEnabled').val(),
					'TextEnabled'  : $('#TextEnabled').val(),
					'watsappEnabled'  : $('#watsappEnabled').val(),
					'flashEnabled'  : $('#flashEnabled').val(),
					'sendRate'  : $('#sendRate').val(),
					'sendRealTime'  : $('#sendRealTime').val(),
					'defaultLanguage'  : $('#defaultLanguage').val(),
				<?php } ?>
				'save_settings':'ok',
				'user' : '<?=$userID?>'
			};
	
			$.ajax({
				type        : 'POST', 
				url         : 'API',
				data        : formData, 
				dataType    : 'json',
				encode      : true
			}).done(function(data) {
				if ( ! data.success) { 
					if (data.errors) {
						swal("Oops!", data.errors, "warning");
						$('#cus-button').show();
						$('#cus-spin').hide();
					}
				} else { 
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['Your changes have been saved']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){ 
						window.location = '<?=$URL?>?gen'; 
					});
				}
				}).fail(function (jqXHR,status,err) {
					swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
					$('#cus-button').show();
					$('#cus-spin').hide();
				});
		});		
		
		//noptifications
		$('#not-button').click(function(event) { 
			event.preventDefault();	  
			$('#not-button').hide();
			$('#not-spin').show();
			var formData = {
				'newAccountSMS'  : $('#newAccountSMS').val(),
				'newAccountEmail'  : $('#newAccountEmail').val(),
				'newPasswordSMS'  : $('#newPasswordSMS').val(),
				'newAccountEmailSubject'    : $('#newAccountEmailSubject').val(),
				'newPasswordEmailSubject'  : $('#newPasswordEmailSubject').val(),
				'newPasswordEmail'  : $('#newPasswordEmail').val(),
				'orderApproveEmailSubject'  : $('#orderApproveEmailSubject').val(),
				'orderApproveEmail'  : $('#orderApproveEmail').val(),
				'orderApproveSMS'    : $('#orderApproveSMS').val(),
				
				'newAccountVerifySMS'    : $('#newAccountVerifySMS').val(),
				'newAccountVerifyEmail'    : $('#newAccountVerifyEmail').val(),
				'newAccountVerifyEmailSubject'    : $('#newAccountVerifyEmailSubject').val(),
				'customerBDSMS'  : $('#customerBDSMS').val(),
				
				'save_settings':'ok',
				'user' : '<?=$userID?>'
			};
	
			$.ajax({
				type        : 'POST', 
				url         : 'API',
				data        : formData, 
				dataType    : 'json',
				encode      : true
			}).done(function(data) {
				if ( ! data.success) { 
					if (data.errors) {
						swal("Oops!", data.errors, "warning");
						$('#not-button').show();
						$('#not-spin').hide();
					}
				} else { 
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['Your changes have been saved']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){ 
						window.location = '<?=$URL?>?notic'; 
					});
				}
				}).fail(function (jqXHR,status,err) {
					swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
					$('#not-button').show();
					$('#not-spin').hide();
				});
		});		
		
		//alert old schools guys
		if(window.FormData === undefined){
			alert('sorry buddy you\'re browsers too old! You may not be able to use our portal om your current browser');
		}
		//upload from files
		Upload.prototype.doUpload = function (holder,requests) {
			$('#imp-button').hide();
			$('#upload-spin').show();
			var that = this;
			var formData = new FormData();
			formData.append("file", this.file, this.getName());
			formData.append("upload_file", true);
			$.ajax({
				type: "POST",
				url: "API?"+requests,
				xhr: function () {
					var myXhr = $.ajaxSettings.xhr();
					if (myXhr.upload) {
						myXhr.upload.addEventListener('progress', that.progressHandling, false);
					}
					return myXhr;
				},
				success: function (data) {
					var status = data.split(':')[0];
					var file_url = data.split(':')[1];
					if(status.replace(/\s+/g, '') == 'success') {
						$('#'+holder).val(file_url);
					} else {
						swal("Oops!", data.split(':')[0], "warning");
					}
					$('#imp-button').show();
					$('#upload-spin').hide();
				},
				error: function (error) {
					var err = '<?=$LANG['Unable to upload your file']?>'+' '+error;
					swal("Oops!", err, "warning");
					$('#imp-button').show();
					$('#upload-spin').hide();
				},
				async: true,
				data: formData,
				cache: false,
				contentType: false,
				processData: false,
				timeout: 60000
			});
		};
		Upload.prototype.progressHandling = function (event) {
			var percent = 0;
			var position = event.loaded || event.position;
			var total = event.total;
			var progress_bar_id = "#progress-wrp";
			if (event.lengthComputable) {
				percent = Math.ceil(position / total * 100);
			}
			$(progress_bar_id).text(percent + "%");
		};
		//upload background
		$("#files_back").on("change", function (e) {
			var file = $(this)[0].files[0];
			var upload = new Upload(file);
			upload.doUpload('siteBackground','uploadfileMM');
		});	
		//upload logo
		$("#files_logo").on("change", function (e) {
			var file = $(this)[0].files[0];
			var upload = new Upload(file);
			upload.doUpload('siteLogo','uploadfileMM');
		});	
		//upload Signature
		$("#files_sign").on("change", function (e) {
			var file = $(this)[0].files[0];
			var upload = new Upload(file);
			upload.doUpload('invoiceSignature','uploadfileMM');
		});	
		//upload rates
		$("#files_raten").on("change", function (e) {
			var file = $(this)[0].files[0];
			var upload = new Upload(file);
			upload.doUpload('files_holderR','uploadfileCon');
		});	
		
		//Upload SMS RaTES
		$('#impr-button').click(function(event) { 
			event.preventDefault();	  
			$('#impr-button').hide();
			$('#impr-spin').show();
			
			var formData = {
				'files'  :  $("#files_holderR").val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?upload_rates',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['cuss_saved']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>?rate'; 
					});
					$('#impr-button').show();
					$('#impr-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to complete action']?> '+status, "warning");
					$('#impr-button').show();
					$('#impr-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");

				$('#impr-button').show();
				$('#impr-spin').hide();
			});
		});
		
		//togle sms plan
		$('#sch_swit').click(function() {
			if($('#useSMSPackage').is(":checked")){
				var formData = { 'save_settings':'ok',	'useSMSPackage'  : '1', 'user' : '<?=$userID?>' };
				$.ajax({
					type        : 'POST', 
					url         : 'API',
					data        : formData, 
					dataType    : 'json',
					encode      : true
				}).done(function(data) {
					if ( ! data.success) { 
						if (data.errors) {
							swal("Oops!", data.errors, "warning");
						}
					} else { 
						swal("<?=$LANG['Done']?>!", "<?=$LANG['Your changes have been saved']?>", "success");
					}
				}).fail(function (jqXHR,status,err) {
					swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				});
			} else {
				var formData = { 'save_settings':'ok', 	'useSMSPackage'  : '0', 'user' : '<?=$userID?>' };
				$.ajax({
					type        : 'POST', 
					url         : 'API',
					data        : formData, 
					dataType    : 'json',
					encode      : true
				}).done(function(data) {
					if ( ! data.success) { 
						if (data.errors) {
							swal("Oops!", data.errors, "warning");
						}
					} else { 
						swal("<?=$LANG['Done']?>!", "<?=$LANG['Your changes have been saved']?>", "success");
					}
				}).fail(function (jqXHR,status,err) {
					swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				});
			}
		});
		
		//togle sms voucher
		$('#sch_swit2').click(function() {
			if($('#useSMSVoucher').is(":checked")){
				var formData = { 'save_settings':'ok',	'useSMSVoucher'  : '1', 'user' : '<?=$userID?>' };
				$.ajax({
					type        : 'POST', 
					url         : 'API',
					data        : formData, 
					dataType    : 'json',
					encode      : true
				}).done(function(data) {
					if ( ! data.success) { 
						if (data.errors) {
							swal("Oops!", data.errors, "warning");
						}
					} else { 
						swal("<?=$LANG['Done']?>!", "<?=$LANG['Your changes have been saved']?>", "success");
					}
				}).fail(function (jqXHR,status,err) {
					swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				});
			} else {
				var formData = { 'save_settings':'ok',	'useSMSVoucher'  : '0', 'user' : '<?=$userID?>' };
				$.ajax({
					type        : 'POST', 
					url         : 'API',
					data        : formData, 
					dataType    : 'json',
					encode      : true
				}).done(function(data) {
					if ( ! data.success) { 
						if (data.errors) {
							swal("Oops!", data.errors, "warning");
						}
					} else { 
						swal("<?=$LANG['Done']?>!", "<?=$LANG['Your changes have been saved']?>", "success");
					}
				}).fail(function (jqXHR,status,err) {
					swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				});
			}
		});
		//Add voucher
		$('#vouch-button').click(function(event) { 
			event.preventDefault();	  
			$('#vouch-button').hide();
			$('#vouch-spin').show();
			
			var formData = {
				'validity'  :  $("#validity").val(),
				'cost'  :  $("#cost").val(),
				'credit'  :  $("#credit").val(),
				'quantity'  :  $("#quantity").val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?add_voucher',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['Your changes have been saved']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>?vouc'; 
					});
					$('#vouch-button').show();
					$('#vouch-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to complete action']?> '+status, "warning");
					$('#vouch-button').show();
					$('#vouch-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#vouch-button').show();
				$('#vouch-spin').hide();
			});
		});
		//Add Plan
		$('#plan-button').click(function(event) { 
			event.preventDefault();	  
			$('#plan-button').hide();
			$('#plan-spin').show();
			
			var formData = {
				'validity'  :  $("#validity2").val(),
				'cost'  :  $("#cost2").val(),
				'credit'  :  $("#credit2").val(),
				'name'  :  $("#name").val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?add_plan',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['Your changes have been saved']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>?pack'; 
					});
					$('#plan-button').show();
					$('#plan-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to complete action']?> '+status, "warning");
					$('#plan-button').show();
					$('#plan-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#plan-button').show();
				$('#plan-spin').hide();
			});
		});
		
		//Add rate
		$('#rate-button').click(function(event) { 
			event.preventDefault();	  
			$('#rate-button').hide();
			$('#rate-spin').show();
			
			var formData = {
				'customer'  :  $("#customer_id2").val(),
				'country'  :  $("#country_code").val(),
				'operator'  :  $("#operator_code").val(),
				'gateway'  :  $("#gateway").val(),
				'type'  :  $("#type").val(),
				'rate'  :  $("#rate").val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?add_rate',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['Your changes have been saved']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>?rate'; 
					});
					$('#rate-button').show();
					$('#rate-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to complete action']?> '+status, "warning");
					$('#rate-button').show();
					$('#rate-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#rate-button').show();
				$('#rate-spin').hide();
			});
		});
		
		//add route
		$('#route-button').click(function(event) { 
			event.preventDefault();	  
			$('#route-button').hide();
			$('#route-spin').show();
			
			var formData = {
				'customer_id'  :  $("#customer_id").val(),
				'country'  :  $("#country_code").val(),
				'operator'  :  $("#operator_code").val(),
				'gateway_id'  :  $("#gateway_id").val(),
				'group_id'  :  $("#group_id").val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?add_route',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['Your changes have been saved']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>?rout'; 
					});
					$('#route-button').show();
					$('#route-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to complete action']?> '+status, "warning");
					$('#route-button').show();
					$('#route-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#route-button').show();
				$('#route-spin').hide();
			});
		});
		
		<?php if(!isset($_GET['gwid'])) { ?>
			//reset all 
			$('#param1_field').val('');
			$('#param2_field').val('');
			$('#param3_field').val('');
			$('#param4_field').val('');
			$('#param1_value').val('');
			$('#param2_value').val('');
			$('#param3_value').val('');
			$('#param4_value').val('');
			$('.show-custom').hide();
			$('.show-unicode').hide();
			$('.show-smpp').hide();
			$('.hide-2way').hide();
			$('.show-auth').hide();
			$('.show-voice').hide();
			$('.show-mms').hide();
			$('.show-post').hide();
			$('.show_p1').hide();
			$('.show_p2').hide();
			$('.show_p3').hide();
			$('.show_p4').hide();
			$('.basic_params').hide();
			$('.gat_disname').hide();
		<?php } ?>		
		//show JSON
		$('#request_type').change(function(){
			if($('#request_type').val() == 'GET') {
				$('.show-post').hide();
			} else {
				$('.show-post').show();
			}	
		});
		
		//show Auths
		$('#authentication').change(function(){
			if($('#authentication').val() == '0') {
				$('.show-auth').hide();
			} else {
				$('.show-auth').show();
			}	
		});
		$('#cusType').change(function(){
			if($('#cusType').val() == 'voice') {
				$('.show-unicode').hide();
				$('.show-voice').show();
			} else {
				$('.show-voice').hide();
				if($('#cusType').val() == 'mms') {
					$('.show-mms').show();
				}
			}
			if($('#cusType').val() == 'mms') {
				$('.show-mms').show();
				$('.show-unicode').hide();
			} else {
				if($('#cusType').val() != 'voice') {
					$('.show-mms').hide();
				}
			}
			if($('#cusType').val() == 'unicode') {
				$('.show-unicode').show();
			} else {
				$('.show-unicode').hide();
			}
			if($('#cusType').val() == '2way') {
				$('.show-unicode').show();
				$('.hide-2way').hide();
				$('.show-2way').show();
			} else {
				$('.hide-2way').show();
				$('.show-2way').hide();
			}
		});
		
		//Load SMS Gateway settings
		$('#alias').change(function(){
			$('.gat_disname').show();
			$('#param1_field').val('');
			$('#param2_field').val('');
			$('#param3_field').val('');
			$('#param4_field').val('');
			$('#param1_value').val('');
			$('#param2_value').val('');
			$('#param3_value').val('');
			$('#param4_value').val('');
			$('.show-custom').hide();
			$('.show-unicode').hide();
			$('.show-smpp').hide();
			$('.hide-2way').hide();
			$('.show-auth').hide();
			$('.show-voice').hide();
			$('.show-mms').hide();
			$('.show-post').hide();
			$('.show_p1').hide();
			$('.show_p2').hide();
			$('.show_p3').hide();
			$('.show_p4').hide();


			var aka = $('#alias').val();
			if(aka > 0) { 
				$.ajax({url: "API?load_sms_gateway_temp="+aka, success: function(result){ 
				var result = JSON.parse(result);
					$('.show-unicode').hide();
					 $('.show-custom').hide();
					$('#sgtype').val(result.type);
					if(result.alias == 'custom') {
						$('.show-custom').show();
						$('.no_change').show();
						$('.basic_params').show();
						$('.show-unicode').hide();
					} else {
                    	$('.show-custom').hide();
					    $('.show-mms').hide();
                         $('.no_change').hide();
                         $('.basic_params').hide();                    
                    	if(result.alias == 'smpp') {
                            $('.show-smpp').show();
                            $('.basic_params').show();
                        } else {
                            $('.show-smpp').hide();
                            $('.show-custom').hide();
                        }
					}
					
					if(result.type == 'voice') {
						$('.show-voice').show();
					} else {
						$('.show-voice').hide();
						if(result.type == 'mms') {
							$('.show-mms').show();
						}
					}
					if(result.type == 'mms') {
						$('.show-mms').show();
					} else {
						if(result.type != 'voice') {
							$('.show-mms').hide();
						}
					}
					if(result.type == 'unicode') {
						$('.show-unicode').show();
					} else {
						$('.show-unicode').hide();
					}
					if(result.type == '2way') {
						$('.hide-2way').hide();
						$('.show-2way').show();
						$('.basic_params').show();
					} else {
					    $('.hide-2way').show();
						$('.show-2way').hide();
					}
					if(result.alias != 'custom') {
						if(result.authentication == '0') {
							$('.show-auth').hide();
						} else {
							$('.show-auth').show();
						}
					} else {
						$('.show-auth').hide();	
					}
					if(result.alias != 'custom') {
						$('.no_change').hide();
						$('.show-mms').hide();
						$('.show-voice').hide();
						if(result.param1_label != '') {
							$('.show_p1').show();
							$('#label_p1').text(result.param1_label);
							$('#param1_value').val(result.param1_value);
						} else {
							$('.show_p1').hide(); 
						}
						if(result.param2_label != '') {
							$('.show_p2').show();
							$('#label_p2').text(result.param2_label);
							$('#param2_value').val(result.param2_value);
						} else {
							$('.show_p2').hide();
						}
						if(result.param3_label != '') {
							$('.show_p3').show();
							$('#label_p3').text(result.param3_label);
							$('#param3_value').val(result.param3_value);
						} else {
							$('.show_p3').hide();
						}
						if(result.param3_label != '') {
							$('.show_p4').show();
							$('#label_p4').text(result.param4_label);
							$('#param4_value').val(result.param4_value);
						} else {
							$('.show_p4').hide();
						}
						$('#request_type').val(result.request_type);
						
					} else {
						$('.show_p1').show();
						$('#label_p1').text('<?=$LANG['Parameter 1 Value']?>');
						$('.show_p2').show();
						$('#label_p2').text('<?=$LANG['Parameter 2 Value']?>');
						$('.show_p3').show();
						$('#label_p3').text('<?=$LANG['Parameter 3 Value']?>');
						$('.show_p4').show();
						$('#label_p4').text('<?=$LANG['Parameter 4 Value']?>');
						$('#param1_value').val(result.param1_value);
						$('#param2_value').val(result.param2_value);
						$('#param3_value').val(result.param3_value);
						$('#param4_value').val(result.param4_value);
						$('#param1_field').val(result.param1_field);
						$('#param2_field').val(result.param2_field);
						$('#param3_field').val(result.param3_field);
						$('#param4_field').val(result.param4_field);
					}
					setup_text = result.setup_text;
					if(setup_text != '') {
						$('.show-text').show();
						$('#setup_text').html(setup_text);
					} else {
						$('.show-text').hide();	
					}
					$('#cusType').val(result.type);
					$('#base_url').val(result.base_url);
					$('#success_word').val(result.success_word);
					$('#success_logic').val(result.success_logic);
					$('#authentication').val(result.authentication);
					$('#username').val(result.username);
					$('#password').val(result.password);
					$('#sender_field').val(result.sender_field);
					$('#recipient_field').val(result.recipient_field);
					$('#message_field').val(result.message_field);
					$('#audio_field').val(result.audio_field);
					
					$('#language_field').val(result.language_field);
					$('#timeout_field').val(result.timeout_field);
					$('#json_encode').val(result.json_encode);
					$('#base64_encode').val(result.base64_encode);
					$('#unicode_encode').val(result.unicode_encode);
					$('#sgtype').val(result.type); 
					$('#alias').select2('focus');
					$('#alias').select2('open').select2('close');
					//$('.show-unicode').hide();
				}});
			}
			//show JSON
			$('#request_type').change(function(){
				if($('#request_type').val() == 'GET') {
					$('.show-post').hide();
				} else {
					$('.show-post').show();
				}	
			});
			
		});
		
		//Add sms gateway
		$('#sgate-button').click(function(event) { 
			event.preventDefault();	  
			$('#sgate-button').hide();
			$('#sgate-spin').show();
			
			var formData = {
				'param1_value' : $('#param1_value').val(),
				'param2_value' : $('#param2_value').val(),
				'param3_value' : $('#param3_value').val(),
				'param4_value' : $('#param4_value').val(),
				'param1_field' : $('#param1_field').val(),
				'param2_field' : $('#param2_field').val(),
				'param3_field' : $('#param3_field').val(),
				'param4_field' : $('#param4_field').val(),
				'request_type' : $('#request_type').val(),
				'balance_url'  : $('#balance_url').val(),
				'base_url' : $('#base_url').val(),
				'success_word' : $('#success_word').val(),
				'success_logic' : $('#success_logic').val(),
				'authentication' : $('#authentication').val(),
				'username' : $('#username').val(),
				'password' : $('#password').val(),
				'sender_field' : $('#sender_field').val(),
				'recipient_field' : $('#recipient_field').val(),
				'message_field' : $('#message_field').val(),
				'audio_field' : $('#audio_field').val(),
				
				'language_field' : $('#language_field').val(),
				'timeout_field' : $('#timeout_field').val(),
				'json_encode' : $('#json_encode').val(),
				'base64_encode' : $('#base64_encode').val(),
				'unicode_encode' : $('#unicode_encode').val(),
				'type' : $('#sgtype').val(),
				'cusType' : $('#cusType').val(),
				'alias'  :  $("#alias").val(),
				'cutting_limit' : $('#cutting_limit').val(),
				'cutting_percent'  :  $("#cutting_percent").val(),
				'hour_limit' : $('#hour_limit').val(),
				'title'  :  $("#sgtitle").val(),
				'gateway_id'  :  $("#sgateway_id").val(),
				'group_id2'  :  $("#group_id2").val(),
				'd_rate' : $("#d_rate").val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?add_sms_gateway',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['Your changes have been saved']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>?sms'; 
					});
					$('#sgate-button').show();
					$('#sgate-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to complete action']?> '+status, "warning");
					$('#sgate-button').show();
					$('#sgate-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#sgate-button').show();
				$('#sgate-spin').hide();
			});
		});
		//change  message type
		$('#cusType').change(function(){
			var type = $('#cusType').val();
					if(type == 'voice') {
						$('.show-voice').show();
					} else {
						$('.show-voice').hide();
						if(type == 'mms' || type == 'whatsapp') {
							$('.show-mms').show();
						}
					}
					if(type == 'mms' || type == 'whatsapp') {
						$('.show-mms').show();
					} else {
						if(type != 'voice') {
							$('.show-mms').hide();
						}
					}
					if(type == 'unicode') {
						$('.show-unicode').show();
					} else {
						$('.show-unicode').hide();
					}
					if(type == '2way') {
						$('.hide-2way').hide();
						$('.show-2way').show();
					} else {
						$('.show-2way').hide();
						$('.hide-2way').show();
					}
		});
		//load gateway settings
		$('#gtype').change(function(){
			$('#param1').val('');
			$('#param2').val('');
			$('#param3').val('');
			$('#show_p1').hide();
			$('#show_p2').hide();
			$('#show_p3').hide();
			var aka = $('#gtype').val();
			//$('#gtitle').val(aka);
			if(aka.length > 1) { 
				$.ajax({url: "API?load_pay_gateway_temp="+aka, success: function(result){
					var param1 = result.split(':')[0];					
					var param2 = result.split(':')[1]
					var param3 = result.split(':')[2]
					if(param1.length > 1) {
						$('#label_p1').text(param1);
						$('#show_p1').show();
					} else {
						$('#param1').val('');
						$('#show_p1').hide();
					}
					if(param2.length > 1) {
						$('#label_p2').text(param2);
						$('#show_p2').show();
					} else {
						$('#param2').val('');
						$('#show_p2').hide();
					}
					if(param3.length > 1) {
						$('#label_p3').text(param3);
						$('#show_p3').show();
					} else {
						$('#param3').val('');
						$('#show_p3').hide();
					}
					if(aka=='custom') {
						$('#show_p1').hide();
						$('#show_p2').hide();
						$('#show_p3').hide();
					}
				}});
			}
		});
		
		//load gateway settings
		$('#charge_type').change(function(){
			$('#charges_perc').val('0.00');
			$('#charges_fix').val('0.00');
			$('#hide_fix').hide();
			$('#hide_pec').hide();
			var aka = $('#charge_type').val();
			if(aka.length > 1) { 
				if(aka == 'percent') {
					$('#hide_pec').hide();
				} else {
					$('#hide_pec').show();
				}
				if(aka == 'fixed') {
					$('#hide_fix').hide();
				} else {
					$('#hide_fix').show();
				}
			}
		});
		//Add payment gateway
		$('#gate-button').click(function(event) { 
			event.preventDefault();	  
			$('#gate-button').hide();
			$('#gate-spin').show();
			
			var formData = {
				'gtype'  :  $("#gtype").val(),
				'gtitle'  :  $("#gtitle").val(),
				'param1'  :  $("#param1").val(),
				'param2'  :  $("#param2").val(),
				'param3'  :  $("#param3").val(),
				'minimum_order'  :  $("#minimum_order").val(),
				'charge_type'  :  $("#charge_type").val(),
				'charges_perc'  :  $("#charges_perc").val(),
				'charges_fix'  :  $("#charges_fix").val(),
				'text'  :  $("#text").val(),
				'genabled'  :  $("#genabled").val(),
				'gateway_id'  :  $("#gateway_id").val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?add_gateway',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['Your changes have been saved']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>?pay'; 
					});
					$('#gate-button').show();
					$('#gate-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to complete action']?> '+status, "warning");
					$('#gate-button').show();
					$('#gate-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#gate-button').show();
				$('#gate-spin').hide();
			});
		});
		
		<?php if($URL != 'smsetting' && $URL != 'paysetting') { ?>
		jQuery.fn.extend({
				toggleText: function (a, b){
					var that = this;
					if (that.text() != a && that.text() != b){
						that.text(a);
					}
					else
						if (that.text() == a){
							that.text(b);
						}
					else
						if (that.text() == b){
							that.text(a);
						}
					return this;
				}
			});
			var editor = new Simditor({
				textarea: $('#newAccountEmail'),
				placeholder: '<?=$LANG['New Account Welcome Email']?> <?=$LANG['Body']?>',
				toolbar: [ 'bold','italic', 'underline', 'strikethrough', 'ol', 'link', 'ul', 'blockquote', 'code' ]
			});
			var editor = new Simditor({
				textarea: $('#newAccountVerifyEmail'),
				placeholder: '<?=$LANG['Account Verification Email']?> <?=$LANG['Body']?>',
				toolbar: [ 'bold','italic', 'underline', 'strikethrough', 'ol', 'link', 'ul', 'blockquote', 'code' ]
			});
			var editor = new Simditor({
				textarea: $('#newPasswordEmail'),
				placeholder: '<?=$LANG['Password Reset Email']?> <?=$LANG['Body']?>',
				toolbar: [ 'bold','italic', 'underline', 'strikethrough', 'ol', 'link', 'ul', 'blockquote', 'code' ]
			});
			var editor = new Simditor({
				textarea: $('#orderApproveEmail'),
				placeholder: '<?=$LANG['Order Confirmation Email']?> <?=$LANG['Body']?>',
				toolbar: [ 'bold','italic', 'underline', 'strikethrough', 'ol', 'link', 'ul', 'blockquote', 'code' ]
			});
		<?php } ?>	
	<?php } ?>
	<?php if($URL=='profile' || $URL=='aprofile' || ($URL=='user' && isset($_GET['v']))) { ?>
	<?php if($URL!='user') { ?>
		$('#country').select2(); 
		<?php if($URL!='aprofile') { ?>
		$('#currency').select2();
		<?php } ?>
	
	<?php } ?>

		<?php if(isset($_GET['setting'])) { 
			echo 'swal("Attention!", "'.$LANG['Your account information is incomplete! Please update your profile before you continue.'].'", "warning");';
		}
		?>
	  $('#cus-button').click(function(event) { 
			event.preventDefault();	  
			$('#cus-button').hide();
			$('#cus-spin').show();
			var formData = {
				'customer_id'  : $('#customer_id').val(),
				'first_name'  : $('#fname').val(),
				'last_name'  : $('#lname').val(),
				'email'    : $('#email').val(),
				'phone'  : $('#phone').val(),
				'country_id'  : $('#country').val(),
				'password'  : $('#password').val(),
				'currency_id'  : $('#currency').val(),
				'language_id'  : $('#language_id').val(),
				'default_sender_ID' : $('#default_sender_ID').val(),
				'address'  : $('#address').val(),
				'birthday'  : $('#birthday').val(),
				'city'  : $('#city').val(),
				'role_id'  : $('#role_id').val(),
				'state'  : $('#state').val(),
				'photo'  : $('#photo').val(),
				<?php if($URL=='profile') { ?>
				//Do Custom Fields
				<?php $reseller = resellerByDomain() ?>
				<?=loadCustomFormFields($reseller,$userID,0) ?>
				<?php } ?> 
				'update_profile'	: '1',
				'user' : '<?=$userID?>'
			};
	
			$.ajax({
				type        : 'POST', 
				url         : 'API',
				data        : formData, 
				dataType    : 'json',
				encode      : true
			}).done(function(data) {
				if ( ! data.success) { 
					if (data.errors) {
						swal("Oops!", data.errors, "warning");
						$('#cus-button').show();
						$('#cus-spin').hide();
					}
				} else { 
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['profile_saved']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){ 
						window.location = '<?=$URL?>'; 
					});
				}
				}).fail(function (jqXHR,status,err) {
					swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
					$('#cus-button').show();
					$('#cus-spin').hide();
				});
		});		
		
		//alert old schools guys
		if(window.FormData === undefined){
			alert('sorry buddy you\'re browsers too old! You may not be able to use our portal om your current browser');
		}
		//upload from files
		Upload.prototype.doUpload = function (holder,requests) {
			$('#cus-button').hide();
			$('#upload-spin').show();
			var that = this;
			var formData = new FormData();
			formData.append("file", this.file, this.getName());
			formData.append("upload_file", true);
			$.ajax({
				type: "POST",
				url: "API?"+requests,
				xhr: function () {
					var myXhr = $.ajaxSettings.xhr();
					if (myXhr.upload) {
						myXhr.upload.addEventListener('progress', that.progressHandling, false);
					}
					return myXhr;
				},
				success: function (data) {
					var status = data.split(':')[0];
					var file_url = data.split(':')[1];
					if(status.replace(/\s+/g, '') == 'success') {
						$('#'+holder).val(file_url);
					} else {
						swal("Oops!", data.split(':')[0], "warning");
					}
					$('#cus-button').show();
					$('#upload-spin').hide();
				},
				error: function (error) {
					var err = '<?=$LANG['Unable to upload your file']?>'+' '+error;
					swal("Oops!", err, "warning");
					$('#cus-button').show();
					$('#upload-spin').hide();
				},
				async: true,
				data: formData,
				cache: false,
				contentType: false,
				processData: false,
				timeout: 60000
			});
		};
		Upload.prototype.progressHandling = function (event) {
			var percent = 0;
			var position = event.loaded || event.position;
			var total = event.total;
			var progress_bar_id = "#progress-wrp";
			if (event.lengthComputable) {
				percent = Math.ceil(position / total * 100);
			}
			$(progress_bar_id).text(percent + "%");
		};
		//upload contact files
		$("#files").on("change", function (e) {
			var file = $(this)[0].files[0];
			var fileSize = file.size/1024;
			var max_upload = <?=getSetting('maxFileLimit',0)>0?getSetting('maxFileLimit',0)*1024:'3072'?>;
			if(fileSize > max_upload) {
				maxoad = Math.ceil(max_upload/1024)
				swal("Oops!", '<?=$LANG['Your file is too large. Please choose a file below']?> '+maxoad+' MB', "warning");
			} else {
				var upload = new Upload(file);
				upload.doUpload('photo','uploadfileMM');
			}
		});	
	<?php } ?>	
	
	<?php if($URL == 'abanned') {?>	
		$('#country').select2();
	
		$('#isave-button').click(function(event) { 
			event.preventDefault();	  
			$('#isave-button').hide();
			$('#isave-spin').show();
			
			var formData = {
				'ip'  :  $("#ip").val(),
				'reason'  :  $("#ireason").val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?add_banned',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['Your changes have been saved']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>?i'; 
					});
					$('#isave-button').show();
					$('#isave-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to complete action']?> '+status, "warning");
					$('#isave-button').show();
					$('#isave-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#isave-button').show();
				$('#isave-spin').hide();
			});
		});
		//country
		$('#csave-button').click(function(event) { 
			event.preventDefault();	  
			$('#csave-button').hide();
			$('#csave-spin').show();
			
			var formData = {
				'country'  :  $("#country").val(),
				'reason'  :  $("#creason").val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?add_banned',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['Your changes have been saved']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>?c'; 
					});
					$('#csave-button').show();
					$('#csave-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to complete action']?> '+status, "warning");
					$('#csave-button').show();
					$('#csave-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#csave-button').show();
				$('#csave-spin').hide();
			});
		});
		//Word
		$('#wsave-button').click(function(event) { 
			event.preventDefault();	  
			$('#wsave-button').hide();
			$('#wsave-spin').show();
			
			var formData = {
				'word'  :  $("#word").val(),
				'reason'  :  $("#wreason").val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?add_banned',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['Your changes have been saved']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>?w'; 
					});
					$('#wsave-button').show();
					$('#wsave-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to complete action']?> '+status, "warning");
					$('#wsave-button').show();
					$('#wsave-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#wsave-button').show();
				$('#wsave-spin').hide();
			});
		});
		//Email
		$('#esave-button').click(function(event) { 
			event.preventDefault();	  
			$('#esave-button').hide();
			$('#esave-spin').show();
			
			var formData = {
				'email'  :  $("#email").val(),
				'reason'  :  $("#ereason").val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?add_banned',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['Your changes have been saved']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>?e'; 
					});
					$('#esave-button').show();
					$('#esave-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to complete action']?> '+status, "warning");
					$('#esave-button').show();
					$('#esave-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#esave-button').show();
				$('#esave-spin').hide();
			});
		});
		//sender
		$('#ssave-button').click(function(event) { 
			event.preventDefault();	  
			$('#ssave-button').hide();
			$('#ssave-spin').show();
			
			var formData = {
				'sender'  :  $("#sender").val(),
				'reason'  :  $("#sreason").val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?add_banned',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['Your changes have been saved']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>?s'; 
					});
					$('#ssave-button').show();
					$('#ssave-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to complete action']?> '+status, "warning");
					$('#ssave-button').show();
					$('#ssave-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#ssave-button').show();
				$('#ssave-spin').hide();
			});
		});
	<?php } ?>
	<?php if(userRole()<2) {?>
	//System Update stuffs... very important
	<?php if(($URL=='info'||$URL=='dashboard')&&!empty(systemInformation())) {?>
		swal({   
			title: "Notice!",  
			text:  '<?=str_replace("'","\'",trim(preg_replace('/\s+/',' ',systemInformation())))?>',
			type: "info",
			html: true 
		});
	<?php } ?>	
	<?php if($URL=='info'||$URL=='dashboard') { autoUpdate();isOutdated();  } ?>	
	<?php } ?>
	<?php if($URL=='amodule') {?>
	$('#mod-button').click(function(event) { 
			event.preventDefault();	  
			$('#mod-button').hide();
			$('#mod-spin').show();
			var formData = {
				'module'  : $('#files_holder').val(),
				'user' : '<?=$userID?>'
			};
	
			$.ajax({
				type        : 'POST', 
				url         : 'API?install_module',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['Your changes have been saved']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>'; 
					});
					$('#mod-button').show();
					$('#mod-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to complete action']?> '+status, "warning");
					$('#mod-button').show();
					$('#mod-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#mod-button').show();
				$('#mod-spin').hide();
			});
		});
		
		//alert old schools guys
		if(window.FormData === undefined){
			alert('sorry buddy you\'re browsers too old! You may not be able to use our portal om your current browser');
		}
		//upload from files
		Upload.prototype.doUpload = function (holder,requests) {
			$('#mod-button').hide();
			$('#upload-spin').show();
			var that = this;
			var formData = new FormData();
			formData.append("file", this.file, this.getName());
			formData.append("upload_file", true);
			$.ajax({
				type: "POST",
				url: "API?"+requests,
				xhr: function () {
					var myXhr = $.ajaxSettings.xhr();
					if (myXhr.upload) {
						myXhr.upload.addEventListener('progress', that.progressHandling, false);
					}
					return myXhr;
				},
				success: function (data) {
					var status = data.split(':')[0];
					var file_url = data.split(':')[1];
					if(status.replace(/\s+/g, '') == 'success') {
						$('#'+holder).val(file_url);
					} else {
						swal("Oops!", data.split(':')[0], "warning");
					}
					$('#mod-button').show();
					$('#upload-spin').hide();
				},
				error: function (error) {
					var err = '<?=$LANG['Unable to upload your file']?>'+' '+error;
					swal("Oops!", err, "warning");
					$('#mod-button').show();
					$('#upload-spin').hide();
				},
				async: true,
				data: formData,
				cache: false,
				contentType: false,
				processData: false,
				timeout: 60000
			});
		};
		Upload.prototype.progressHandling = function (event) {
			var percent = 0;
			var position = event.loaded || event.position;
			var total = event.total;
			var progress_bar_id = "#progress-wrp";
			if (event.lengthComputable) {
				percent = Math.ceil(position / total * 100);
			}
			$(progress_bar_id).text(percent + "%");
		};
		//upload contact files
		$("#files").on("change", function (e) {
			var file = $(this)[0].files[0];
			var fileSize = file.size/1024;
			var max_upload = <?=getSetting('maxFileLimit',0)>0?getSetting('maxFileLimit',0)*1024:'3072'?>;
			if(fileSize > max_upload) {
				maxoad = Math.ceil(max_upload/1024)
				swal("Oops!", '<?=$LANG['Your file is too large. Please choose a file below']?> '+maxoad+' MB', "warning");
			} else {
				var upload = new Upload(file);
				upload.doUpload('files_holder','uploadfileZIP');
			}
		});	
	
	<?php }?>
	
	<?php if($URL=='currency') { ?>
		//add currency
		$('#curren-button').click(function(event) { 
			event.preventDefault();	  
			$('#curren-button').hide();
			$('#route-spin').show();
			
			var formData = {
				'title'  :  $("#title").val(),
				'code'  :  $("#code").val(),
				'symbul'  :  $("#symbul").val(),
				'rate'  :  $("#rate").val(),
				'zeros'  :  $("#zeros").val(),
				'currency_id'  :  $("#currency_id").val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?add_currency',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['Your changes have been saved']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>'; 
					});
					$('#curren-button').show();
					$('#curren-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to complete action']?> '+status, "warning");
					$('#curren-button').show();
					$('#curren-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#curren-button').show();
				$('#curren-spin').hide();
			});
		});
	<?php } ?>
	<?php if($URL=='info') { ?>
		$('#lic-button').click(function(event) { 
			event.preventDefault();	  
			$('#lic-button').hide();
			$('#lic-spin').show();
			
			var formData = {
				'license'  :  $("#license").val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?update_license',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['Your new license has been applied']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>'; 
					});
					$('#lic-button').show();
					$('#lic-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to complete action']?> '+status, "warning");
					$('#lic-button').show();
					$('#lic-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#lic-button').show();
				$('#lic-spin').hide();
			});
		});
	<?php } ?>
	
	<?php if($URL=='pushnotice') { ?>
			jQuery.fn.extend({
				toggleText: function (a, b){
					var that = this;
					if (that.text() != a && that.text() != b){
						that.text(a);
					}
					else
						if (that.text() == a){
							that.text(b);
						}
					else
						if (that.text() == b){
							that.text(a);
						}
					return this;
				}
			});
			var editor = new Simditor({
				textarea: $('#pushMessage'),
				toolbar: [
				  'title',
				  'bold',
				  'italic',
				  'underline',
				  'strikethrough',
				  'fontScale',
				  'color',
				  'ol',            
				  'ul',            
				  'blockquote',
				  'code',        
				  'table',
				  'link',
				  'image',
				  'hr',            
				  'indent',
				  'outdent',
				  'alignment'
				]
			});
	
		$('#push-button').click(function(event) { 
			event.preventDefault();	  
			$('#push-button').hide();
			$('#push-spin').show();
			
			var formData = {
				'pushTitle'  :  $("#pushTitle").val(),
				'pushFor'  :  $("#pushFor").val(),
				'pushPages'  :  $("#pushPages").val(),
				'pushMessage'  :  $("#pushMessage").val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?update_push',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['Your changes has been applied']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>'; 
					});
					$('#push-button').show();
					$('#push-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to complete action']?> '+status, "warning");
					$('#push-button').show();
					$('#push-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#push-button').show();
				$('#push-spin').hide();
			});
		});
	<?php } ?>

	<?php if($URL=='customfields') { ?>
		//strat chat
		$('#customf-button').click(function(event) { 
			event.preventDefault();	  
			$('#customf-button').hide();
			$('#customf-spin').show();
			
			var formData = {
				'customfield_id'  :  $("#customfield_id").val(),
				'field_type'  :  $("#field_type").val(),
				'name'  :  $("#name").val(),
				'required'  :  $("#required").val(),
				'show_form'  :  $("#show_form").val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?add_customfields',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['The new custom field has been saved']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>'; 
					});
				} else {
					swal("Oops!", '<?=$LANG['Unable to complete action']?> '+status, "warning");
					$('#customf-button').show();
					$('#customf-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#customf-button').show();
				$('#customf-spin').hide();
			});
		});
	<?php } ?>		
	
	<?php if($URL=='smschat') { ?>

		//strat chat
		$('#start-button').click(function(event) { 
			event.preventDefault();	  
			$('#start-button').hide();
			$('#start-spin').show();
			
			var formData = {
				'receiver'  :  $("#receiver").val(),
				'sender'  :  $("#sender").val(),
				'message'  :  $("#message").val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?post_sms_chat',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					//add number list
					var new_line = '<a href="#!" class="collection-item" onClick="loadChat(\''+$("#receiver").val()+'\')">'+$("#receiver").val()+'<br><small><?=$LANG['Just now']?></small></a>';
					$("#chat_lists").prepend(new_line);
					//show messager form
					$('#chat_messages').show();
					$('#chat_composer').show();
					$('#chat_int').hide();
					//append chat and scrool
					var newM = '<div class="row"><div class="col s11 m10 grey lighten-4 right chts"><strong class="black-text"><?=$LANG['Me']?> <small><?=$LANG['Just now']?></small></strong><br>'+$("#receiver").val()+'</div></div>';
					$("#chat_messages").append(newM);
					//set other test
					$('#receiver2').val($("#receiver").val());
					$('#sender2').val($("#sender").val());
					$('#chating_with').text($("#receiver").val());
					//hide fiorm
					$('#start_chat').hide();
					$('#start-button').show();
					$('#start-spin').hide();
					$("#message").val('');
					$("#receiver").val('');
					
				} else {
					swal("Oops!", '<?=$LANG['Unable to complete action']?> '+status, "warning");
					$('#start-button').show();
					$('#start-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#start-button').show();
				$('#start-spin').hide();
			});
		});
		
		//post message
		$('#send-button').click(function(event) { 
			event.preventDefault();	  
			$('#send-button').hide();
			$('#send-spin').show();
			
			var formData = {
				'receiver'  :  $("#receiver2").val(),
				'sender'  :  $("#sender2").val(),
				'message'  :  $("#message2").val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?post_sms_chat',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					//append chat and scrool
					var newM = '<div class="row"><div class="col s11 m10 grey lighten-4 right chts"><strong class="black-text"><?=$LANG['Me']?> <small><?=$LANG['Just now']?></small></strong><br>'+$("#receiver").val()+'</div></div>';
					$("#chat_messages").append(newM);
					var d = $('#chat_messages');
					d.scrollTop(d.prop("scrollHeight"));
					//hide fiorm
					$('#send-button').show();
					$('#send-spin').hide();
					$("#message2").val('');
					
				} else {
					swal("Oops!", '<?=$LANG['Unable to complete action']?> '+status, "warning");
					$('#send-button').show();
					$('#send-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#send-button').show();
				$('#send-spin').hide();
			});
		});
		
		//fetch new messages every 11 seconds
				
	<?php } ?>

	
	<?php if($URL=='sendemail') { ?>
		$("#recipients").select2();
		$('#send-button').click(function(event) { 
			event.preventDefault();	  
			$('#send-button').hide();
			$('#send-spin').show();
			
			var formData = {
				'recipients'  :  $("#recipients").val(),
				'subject'  :  $("#subject").val(),
				'message'  :  $("#message").val(),
				'attach'  :  $("#files_holder").val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?send_email',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Done']?>!",   
						text: "<?=$LANG['Your email message has been queued and will be procesed soon']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>'; 
					});
					$('#send-button').show();
					$('#send-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to complete action']?> '+status, "warning");
					$('#send-button').show();
					$('#send-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#send-button').show();
				$('#send-spin').hide();
			});
		});
		jQuery.fn.extend({
				toggleText: function (a, b){
					var that = this;
					if (that.text() != a && that.text() != b){
						that.text(a);
					}
					else
						if (that.text() == a){
							that.text(b);
						}
					else
						if (that.text() == b){
							that.text(a);
						}
					return this;
				}
			});
			var editor = new Simditor({
				textarea: $('#message'),
				toolbar: [
				  'title',
				  'bold',
				  'italic',
				  'underline',
				  'strikethrough',
				  'fontScale',
				  'color',
				  'ol',            
				  'ul',            
				  'blockquote',
				  'code',        
				  'table',
				  'link',
				  'image',
				  'hr',            
				  'indent',
				  'outdent',
				  'alignment'
				]
			});
	<?php } ?>
	$('#verP-button').click(function(event) { 
			event.preventDefault();	  
			$('#verP-button').hide();
			$('#verP-spin').show();
			
			var formData = {
				'code'  :  $("#code").val(),
				'user' : '<?=$userID?>'
			};
			
			$.ajax({
				type        : 'POST', 
				url         : 'API?verify_phone',
				data        : formData, 
			}).done(function(data) {
				var status = data.split(':')[0];
				if(status.replace(/\s+/g, '') == 'success') {
					swal({   
						title: "<?=$LANG['Congratulations']?>!",   
						text: "<?=$LANG['You have successfully verified your phone number']?>",   
						type: "success",   
						confirmButtonColor: "#086",   
						confirmButtonText: "Got it!", 
						closeOnConfirm: false 
					}, function(){  
						window.location = '<?=$URL?>'; 
					});
					$('#verP-button').show();
					$('#verP-spin').hide();
				} else {
					swal("Oops!", '<?=$LANG['Unable to complete action']?> '+status, "warning");
					$('#verP-button').show();
					$('#verP-spin').hide();	
				}
			}).fail(function (jqXHR,status,err) {
				swal("Oops!", '<?=$LANG['Unable to establish connection to server']?>! '+err, "warning");
				$('#verP-button').show();
				$('#verP-spin').hide();
			});
		});
		
		//do notifications for customers
		<?php 
		if(userRole()>2) { 
			$pushTitle=getSetting('pushTitle');$pushFor=getSetting('pushFor');$pushPages=getSetting('pushPages');$pushMessage=getSetting('pushMessage');
			if(!empty($pushMessage)) { 
				if($pushFor==0||($pushFor==1&&userRole()==4)||(($pushFor==2&&userRole()==3))) { 
					if($pushPages=='all'||(strtolower($pushPages)==strtolower($URL))) { 
						?>swal({ title: "<?=$pushTitle?>", text: '<?=str_replace("'","\'",trim(preg_replace('/\s+/',' ',$pushMessage)))?>',type: "info",html: true ,showCancelButton: false, confirmButtonColor: "#086", confirmButtonText: "OK",closeOnConfirm: true }, function(){ });
<?php	
					}
				}
			}
		}
		?>
}); //End of DOM functions