// all div have href as a
jQuery(document).on("click","[href]:not(a)",function(){
  window.location=jQuery(this).attr('href');
});
// Function
function erase(element,rank){
  var a = jQuery(element);
  for (var i = 0; i < rank; i++) {
    a = a.parent().first();
  }
  a.remove();
}
function print(content){
    var mywindow = window.open('', 'PRINT', 'height=700,width=1200');

    mywindow.document.write('<html><head><title>' + document.title  + '</title>');
    mywindow.document.write('</head><body style="margin: 0;">');

    mywindow.document.write(content);
    mywindow.document.write('</body></html>');

    mywindow.document.close(); // necessary for IE >= 10
    mywindow.focus(); // necessary for IE >= 10*/

    mywindow.print();
    mywindow.close();

    return true;
}
// Ajax 
function handle_ajax_return_data(data,form="#null"){
  try{
    obj = JSON.parse(data);
  }catch(e){
    return false;
  }
  // redirect to a url
  if (typeof obj.redirect !== 'undefined') {
    console.log(base_url+obj.redirect);
    window.location.replace(base_url+obj.redirect);
    window.location.reload();
  }
  // Show Toast Notification
  if (typeof obj.notification !== 'undefined') {
    jQuery.toast({
      text: obj.notification,
      icon: obj.type,
      loader: false,        // Change it to false to disable loader
    })
  }
  // change Form HTML content
  if (typeof obj.form !== 'undefined') {
    jQuery(form).html(obj.form);
  }
  // replace some HTML content
  if (typeof obj.replace !== 'undefined') {
    jQuery.each( obj.replace, function( key, value ) {
      jQuery(key).replaceWith(value);
    });
    if ( (typeof obj.iframe !== 'undefined') && document.querySelector(obj.iframe)!=null ) document.querySelector(obj.iframe).contentWindow.postMessage("console.log(iframe transfer);");
  }
  // append some HTML content
  if (typeof obj.append !== 'undefined') {
    jQuery.each( obj.append, function( key, value ) {
      jQuery(key).append(value);
    });
  }
  // change value input
  if (typeof obj.value === 'object') {
    jQuery.each( obj.value, function( key, value ) {
      jQuery(key).val(value);
    });
  }
  // delete,erase HTML
  if (typeof obj.remove !== 'undefined') {
    jQuery(obj.remove).remove();
  }
  // redirect to a url
  if (typeof obj.redirect !== 'undefined') {
    window.location.replace(obj.redirect);
  }
  // Toggle Modal
  if (typeof obj.modal !== 'undefined') {
    jQuery(obj.modal).modal('toggle');
  }
  // Click some button
  if (typeof obj.click !== 'undefined') {
    jQuery(obj.click).click();
  }
  // Focus selector
  if (typeof obj.focus !== 'undefined') {
    jQuery(obj.focus).focus();
  }
  // print content
  if (typeof obj.print !== 'undefined') {
    jQuery("body").append("<div class='reload' id='print'></div>");
    jQuery("#print").html(obj.print);
    print(jQuery("#print").html());
    jQuery("#print").remove();
  }
  // RUN SCRIPT ON IFRAME
  if (typeof obj.iframe !== 'undefined'){
    var iframe = document.querySelector(obj.iframe).contentWindow;
    obj.iframe = undefined;
    obj.notification = undefined;
    obj.modal = undefined;
    iframe.postMessage(JSON.stringify(obj));
    obj.eval = undefined;
  }
  // --------------------------------------------------------------------
  if (typeof obj.eval !== 'undefined') {
    eval(obj.eval);
  }
  // change some HTML content
  if (typeof obj.html === 'object' ) {
    jQuery.each( obj.html, function( key, value ) {
      jQuery(key).html(value);
    });
  }
  setTimeout(function() {	  handle_permission();	}, 200);
}
window.onmessage = function(e){
  if (e.data !== 'undefined') {
    handle_ajax_return_data(e.data);
  }
};
function ajax(action=base_url+uri,data='',method='GET',async=false){
  var a;
  jQuery.ajax({
    async: async,
        type: method,
        url: action,
        data: data,
        dataType: "html",
        success: function(data) {
          if(async){
            handle_ajax_return_data(data);
          }else{
            a = data;
          }
        },
        error: function() {
          jQuery.toast({
          heading: 'Error',
          text: 'Action error',
          icon: 'error',
          loader: false,
      })
        }
    });
  return a;
}

jQuery(document).on("click",".form.ajax .submit",function(){
  
  var action = jQuery(this).attr('action');
  var method = jQuery(this).attr('method');
  var form = jQuery(this).parents(".ajax").first();
  var name = jQuery(this).attr('name');
  var value = jQuery(this).attr('value');

  var input = jQuery(form).find(':input');
  jQuery.each( input, function( key, value ) {
    if(jQuery(value)[0].checkValidity()==false) return jQuery(value)[0].reportValidity();
  });
  var data = jQuery(form).find(':input').serialize();
  if( name!=""&&value!="" ) data+="&"+name+"="+value;
  if(action == undefined) action = jQuery(form).attr('action');
  if(method == undefined) method = jQuery(form).attr('method');
  if(action == undefined) action = base_url+uri;
  if(method == undefined) method = "GET";
  
  ajax(action,data,method,true);

  return false;
});

function ajax_submit(form,async=false){

  var method = jQuery(form).attr('method');
  if(!method) method = "GET";
  var action = jQuery(form).attr('action');
  if(!action) action = jQuery(form).attr('href');
  if(!action) action = base_url+uri;
  var a;

  var data = jQuery(form).find(':input').serialize() ;
  var b = jQuery(form).data();
  for(key in b) data+='&'+key+'='+b[key];


  jQuery.ajax({
    async: async,
        type: method,
        url: action,
        data: data,
        dataType: "html",
        success: function(data) {
          if(async){
            handle_ajax_return_data(data);
            a = true;
          }else{
            a = data;
          }
        },
        error: function() {
            jQuery.toast({
          heading: 'Error',
          text: 'submit error',
          icon: 'error',
          loader: true,        // Change it to false to disable loader
          loaderBg: '#9EC600'  // To change the background
      })
        }
    });
  return a;
}
jQuery(document).on("submit","form.ajax",function(){
    ajax_submit(this,true);
    return false;
});
jQuery(document).on("click","a.ajax",function(){
    ajax_submit(this,true);
    return false;
});
jQuery(document).on("click",".button.ajax",function(){
    ajax_submit(this,true);
    return false;
});

jQuery(document).on('keydown',"form.ctrl-s", function(e) {
  if(e.ctrlKey && (e.which == 83)) {
  e.preventDefault();
  jQuery(this).submit();
  return false;
  }
});
// click to addclass active
jQuery(document).on('click', '.clickable-active', function(){
	var b = jQuery(this).attr('target');
	var target = jQuery(this);
	if(typeof b !== "undefined") target = jQuery(b);
    if(target.hasClass('active')){
    	target.removeClass('active');
    }else{
    	target.addClass('active');
    }
});

jQuery(document).on('click', '[toggle-class]', function(){
  var c = jQuery(this).attr('toggle-class');
  if(c=='') c = 'active';
  //clear class
  var clear = jQuery(this).attr('clear');
  jQuery(clear).removeClass(c);
  
  var b = jQuery(this).attr('target');
  var target = jQuery(this);
  if(typeof b !== "undefined") target = jQuery(b);
    if(target.hasClass(c)){
      target.removeClass(c);
    }else{
      target.addClass(c);
    }
});



// Fancybox
jQuery(document).on('click', '.iframe-btn', function(){
    jQuery.fancybox.open({
      src: jQuery(this).attr('href'),
      'width'   : 900,
      'height'  : 600,
      'type'    : 'iframe',
      'autoScale'     : true
    });
    return false;
});






function handle_permission(){
  var permissions=[];
  jQuery("[permission]").each(function(){
    var permission = jQuery(this).attr("permission");
    if (permissions.indexOf(permission) === -1) {
      permissions.push(permission);
    }
  });
  var urls=[];
	jQuery(".permissions [href],.permissions [action]").each(function(){
		var url = jQuery(this).attr('href');
    if (urls.indexOf(url) === -1) {
      urls.push(url);
    }
	});

  if( jQuery("[permission]").length>0 || jQuery(".permissions [href],.permissions [action]").length>0 ){
  	var data = {};
  	data["permissions"] = JSON.stringify(permissions);
  	data["urls"] = JSON.stringify(urls);



  	
  	try {obj = JSON.parse( ajax(base_url+'permissions/verification',data) );}catch(e){}
    jQuery("[permission]").each(function(){
      var permission = jQuery(this).attr("permission");
      if( obj[permission] >= 1 ) jQuery(this).show();
      else jQuery(this).remove();
      jQuery(this).removeAttr("permission");
    });
  }
}

function handle_time(selector = document){
  jQuery(selector).find(".time").each(function(){
    // get data
    var timestamp = jQuery(this).data('value');
    var format = jQuery(this).data('format');
    if(timestamp!=0) jQuery(this).html(time_format(timestamp,format));
  });
}
//<!-- AUTO SCROLL TO ID -->
jQuery(document).ready(function(){
  var id = window.location.hash;

  if( typeof jQuery(id)[0] !== 'undefined' ) jQuery('html, body').animate({scrollTop: jQuery(id).offset().top}, 1000);
});
function change_to_slug(target,value){
  slug = value.toLowerCase();
  //Đổi ký tự có dấu thành không dấu
  slug = slug.replace(/á|à|ả|ạ|ã|ă|ắ|ằ|ẳ|ẵ|ặ|â|ấ|ầ|ẩ|ẫ|ậ/gi, 'a');
  slug = slug.replace(/é|è|ẻ|ẽ|ẹ|ê|ế|ề|ể|ễ|ệ/gi, 'e');
  slug = slug.replace(/i|í|ì|ỉ|ĩ|ị/gi, 'i');
  slug = slug.replace(/ó|ò|ỏ|õ|ọ|ô|ố|ồ|ổ|ỗ|ộ|ơ|ớ|ờ|ở|ỡ|ợ/gi, 'o');
  slug = slug.replace(/ú|ù|ủ|ũ|ụ|ư|ứ|ừ|ử|ữ|ự/gi, 'u');
  slug = slug.replace(/ý|ỳ|ỷ|ỹ|ỵ/gi, 'y');
  slug = slug.replace(/đ/gi, 'd');
  //Xóa các ký tự đặt biệt
  slug = slug.replace(/\`|\~|\!|\@|\#|\||\$|\%|\^|\&|\*|\(|\)|\+|\=|\,|\.|\/|\?|\>|\<|\'|\"|\:|\;|_/gi, '');
  //Đổi khoảng trắng thành ký tự gạch ngang
  slug = slug.replace(/ /gi, "-");
  //Đổi nhiều ký tự gạch ngang liên tiếp thành 1 ký tự gạch ngang
  //Phòng trường hợp người nhập vào quá nhiều ký tự trắng
  slug = slug.replace(/\-\-\-\-\-/gi, '-');
  slug = slug.replace(/\-\-\-\-/gi, '-');
  slug = slug.replace(/\-\-\-/gi, '-');
  slug = slug.replace(/\-\-/gi, '-');
  //Xóa các ký tự gạch ngang ở đầu và cuối
  slug = '@' + slug + '@';
  slug = slug.replace(/\@\-|\-\@|\@/gi, '');
  //In slug ra textbox có id “slug”
  //document.getElementById('slug').value = slug;
  
  jQuery(target).val(slug);
}

function handle_colorpicker(selector = document){
  if (typeof jQuery(selector).colorpicker === 'undefined') return false;
  jQuery(selector).find('.item-color').colorpicker({format: "rgba"});
  jQuery(selector).find('.colorpicker').colorpicker({format: "rgba"});
}

// Tiny MCE
jQuery("#modal").on("hidden.bs.modal", function () {
  tinymce.remove('#modal textarea.tinymce');
});

function handle_tinymce(selector = document){
  if (typeof tinymce === 'undefined') return false;
  var a = jQuery(selector).find('.tinymce');
  tinymce.init({
  selector: a,
  plugins: [
   "advlist autolink link image lists charmap print preview hr anchor pagebreak",
   "searchreplace wordcount visualblocks visualchars insertdatetime media nonbreaking fullscreen",
   "table contextmenu directionality emoticons paste textcolor responsivefilemanager code "
  ],
  toolbar: 'undo redo pastetext | styleselect | fontselect | fontsizeselect | bold italic underline | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link unlink anchor | table responsivefilemanager image media | forecolor backcolor | print preview code | a11ycheck',
  image_advtab: true,
  external_filemanager_path:"/plugins/filemanager/",
  filemanager_title:"Responsive Filemanager",
  external_plugins: { "filemanager" : "/plugins/filemanager/plugin.min.js"},
  content_css: [
  '//fonts.googleapis.com/css?family=Lato:300,300i,400,400i',
  '//www.tiny.cloud/css/codepen.min.css'
  ],
  link_list: [
  { title: 'My page 1', value: 'http://www.tinymce.com' },
  { title: 'My page 2', value: 'http://www.moxiecode.com' }
  ],
  image_list: [
  { title: 'My page 1', value: 'http://www.tinymce.com' },
  { title: 'My page 2', value: 'http://www.moxiecode.com' }
  ],
  image_class_list: [
  { title: 'None', value: '' },
  { title: 'Some class', value: 'class-name' }
  ],
  importcss_append: true,
  height: 400,
  file_picker_callback: function (callback, value, meta) {
  /* Provide file and text for the link dialog */
  if (meta.filetype === 'file') {
    callback('https://www.google.com/logos/google.jpg', { text: 'My text' });
  }

  /* Provide image and alt text for the image dialog */
  if (meta.filetype === 'image') {
    callback('https://www.google.com/logos/google.jpg', { alt: 'My alt text' });
  }

  /* Provide alternative source and posted for the media dialog */
  if (meta.filetype === 'media') {
    callback('movie.mp4', { source2: 'alt.ogg', poster: 'https://www.google.com/logos/google.jpg' });
  }
  },
  templates: [
  { title: 'Some title 1', description: 'Some desc 1', content: 'My content' },
  { title: 'Some title 2', description: 'Some desc 2', content: '<div class="mceTmpl"><span class="cdate">cdate</span><span class="mdate">mdate</span>My content2</div>' }
  ],
  template_cdate_format: '[CDATE: %m/%d/%Y : %H:%M:%S]',
  template_mdate_format: '[MDATE: %m/%d/%Y : %H:%M:%S]',
  image_caption: true,

  spellchecker_dialog: true,
  spellchecker_whitelist: ['Ephox', 'Moxiecode']
  });
}
function handle_to_slug(selector = document){
  jQuery(selector).find('.to-slug').keyup(function(){
    var a = jQuery(this).data('target');
    if( jQuery(a).data("old") == ""){
      var b = jQuery(this).val();
      change_to_slug(a,b);
    }
  });
}
function handle_price(selector = document){
  jQuery(selector).find(".price").each(function(){
    var a = jQuery(this).data('value');
    var b = jQuery(this).html();
    var result = number_format(a,0,'','.')+'<sup>đ</sup>';
    if(a>0||b==""||b==a){
      jQuery(this).html(result);
    }
  });
}

function handle(selector = document){
  handle_price(selector);
  handle_time(selector);
  handle_to_slug(selector);
  handle_tinymce(selector);
  handle_colorpicker(selector);
  // pathname auto active menu
  jQuery(selector).find(".menu").find("a").each(function(){
    if( jQuery(this).attr('href') == uri ){
      var element = jQuery(this).parent().first(); 
      while( element.prop("tagName")=="LI" ){
        element.addClass("active");
        element = element.parent().first();
        element = element.parent().first();
      }
      
    }
  });
  //---------
  jQuery(".readonly").keydown(function(e){
    e.preventDefault();
  });
  //notification
  // try {
  //   obj = JSON.parse( ajax(base_url+'notification') );
  // }catch(e){

  // }
  
  // if(typeof obj != "undefined") jQuery.each( obj, function( key, value ) {
  //   jQuery.toast({
  //     text: value['notification'],
  //     icon: value['type'],
  //     loader: false,        // Change it to false to disable loader
  //   })
  // });
  //money
  jQuery('.money').simpleMoneyFormat();
}

function handle_image(selector = document){
  setTimeout(function() {
    jQuery(selector).find('img').each(function(){
    jQuery(this).attr('src',jQuery(this).data('src'));
    jQuery(this).removeAttr( "data-src" );
    });
  }, 300);
}

jQuery(window).on('load',function() { 
  setTimeout(function() {
    handle();
    handle_permission();
  }, 100);
});
// reload image after load page
jQuery(window).on('load',function() { 
  setTimeout(function() {
    handle_image();
  }, 4000);
});



jQuery(window).one('mouseenter',function(){
  jQuery(window).on('load',function(){
    
      handle_image();
    
  });
});
jQuery(window).one('touchstart',function() { 
  jQuery(window).on('load',function(){
    
      handle_image();
    
  });
});
jQuery(window).on('load',function(){
  jQuery(window).one('mouseenter',function(){
    
    handle_image();
    
  });
  jQuery(window).one('touchstart',function() { 
    
    handle_image();
    
  });
});
// reload javascript new content
jQuery(document).on('DOMSubtreeModified',".reload", function() {
  handle(this);
});