const DOMAIN = window.location.hostname;
const GET = "GET";
const POST = "POST";





function objectToQueryString(json) {
    return '?' + 
        Object.keys(json).map(function(key) {
            return encodeURIComponent(key) + '=' +
                encodeURIComponent(json[key]);
        }).join('&');
}
// ECMAScript 6
/*
const objectToQueryString = obj =>
  Object.keys(obj)
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
    .join('&');
*/


(function(window){
    
    // You can enable the strict mode commenting the following line  
    // 'use strict';
    
    // Code
    function mkoLib() {
        
        // private:
        var _mkoLibObj = {};
        var _request = new XMLHttpRequest();
        var _settings = {
            apiurl : 'https://apis.explico.biz/rest/v1',  
        };


        var modal_settings = {
          volume:100,
          mute:false,
          modal_id : null
        };


        // public:

        // Esegue la chiamata alle API di mokoffee
        // _mkoLibObj.callApi = function(method, url, data, callback){
        _mkoLibObj.callApi = function(url, getData, postData, callback){
          
            // Verifica la presenza di postData
            var method;          
            if(Object.keys(postData).length === 0 && postData.constructor === Object) {
              method = GET;
            } else {
              method = POST;
            }
          
            // Assegna il calback se specificato
            _request.onreadystatechange = function() {
                if(_request.readyState == 4 && _request.status == 200) {
                    callback(this.responseText);   
                }
            };
            
            // Costruisce l'url di chiamata eventualmente appende getData
            if(Object.keys(getData).length === 0 && getData.constructor === Object) {
              _request.open(method, _settings.apiurl + url, true);
            } else {
              _request.open(method, _settings.apiurl + url + '?' + objectToQueryString(getData), true);
            }
            
            // Invia la richiesta in GET o POST
            if(Object.keys(postData).length === 0 && postData.constructor === Object) {
              _request.send();
            } else {
              _request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
              _request.send(JSON.stringify( postData ));                            
            }
            
        };

        
        // Open confirm dialog
        _mkoLibObj.confirm = function(options){
            
            modal_settings.modal_id = options.dialog;
            
            document.querySelector('#' + options.dialog + ' .title').innerHTML = options.title;
            document.querySelector('#' + options.dialog + ' .message').innerHTML = options.message;
            
            if(options.buttons.ok) {
                document.querySelector('#' + options.dialog + ' .ok').onclick = options.buttons.ok;
            }
            if(options.buttons.cancel) {
                document.querySelector('#' + options.dialog + ' .cancel').onclick = options.buttons.cancel;
            }
            
            // <span> (x), chiude il dialogo
            document.querySelector('#' + options.dialog + ' .close').onclick = function() {
                document.getElementById(options.dialog).style.display = "none";
            };
            
            // When the user clicks anywhere outside of the modal, close it
            //window.onclick = function(event) {
            //  if (event.target == modal) {
            //    modal.style.display = "none";
            //  }
            //};
            
            document.getElementById(options.dialog).style.display = "block";
        };

        // Close confirm dialog
        _mkoLibObj.confirm.close = function () {
            document.getElementById(modal_settings.modal_id).style.display = "none";
        };

    

    // Then your variable will be exposed with this method !
    _mkoLibObj.getSettings = function(){
        return modal_settings;
    };


    // You can create a get method without expose your variable using something like this
    // The object keys will be copied to a new object instead our object.
    // Note that you need to achieve this method according to the structure of your variable (or if it's an array)
    _mkoLibObj.getsSettings = function(){
      var mySecurityCopy = {};
    
      for(var i in modal_settings) {
          if(i)
            mySecurityCopy[i] = modal_settings[i];
                
      }
    
      return mySecurityCopy;
    };
    
    return _mkoLibObj;
  }

    // We need that our library is globally accesible, then we save in the window
    if(typeof(window.mko) === 'undefined'){
        window.mko = mkoLib();
    }
})(window); // We send the window variable withing our function




    // Restitiisce i parametri della query string dell'URL
    function getParameterByName(name, url) {
        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, '\\$&');
        var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, ' '));
    }

    // Converte i campi del form in json
	function toObject( form ) {
		var obj = {};
    
    if(form.name) obj.formname = form.name;
    
		var elements = form.querySelectorAll( "input, select, radio, checkbox, hidden, textarea" );
		for( var i = 0; i < elements.length; ++i ) {
			var element = elements[i];

			var name = null;
            var value = null;
            
            switch(element.type) {
                case "radio" :
                    if(element.checked)
                    {
                        name = element.name;
                        value = element.value;
                    }
                    break;

                case "checkbox" :
                    if(element.checked)
                    {
                        name = element.name;
                        value = 1;
                    }
                    else {
                        name = element.name;
                        value = 0;
                    }
                    break;

                case "select-one" :
                    name = element.name;
                    value = element.value;
                    break;                

                case "text" :
                case "hidden" :
                case "textarea" :
                case "email" :
                    name = element.name;
                    value = element.value;
                    break;                
            }
            
			if( name ) {
				obj[ name ] = value;
			}
		}
    
    
    
		//return JSON.stringify( obj );
        return obj;
	}
