/* CliqB.Js */
/** Cliqon Blog Functions - Cliqb.action() **/
		
var Cliqb = (function($) {
	// initialise
	// var shared values
	var bcfg = {
		useCaching: true,
		data: {}, app: {},
		spinner: new Spinner(),
		subdir: 'tmp/',
		uploadurl: '/ajax/'+jlcd+'/fileupload/',
		table: 'dbitem',
		tabletype: 'blog',
		df: new Object(),
		dz: new Object(),
		teditor: {},
		idioms: {}, icons: {}
	}, cfg = {};
    var _set = function(key,value)
    {
        bcfg[key] = value;
        return fcfg[key];
    }
    var _get = function(key)
    {
        return bcfg[key];
    }
	/** Top and Row buttons  
	 * @param - array - any data- attached to the field
	 * @return - object - a functional object
	 **/
	 var actionButton = function(dta) {
	
		switch(dta.action) {
			case "cancel":
			case "displayblog":
                var urlstr = '/admindesktop/'+jlcd+'/blogarticle/dbitem/blog/';
                uLoad(urlstr);
			break;
			case "addarticle":
			case "editarticle":
                var urlstr = "/admindesktop/"+jlcd+"/page/dbitem/blog/?class=blog&action=blogform&recid="+dta.recid;
				uLoad(urlstr);
			break;
			case "viewarticle": viewArticle(dta); break;
			default:
				Cliq.success(dta.action);
			break;
		}
	 }
	/** Display the Blog form   
	 * @param - array - configuration options generated by the Server
	 * @return - object - a functional object
	 **/
	 var actionForm = function(opts)
	 {
		$('#pills_tab a').on('click', function (e) {
		  	e.preventDefault();
		  	$(this).tab('show');
		});
		bcfg.df = new Vue({
			el: '#inputform',
			data: opts.pageform.fields,
			methods: {
                // Click Icon Handlers
                clickicon: function(event) {
                	var action = $(event.target).data('action');
                	frmBtn(event.target, action);
                },
                // Image handlers
                onFileChange(e) {
                	e.stopImmediatePropagation();
                	var fldid = $(e.target).data('fldid');
                    var files = e.target.files || e.dataTransfer.files;
                    if(!files.length) {
                       return; 
                    };
                    this.createImage(files[0], fldid);
                },
                createImage(file, fldid) {
                    var d_image = new Image();
                    var reader = new FileReader();
                    var vm = this;
                    reader.onload = (e) => {
                        vm.d_image = e.target.result;
                    };
                    reader.readAsDataURL(file);
                },
                removeImage: function (e) {        
                    e.stopImmediatePropagation();
                    this.d_image = '';
                }
			},
			mounted: function() {
				var that = this;
				// HTML5 Text Types
					$('input[type="text"], input[type="email"], input[type="url"]').each(function() {
		           		
		           		var fldid = $(this).attr('id');
		           		var thisfld = $('#'+fldid);
						if( thisfld.hasClass('nextref') ) {		
							modInput(fldid, 'getnextref','');
						};
						$('.isunique').on('blur', function() {
							modInput(fldid, 'isunique', '');	
						});
					});	
				// Date
					$('.datepicker').pikaday({
						firstDay: 1
					});
				// Tags 
					var tags = explode(',', this.$data.c_options);
					$('.tagit').tagit({
						availableTags: tags,
						singleField: true,
						tagLimit: 10						
					});	
            	// TinyMCE Editor
                    var tinypath = jspath+'tinymce';
                    tinymce.baseURL = tinypath;
                    bcfg.teditor = $('.tiny').tinymce({
                        document_base_url: tinypath,
                        script_url: tinypath,
                        height: 480,
                        theme: 'modern',
                        skin: 'cliqon',
	                    content_style: 'html {padding: 10px 20px; min-height: 400px;}',
						plugins: [
							'advlist code codemirror anchor autosave charmap colorpicker contextmenu hr image imagetools insertdatetime lists link nonbreaking paste preview searchreplace table template textcolor textpattern visualblocks visualchars'
						], // wordcount
						toolbar1: 'savebutton translate | undo redo | insert | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | forecolor backcolor | preview | code',
						// templates: '/dir/templates.php' - URL return JSON output
						image_advtab: true,
						external_filemanager_path: jspath + 'tinymce/plugins/filemanager/',
						filemanager_title:'Filemanager',
						external_plugins: { 'filemanager' : jspath + 'tinymce/plugins/filemanager/plugin.min.js'},
                        codemirror: {
                            indentOnInit: true, // Whether or not to indent code on init.
                            fullscreen: true,   // Default setting is false
                            path: jspath+'codemirror', // Path to CodeMirror distribution
                            config: {           // CodeMirror config object
                               mode: 'application/x-httpd-php',
                               lineNumbers: false
                            },
                            width: 800,         // Default value is 800
                            height: 600,        // Default value is 550
                            saveCursorPosition: true,    // Insert caret marker
                            jsFiles: [          // Additional JS files to load
                               'mode/clike/clike.js',
                               'mode/php/php.js'
                            ]
                        }
                    }); 
                // Mounted ends
			}
		});
		$('#submitbutton').on('click', function (e) {
		  	e.preventDefault();					
			var frmData = getFormData(false);
			var urlstr = '/ajax/'+jlcd+'/postform/dbitem/blog/';
			$.ajax({
				url: urlstr, data: frmData,
				cache: false, contentType: false, processData: false,
				type: 'POST', async: false, timeout: 25000,
				success: function(response, statusText, xhr) {
					// Stop and close the Spinner
					bcfg.spinner.stop();
					// first argument to the success callback is the json data object returned by the server
					if(typeof response == 'object') {
						var match = /NotOk/.test(response.flag);
						if(!match == true) {	
							// Reload the blog
                			var urlstr = '/admindesktop/'+jlcd+'/blogarticle/dbitem/blog/';
                			uLoad(urlstr);
						} else {
							Cliq.error('Ajax function returned error NotOk - '+JSON.stringify(response.msg))
						}; 							
					} else {
						Cliq.error('Response was not JSON object - '+JSON.stringify(response))
					};
				}, 
     	 		error: function(xhr, status, text) {
					cfg.spinner.stop();
					var response = $.parseJSON(xhr.responseText);
					Cliq.error(JSON.stringify(response.msg));
					return false;
				}
			}); 
		});
	 }
 	/** Next Reference, Next ID, Is Unique       
 	 * 
 	 * @param - 
 	 * @param -
 	 * @return - 
 	 **/
	 var modInput = function(fldid, action, prefix) // eg 'reference'
	 {               
        cfg = Cliq.config();
       	// console.log(fldid, action, table, tabletype);
        var urlstr = '/ajax/'+cfg.langcd+'/'+action+'/'+cfg.table+'/'+cfg.tabletype+'/';
        aja().method('GET').url(urlstr)
        .data({fld: fldid, prefix:prefix, currval: $('#'+fldid).val() }).cache(false)
        .on('40x', function(response) {Cliq.error('Page not Found - '+urlstr+':'+response);})
        .on('500', function(response) {Cliq.error('Server Error - '+urlstr+':'+response);})
        .on('timeout', function(response) {Cliq.error('Timeout - '+urlstr+':'+response);})
        .on('success', function(response) {
            
			if(typeof response == 'object')
			{
				// Test NotOK - value already exists
				var match = /NotOk/.test(response.flag);
				if(!match == true) {
					
					switch(action) {
						case "getnextref":
						case "getnextentry":
						case "getnextid":
							Vue.set(bcfg.df, fldid, response.data);
							$('#'+fldid).val(response.data);
						break;
						
						case "isunique":
							if(response.data) {
								$('#'+fldid).val('');
								$('#'+fldid).focus();
								Cliq.msg({type: 'warning', buttons: false, text: 'Value already exists'});
							};
						break;
					};		
					
                } else { Cliq.error('Ajax function returned error NotOk - '+urlstr+':'+JSON.stringify(response)); }; 
            } else { Cliq.error('Response was not JSON object - '+urlstr+':'+response.msg); }
        }).go(); 	
	 }
    /** Get all form data for a form  
 	 * A function to collect any and all data, including files from a form
 	 * @param - boolean - add filename
 	 * @param - string - 
 	 * @return - object - the FormData
 	 **/
 	 var getFormData = function(addfilename) {
 		// Test config files
 		// console.log(cfg, fcfg);
 		// cfg contains:  displaytype, table and tabletype, langcd  		
 		
 		// Define the Form ID
 			var id = 'inputform'; var thisform = $('#'+id);
 		// Start a Spinner
 			var target = document.getElementById(id); bcfg.spinner.spin(target);	
		// Get any tinymce Editors if exist and update the Vue instance with Tiny editor content
			var tinyeditors = tinymce.EditorManager.editors;
			if(count(tinyeditors) > 0) {
				var vals = {};
				var fldname = '';
				$.each(tinyeditors, function(i, teditor) {
					var name = trim(teditor.id, '_te'); // works fine
					// d_text_en
					var val = tinymce.get(teditor.id).getContent();		
					var t = explode('_', name);
					if(fldname != t[0]+'_'+t[1]) {fldname = t[0]+'_'+t[1];};
					var k = t[2];
					vals[k] = val;
				});	
				Vue.set(bcfg.df, fldname, vals);
			};
		// If Tagit
			$('.tagit').each(function() {
				var fldid = $(this).attr('id');
				var tags = $("#"+fldid).tagit("assignedTags");
				var strtags = implode(',', tags);
				Vue.set(bcfg.df, fldid, strtags);
			});     
       	
 		// validation here	if required
 		// Change language entries to JSON
 			Vue.set(bcfg.df, 'd_title', json_encode(bcfg.df.d_title));
			Vue.set(bcfg.df, 'd_description', json_encode(bcfg.df.d_description));
			Vue.set(bcfg.df, 'd_text', rawurlencode(json_encode(bcfg.df.d_text)));
		// Now get Data from the Vue Instance
			var postData = bcfg.df.$data;	
		
		// Test Form Content
			// console.log(postData);	           				
		// Now convert Postdata to FormData
			var frmData = new FormData();
			$.each(postData, function(fld, val) {
				frmData.set(fld, val);
			});
			frmData.append('token', jwt);
		
		// Add any AJAX Form upload for a single file
			if( $('#'+id+' :input').hasClass('form-control-file') ) {
				var file = $('input[type=file]', thisform)[0].files[0];		
				if(addfilename) {
					frmData.append(addfilename, file.name);	
				} else {
					frmData.append('filename', file.name);	
				}											
				frmData.append(file.name, file, file.filename);	
			}
		// New image handling will get image contents anyway
		return frmData;		
 	 }
 	/** View article as it would appear in a popup
 	 * @param - all the Data
 	 * @return - Popup with content
 	 **/
 	 var viewArticle = function(dta)
 	 {
        cfg = Cliq.config();
        var urlstr = '/ajax/'+cfg.langcd+'/getblogview/'+cfg.table+'/'+cfg.tabletype+'/';
        aja().method('GET').url(urlstr)
        .data({'recid': dta.recid}).cache(false)
        .on('40x', function(response) {Cliq.error('Page not Found - '+urlstr+':'+response);})
        .on('500', function(response) {Cliq.error('Server Error - '+urlstr+':'+response);})
        .on('timeout', function(response) {Cliq.error('Timeout - '+urlstr+':'+response);})
        .on('success', function(response) {           
			if(typeof response == 'object')
			{
				// Test NotOK - value already exists
				var match = /NotOk/.test(response.flag);
				if(!match == true) {
            		var opts = {
	                    content: '<div class="col mr10 pad">'+response.html+'</div>',
	                    contentSize: {
	                        width: 600,
	                        height: 600
	                    },
	                    paneltype: 'modal',
	                    headerTitle: '<span class="">'+response.title+'</span>'
	                };
	                var viewPopup = Cliq.win(opts);
                } else { Cliq.error('Ajax function returned error NotOk - '+urlstr+':'+JSON.stringify(response)); }; 
            } else { Cliq.error('Response was not JSON object - '+urlstr+':'+response.msg); }
        }).go(); 					
 	 }
	// explicitly return public methods when this object is instantiated
	return {
	   // outside: inside
	   actionButton: actionButton,
	   actionForm: actionForm,
       set: _set,
       get: _get
	};   
})(jQuery);
 
  |