/* Pulse */
	function VodacomPulse(){
		$('#VodacomPulse button').on('click',function(){
			if(validation('VodacomPulse')){
				$.ajax({
			        type: "GET",
			        url : $baseUrl + '/vodacom-check-email/',
			        data : 'Email=' + $('input[name="Email"]').val(),
			        success : function(data){  
						$('.progress .progress-bar').attr('valuenow','100').html('Step 2 of 2').css('width','100%');
						$('form').hide();
						$('#pulse').before('<div class="alert alert-success">' + data + '</div>');
						$('#pulse').addClass('active');
			        },
			        error : function(data){
			        	console.log(data);
			        	$('#pulse').before('<div class="alert alert-danger">' + data.responseText + '</div>');
			        	$('form').hide();
			         	setTimeout(function(){
				         	window.location.href = $('#base').attr('data-orig') + '/signin';  
						},2000);
			        }
			    },"json");
			}
			return false;
		});
	}
/* Pulse */

/* Billing */
	function MobileBilling(){
		$('form button').on('click',function(){
			if(validation('MobileBillingForm')){
				$('form button').prop("disabled", true);
				$('form').submit();
			}
			return false;
		});
	}
/* Billing */

/* Policies */
	function PoliciesCallBack(){
		$('.policy-process #callback button').on('click',function(){
			if(validation('callback')){
				preloader('body');
				var SAID = $('input[name="IDNumber"]').val();
				var Name = $('input[name="Name"]').val();
				var Permission = $('select[name="Permission"]').val();
				var Product = $('select[name="Product"]').val();
				var CellNumber = $('input[name="sts_tel"]').val();
				$.ajax({
			        type: "GET",
			        url : $baseUrl + '/call-back-process/',
			        data : 'Name=' + Name + '&SAID=' + SAID + '&Permission=' + Permission + '&Product=' + Product + '&CellNumber=' + CellNumber + '&_token=' + $('input[name="_token"]').val(),
			        success : function(data){  
				        var HTML = '<div class="alert alert-success text-center topmargin">Thank you. A consultant will contact you soon.</div>';
						$('.policy-process').after(HTML);
						$('.policy-process').hide();  
						preloaderRemove();
						return false;
			        },
			        error : function(data){
			        }
			    },"json");
			}
			return false;
		});
	}
	function PoliciesPrepaidFuneral(){
		$('.policy-process #prepaid-funeral button').on('click',function(){
			if(validation('prepaid-funeral')){
				var HTML = '<div class="alert alert-success text-center topmargin">Thank you. A consultant will contact you soon.</div>';
				$('.policy-process').after(HTML);
				$('.policy-process').hide();
			}
			return false;
		});
	}
	function PoliciesFuneral(){
		$('.policy-process #funeral button').on('click',function(){
			if(validation('funeral')){
				var HTML = '<div class="alert alert-success text-center topmargin">Thank you. A consultant will contact you soon.</div>';
				$('.policy-process').after(HTML);
				$('.policy-process').hide();
			}
			return false;
		});
	}
	function Legal(){
		$('.policy-process #legal button').on('click',function(){
			if(validation('legal')){
				var HTML = '<div class="alert alert-success text-center topmargin">Please reply YES to the SMS sent to subscribe.</div>';
				$('.policy-process').after(HTML);
				$('.policy-process').hide();
			}
			return false;
		});
	}
/* Policies */

/* Chat */
	function MediSimOnline(ChatID = false){
	    $.ajax({
	        type: "GET",
	        url : $baseUrl + '/member/chat-online/' + ChatID,
	        success : function(data){              
	        },
	        error : function(data){
	        }
	    },"json");
	}

	function MediSimOffline(ChatID = false){
	    $.ajax({
	        type: "GET",
	        url : $baseUrl + '/member/chat-offline/' + ChatID,
	        success : function(data){              
	        },
	        error : function(data){
	        }
	    },"json");
	}
	
	function MediSimChatOffline(Token = false, UserID = false){
		$('#MediSimChat #offline button').on('click',function(){
			var Message = $('textarea[name="Message"]').val();
			if(validation('offline')){
				$.ajax({
		            type: "POST",
		            url : $baseUrl + '/member/chat-offline-message/' + UserID,
		            data : 'Message=' + Message + '&_token=' + Token,
		            success : function(data){              
		            	$('#MediSimChat .form').html('<p>Thank you for your message. We will respond ASAP.');
		            },
		            error : function(data){
		            }
		        },"json");
			}
			return false;
		});
	}

	function MediSimChat(Status = 'online'){
		$('#MediSimChat .Button').on('click',function(){
			var _This = $(this);
			$('#MediSimChat .ChatWindow').show();
			$('#MediSimChat .Button').fadeOut("slow",function(){
				$('#MediSimChat').addClass('active');

				if(Status == 'online'){
					$('.chat-input').focus();
					
					/* Populate History */
						MediSimChatHistory(_This.attr('data-userid'));
					/* Populate History */

					/* Process Chat */
						$('.chat-input').keydown(function(event){
			                if(event.which == 13 || event.which == 9){
			                    MediSimChatProcess(_This.attr('data-userid'),_This.attr('data-token'));
			                }
			            });
		            /* Process Chat */
		        }

	            /* Close Chat */
					$('#MediSimChat .ChatWindow .heading h2 i').on('click',function(){
						MediSimChatClose();
					});
				/* Close Chat */

			});
			if(Status == 'online'){
				MediSimChatCheck(_This.attr('data-userid'));
			}
		});
	}

	function MediSimChatProcess(UserID = false, Token = false){
        var Input = $('.chat-input').val();
        var ChatID = $('.chat-id').val();
        console.log('ChatID: '  + ChatID);
        $.ajax({
            type: "POST",
            url : $baseUrl + '/member/chat/' + UserID + '/' + $('.chat-id').val(),
            data : 'Message=' + Input + '&_token=' + Token,
            success : function(data){              
            	data = $.parseJSON(data);    
            	console.log(data);           
                /* Populate History */
                    $('.chat-input').val('');
                    $('.chat-id').val(data);
                /* Populate History */
            },
            error : function(data){
            }
        },"json");
    }

    function MediSimChatHistory(UserID = false){
        $.ajax({
            type: "GET",
            url : $baseUrl + '/member/chat-history/' + UserID + '/' + $('.chat-id').val(),
            success : function(data){                         
            console.log(data);   
                /* Populate History */
                    if(data.length > 0 && data != 'false'){
                        var HTML = '';
                        $.each(data,function(a,b){
                        	console.log(b);
                            if(b.AdminUserID != 0){
                            	if(b.AdminName){
                            		HTML += '<div class="other-user"><span><strong>' + b.AdminName + '</strong></span><br/><span>' + b.Message + '</span><div class="chat-date">' + b.DateCreated + '</div></div>';
                            	}else{
                            		HTML += '<div class="other-user"><span>' + b.Message + '</span><div class="chat-date">' + b.DateCreated + '</div></div>';	
                            	}                                
                            }else{
                                HTML += '<div class="my-user"><span>' + b.Message + '</span><div class="chat-date">' + b.DateCreated + '</div></div>';
                            }
                        });
                        $('#MediSimChat .chat-history').append(HTML);
                    }                    
                /* Populate History */
                $('.chat-history').scrollTop($('.chat-history')[0].scrollHeight);
            },
            error : function(data){
            }
        },"json");
    }

    function MediSimChatCheck(UserID = false){
        setInterval(function(){
            $.ajax({
                type: "GET",
	            url : $baseUrl + '/member/chat-check/' + UserID + '/' + $('.chat-id').val(),
                success : function(data){                             
                    /* Update History */
                        if(data && data.length > 0 && data != 'false'){
	                        var HTML = '';
	                        $.each(data,function(a,b){
	                            if(b.AdminUserID != 0){
	                            	if(b.AdminName){
	                            		HTML += '<div class="other-user"><span><strong>' + b.AdminName + '</strong></span><br/><span>' + b.Message + '</span><div class="chat-date">' + b.DateCreated + '</div></div>';
	                            	}else{
	                            		HTML += '<div class="other-user"><span>' + b.Message + '</span><div class="chat-date">' + b.DateCreated + '</div></div>';	
	                            	}
	                            }else{
	                                HTML += '<div class="my-user"><span>' + b.Message + '</span><div class="chat-date">' + b.DateCreated + '</div></div>';
	                            }
	                        });
	                        $('#MediSimChat .chat-history').append(HTML);
	                    }                  
                    /* Update History */
                    $('.chat-history').scrollTop($('.chat-history')[0].scrollHeight);
                },
                error : function(data){
                }
            },"json");
        },5000);
    }

	function MediSimChatClose(){
		$('#MediSimChat .Button').show();
		$('#MediSimChat .ChatWindow').fadeOut("slow",function(){
			$('#MediSimChat').removeClass('active');
		});
	}
/* Chat */

function preloader(msg, which){
	preloaderRemove();
	$(which).append($('<div class="overlay_preloader"><div class="col-xs-12 text-center"><img src="' + $('#base').attr('data-orig') + '/storage/img/logos/favicon.png"/></div><div class="col-xs-12 text-center"><div class="pulse"></div><p>' + msg + '</p></div></div>').show().css({'opacity':0}).animate({'opacity':1}));
	return true;
}

function preloaderRemove(){
	$('.overlay_preloader').fadeOut(800, function(){
		$('.overlay_preloader').remove();
	});	
}


function ProfileImageDone(){
	alert('done');
}

function validation( formname,  data ){
	$validated = 0;
	$('.alert-danger').remove();
	$formname = formname;
	/* validation */
	$('#' + formname + ' input,#' + formname + ' textarea').filter('[required]:visible').each(function(k, requiredField){
		$(this).css('border', '2px var(--green) solid');
		var requiredcheck = $(this).attr('required');
		if (typeof requiredcheck !== typeof undefined && requiredcheck !== false) {	
			$error_msg = $(this).attr('data-required');
			if($(this).attr('type') == 'email'){
				var pattern = new RegExp(/^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
				if(pattern.test($(this).val())){
					$value = 'selected';
				}else{
					$value = '';
					$validated++;
				}
			}
			else if($(this).attr('type') == 'radio'){
				if($(this).is(':checked')){
					$value = 'selected';
				}else{
					$value = '';
					$validated++;
				}
			}
			else if($(this).attr('type') == 'password'){
				if($formname != 'profile'){
					if($(this).val().length < 5){
						$error_msg = 'Please enter at least 5 characters';
						$value = '';
						$validated++;
					}else if($(this).val().length >= 5){
						$value = 'true';
					}
				}

				if($(this).attr('data-type') == 'login'){
					$error_msg = $(this).attr('data-required');
				}

				if($(this).attr('data-copy')){
					if($(this).val() == $('#' + $(this).attr('data-copy')).val()){
						$value = 'true';
					}else{
						$error_msg = 'This is not the same as your password.';
						$value = '';
						$validated++;
					}
				}	
			}else if($(this).attr('type') == 'select'){
				if($(this).val()){
					$value = 'selected';
				}else{
					$value = '';
					$validated++;
				}
			}else{
				$value = $(this).val().replace(/ /g,'');
			}

			if(!$value){
				$('#' + $formname + ' button').css('background-color','#b71318').css('color','#fff').css('border-color','#b71318');
				$(this).css('border', '2px solid #b71318');
				$(this).addClass('warning-input').attr('placeholder','* ' + $error_msg);
				$validated++;
			}else{}
		}
	});

		/* select */
		$('#' + formname + ' select').each(function(){
			if($(this).attr('required')){	
				$error_msg = $(this).attr('data-required');
				$value = $(this).val().replace(/ /g,'');
				if(!$value){
					$(this).css('border', '2px solid #b71318');
					$(this).addClass('warning-input');
					$validated++;
				}else{}
			}

		});
		/* select */	

	/* validation */
	if ($validated > 0)	{
		return false;
	} else {
		return true;
	}
}

function FindFields(formname){
	var fields = "_token=" + $('input[name="_token"]').val();
	$('#' + formname + ' input,#' + formname + ' textarea,#' + formname + ' select').each(function(k){
		if($(this).attr('name') != '_token'){
			fields += '&' + $(this).attr('name') + '=' + $(this).val();
		}
	});
	return fields;
}

function SignIn(User = false, Password = false){
	var Email = encodeURIComponent(User.email);
	var DisplayName = User.displayName;
	var PhotoUrl = encodeURIComponent(User.photoURL);
	var UID = User.uid;
	$.ajax({
        type: "GET",
        url : $baseUrl + "/signin-process",
        data : "Email=" + Email + "&DisplayName=" + DisplayName + "&PhotoUrl=" + PhotoUrl + "&UID=" + UID + "&Password=" + Password,
        success : function(data){
        	console.log('Ajax Results');
        	console.log(data);
        	if(data == '1'){
	        	window.location.href = $('#base').attr('data-orig') + '/member';
	        }else{
	        	window.location.href = $('#base').attr('data-orig') + '/signin';
	        }
            return false;
        },
        error : function(data){
        }
    },"json");
}