//var body = document.getElementsByTagName("body")[0];

{% if app.config['recaptcha_registration_enabled'] %}

var mycRecaptchaObject;

var initMycRecaptcha = function(){
	var recaptchaDiv = document.getElementById('mycFormRecaptcha');	
	recaptchaDiv.innerHTML = "";
	mycRecaptchaObject = grecaptcha.render("mycFormRecaptcha",{sitekey: "{{app.config['recaptcha_client_key']}}", callback: "myc_recaptchaSuccess", size: "invisible"});
}
{% endif %}



	
initMycForm = function(){
		
	

	var mycModal = document.createElement('div');
	mycModal.id="myc-modal-wrapper";
	mycModal.innerHTML = decodeURIComponent('{{modal_content}}');
	
	document.body.appendChild(mycModal);
		
	var modal = document.getElementById('myc-modal');	
	
	var openBtn = document.getElementsByClassName('myc-open-register-modal');
	for (var i = 0; i < openBtn.length; i++){
	    openBtn[i].onclick = function() { myc_customerRegisterPanel(); modal.style.display = "block"; }	
	}
	
	var openBtnLogin = document.getElementsByClassName('myc-open-login-modal');
	for (var i = 0; i < openBtnLogin.length; i++){
	    openBtnLogin[i].onclick = function() { myc_customerLoginPanel(); modal.style.display = "block"; }	
	}
	
	var closeBtn = document.getElementById("myc-close-btn");	
	var closeSpan = document.getElementsByClassName("myc-modal-close")[0];

	closeBtn.onclick = function() { modal.style.display = "none"; }
	closeSpan.onclick = function() { modal.style.display = "none"; }
	
	window.onclick = function(event) {
	    if (event.target == modal) {
	        modal.style.display = "none";
	    }
	}
	
	{% if app.config['recaptcha_registration_enabled'] %} 
		
		if(typeof grecaptcha === "undefined"){
		    var recaptchaScript = document.createElement('script');
		    recaptchaScript.src = "https://www.google.com/recaptcha/api.js?onload=initMycRecaptcha&render=explicit";
		    document.head.appendChild(recaptchaScript);
		}
		
		else initMycRecaptcha();
		
	{% endif %}
	

};


document.addEventListener("DOMContentLoaded", function() { initMycForm() });

function myc_customerRegister(){
	
		 var isValid = true;
		 
		 
		 var inputFields = document.getElementById("myc-registration-form").querySelectorAll("input,select,textarea");
		 		
		 for(var i = 0; i<inputFields.length; i++){
			 if(inputFields[i].hasAttribute('required') && inputFields[i].value==""){
			 	console.log(inputFields[i].name+" - "+inputFields[i].value);
			 	inputFields[i].closest("div").classList.add("invalid");
			 	isValid = false;
			 }
			 else{
				inputFields[i].closest("div").classList.remove("invalid"); 
			 }
		 }
		 			
		if(isValid){
			{% if app.config['recaptcha_registration_enabled'] %} 
				grecaptcha.execute(mycRecaptchaObject);
			{% else %}	
				myc_sendRegistrationRequest();
			{% endif %}
			return true;
		}
		else {		
			document.getElementById("myc-registration-form").classList.add('myc-shake');
			setTimeout(function(){ 
				document.getElementById("myc-registration-form").classList.remove('myc-shake');
		    }, 400);
			
			return false;
		}
		 
		 
		 
}

	 
function myc_sendRegistrationRequest(){
		
		var modalActions = document.getElementsByClassName('myc-modal-actions');
		for (var i = 0; i < modalActions.length; i++){
			modalActions[i].style.display = "none"; 
		}
		
		
		var messageModal =  document.getElementById("myc-modal-message");
		messageModal.classList.remove('myc-error-message');
		messageModal.classList.add('myc-check-message');
	    messageModal.innerHTML = "Checking...";
	    messageModal.style.display = "block";
		
		var url = '{{app.config["app_url"]}}/index.php/customer-register';
				
		var contact_form = document.getElementById('contact-registration-form');		
		var org_form = document.getElementById('org-registration-form');
		
		
		var cntData = {};
	    for(var i=0; i<contact_form.elements.length; i++)
			cntData[contact_form.elements[i].name]=contact_form.elements[i].value; 
	    
	    var orgData = {};
	    for(var i=0; i<org_form.elements.length; i++)
			orgData[org_form.elements[i].name] = org_form.elements[i].value;
	    
	    var formData = new FormData();
	    formData.append("contact_details",myc_serialize(cntData));
	    formData.append("org_details",myc_serialize(orgData));
	    
	    {% if app.config['recaptcha_registration_enabled'] %}
	    	formData.append("g-recaptcha-response",grecaptcha.getResponse());
		{% endif %}
		
	    var xmlHttp = new XMLHttpRequest();
        xmlHttp.onreadystatechange = function()
        {
	        
	        
            if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
            {	  
	            messageModal.classList.remove('myc-check-message');
	                      
                var response = JSON.parse(xmlHttp.responseText);
                console.log(response);
                console.log(xmlHttp.responseText);
                
                if(response.result){
	                contact_form.style.display = "none";
	                org_form.style.display = "none";
	                
	                for (var i = 0; i < modalActions.length; i++){
						modalActions[i].style.display = "none"; 
					}
		
	                
	                messageModal.classList.add('myc-success-message');
	                messageModal.innerHTML = response.message;
                }
                else{
	                for (var i = 0; i < modalActions.length; i++){
						modalActions[i].style.display = "block"; 
					}
		
	                messageModal.classList.add('myc-error-message');
	                messageModal.innerHTML = response.error;
                }
                
            }
            
        }
        xmlHttp.open("POST", url); 
        xmlHttp.send(formData);
		
		{% if app.config['recaptcha_registration_enabled'] %}
		 	grecaptcha.reset(mycRecaptchaObject);
		{% endif %}
}


var mycCurrentPanel = "";
function myc_customerRegisterPanel(){
	
	mycCurrentPanel = "register";
	
	var modalTitle = document.getElementsByClassName('myc-modal-title')[0];
	modalTitle.innerHTML = "Registration Form";
	
	var showPanel =  document.getElementById("myc-registration-form");
	var hidePanel =  document.getElementById("myc-login-form");
	var hidePanel2 =  document.getElementById("myc-forgot-form");
	
	hidePanel.style.display = "none";
	hidePanel2.style.display = "none";
	showPanel.style.display = "inline";
	
	var modalWindow = document.getElementsByClassName('myc-modal-content')[0];
	modalWindow.style.width = "80%";
}

function myc_customerForgotPanel(){
	
	mycCurrentPanel = "forgot";
	
	var modalTitle = document.getElementsByClassName('myc-modal-title')[0];
	modalTitle.innerHTML = "Password Reset";
	
	var showPanel =  document.getElementById("myc-forgot-form");
	var hidePanel =  document.getElementById("myc-login-form");
	var hidePanel2 =  document.getElementById("myc-registration-form");
	
	hidePanel.style.display = "none";
	hidePanel2.style.display = "none";
	showPanel.style.display = "inline";
	
	var modalWindow = document.getElementsByClassName('myc-modal-content')[0];
	modalWindow.style.width = "40%";
}


function myc_customerLoginPanel(){
	
	mycCurrentPanel = "login";
	
	var modalTitle = document.getElementsByClassName('myc-modal-title')[0];
	modalTitle.innerHTML = "Login Form";
	
	var showPanel =  document.getElementById("myc-login-form");
	var hidePanel =  document.getElementById("myc-registration-form");
	var hidePanel2 =  document.getElementById("myc-forgot-form");
	
	hidePanel.style.display = "none";
	hidePanel2.style.display = "none";
	showPanel.style.display = "inline";
	
	var modalWindow = document.getElementsByClassName('myc-modal-content')[0];
	modalWindow.style.width = "40%";
}


function myc_recaptchaSuccess(){
	if(mycCurrentPanel=="login") myc_sendLoginRequest();
	else if(mycCurrentPanel=="register") myc_sendRegistrationRequest();
	else if(mycCurrentPanel=="forgot") myc_sendForgotRequest();
}








function myc_customerForgot(){
		
		
		var loginUser =  document.getElementById("myc-forgot-email");
	    var isValid = true;
	    
	    if(loginUser.value==""){
			 	loginUser.closest("div").classList.add("invalid");
			 	isValid = false;
		}
		else loginUser.closest("div").classList.remove("invalid");
		
	    
	    if(isValid==false){		   
		    return false;
	    }
		
		{% if app.config['recaptcha_registration_enabled'] %} 
				grecaptcha.execute(mycRecaptchaObject);
		{% else %}	
				myc_sendForgotRequest();
		{% endif %}
		
}

function myc_sendForgotRequest(){
		
		var loginUser =  document.getElementById("myc-forgot-email");
	    var isValid = true;
	    
	    if(loginUser.value==""){
			 	loginUser.closest("div").classList.add("invalid");
			 	isValid = false;
		}
	    
	    if(isValid==false){		   
		    return false;
	    }
		
		var login_form = document.getElementById("myc-contact-forgot-form");
		
		var modalActions = document.getElementsByClassName('myc-modal-actions');
		for (var i = 0; i < modalActions.length; i++){
			modalActions[i].style.display = "none"; 
		}
		
		
		var messageModal =  document.getElementById("myc-modal-forgot-message");
		messageModal.classList.remove('myc-error-message');
		messageModal.classList.add('myc-check-message');
	    messageModal.innerHTML = "Checking...";
	    messageModal.style.display = "block";
		
		var url = '{{app.config["app_url"]}}/index.php/api/reset-password';
				
	    var formData = new FormData();
	    formData.append("user",loginUser.value);
	 
	    var xmlHttp = new XMLHttpRequest();
        xmlHttp.onreadystatechange = function()
        {
	        
	        
            if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
            {	  
	            messageModal.classList.remove('myc-check-message');
	                      
                var response = JSON.parse(xmlHttp.responseText);
                console.log(response);
                console.log(xmlHttp.responseText);
                
                if(response.result!==undefined && response.result!="error"){
	                login_form.style.display = "none";
	                
					for (var i = 0; i < modalActions.length; i++){
					    modalActions[i].style.display = "none"; 
					}
	                
	                messageModal.classList.add('myc-success-message');
	                messageModal.innerHTML = "Success!";
                }
                else{
	                
	                
					for (var i = 0; i < modalActions.length; i++){
					    modalActions[i].style.display = "block"; 
					}
	                
	                messageModal.classList.add('myc-error-message');
	                messageModal.innerHTML = response.error;
                }
                
            }
            
        }
        xmlHttp.open("POST", url); 
        xmlHttp.send(formData);
        
        {% if app.config['recaptcha_registration_enabled'] %}
		 	grecaptcha.reset(mycRecaptchaObject);
		{% endif %}
}








function myc_customerLogin(){
		
		
		var loginUser =  document.getElementById("myc-login-email");
	    var loginPass =  document.getElementById("myc-login-password");
	    var loginLang =  document.getElementById("myc-login-language");
	    var isValid = true;
	    
	    if(loginUser.value==""){
			 	loginUser.closest("div").classList.add("invalid");
			 	isValid = false;
		}
		else loginUser.closest("div").classList.remove("invalid");
		
		if(loginPass.value==""){
			 	loginPass.closest("div").classList.add("invalid");
			 	isValid = false;
		}
		else loginPass.closest("div").classList.remove("invalid");
	    
	    if(isValid==false){		   
		    return false;
	    }
		
		{% if app.config['recaptcha_registration_enabled'] %} 
				grecaptcha.execute(mycRecaptchaObject);
		{% else %}	
				myc_sendLoginRequest();
		{% endif %}
		
}

function myc_sendLoginRequest(){
		
		var loginUser =  document.getElementById("myc-login-email");
	    var loginPass =  document.getElementById("myc-login-password");
	    var loginLang =  document.getElementById("myc-login-language");
	    var isValid = true;
	    
	    if(loginUser.value==""){
			 	loginUser.closest("div").classList.add("invalid");
			 	isValid = false;
		}
		else loginUser.closest("div").classList.remove("invalid");
		
		if(loginPass.value==""){
			 	loginPass.closest("div").classList.add("invalid");
			 	isValid = false;
		}
		else loginPass.closest("div").classList.remove("invalid");
	    
	    if(isValid==false){		   
		    return false;
	    }
		
		var login_form = document.getElementById("myc-contact-login-form");
		
		var modalActions = document.getElementsByClassName('myc-modal-actions');
		for (var i = 0; i < modalActions.length; i++){
			modalActions[i].style.display = "none"; 
		}
		
		
		var messageModal =  document.getElementById("myc-modal-login-message");
		messageModal.classList.remove('myc-error-message');
		messageModal.classList.add('myc-check-message');
	    messageModal.innerHTML = "Checking...";
	    messageModal.style.display = "block";
		
		var url = '{{app.config["app_url"]}}/index.php/api/login';
				
	    var formData = new FormData();
	    
	    
	    formData.append("user",loginUser.value);
	    formData.append("pass",loginPass.value);
	 
	    var xmlHttp = new XMLHttpRequest();
        xmlHttp.onreadystatechange = function()
        {
	        
	        
            if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
            {	  
	            messageModal.classList.remove('myc-check-message');
	                      
                var response = JSON.parse(xmlHttp.responseText);
                console.log(response);
                console.log(xmlHttp.responseText);
                
                if(response.result){
	                myc_redirectPost('{{app.config["app_url"]}}/index.php/customer/login_check', {_username: loginUser.value, _password: loginPass.value, user_language: loginLang.value, logout_url: window.location.href })
	                login_form.style.display = "none";
	                
					for (var i = 0; i < modalActions.length; i++){
					    modalActions[i].style.display = "none"; 
					}
	                
	                messageModal.classList.add('myc-success-message');
	                messageModal.innerHTML = "Success! Redirecting ...";
                }
                else{
	                
	                
					for (var i = 0; i < modalActions.length; i++){
					    modalActions[i].style.display = "block"; 
					}
	                
	                messageModal.classList.add('myc-error-message');
	                messageModal.innerHTML = response.error;
                }
                
            }
            
        }
        xmlHttp.open("POST", url); 
        xmlHttp.send(formData);
        
        {% if app.config['recaptcha_registration_enabled'] %}
		 	grecaptcha.reset(mycRecaptchaObject);
		{% endif %}
}


function myc_redirectPost(url, data) {
    var form = document.createElement('form');
    document.body.appendChild(form);
    form.method = 'post';
    form.action = url;
    for (var name in data) {
        var input = document.createElement('input');
        input.type = 'hidden';
        input.name = name;
        input.value = data[name];
        form.appendChild(input);
    }
    form.submit();
}


function myc_serialize(obj, prefix) {
  var str = [], p;
  for(p in obj) {
    if (obj.hasOwnProperty(p)) {
      var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
      str.push((v !== null && typeof v === "object") ?
        myc_serialize(v, k) :
        encodeURIComponent(k) + "=" + encodeURIComponent(v));
    }
  }
  return str.join("&");
}

