// Common script for control
'use strict';
// Global vars
var url = window.location.href,
    url = url ? url : document.URL,
    prz = url.match(/\/(member|planner|hired|editor|admin)\//);
window.isIE11 = !!window.MSInputMethodContext && !!document.documentMode;
// Errors
if(url.match('/fb.ru') && !url.match(/\/(article|post|news)\//)){
  window.onerror=function(r,e,o){
      var req =  new XMLHttpRequest();
      req.open('POST', '/home/xhr_jserror', true)
      req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      req.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
      req.withCredentials = true;
      req.send('page='+url+'&emsg='+r+'&file='+e+'&line='+o);
      return true;
  };
}
// Simple trim
String.prototype.st = function(){
    return this.replace(/^\s\s*|\s\s*$/g, '');
};
// Trim whitespaces
String.prototype.trimWs = function(){
    return this.replace(/^\s\s*|\s\s*$/g, '').replace(/\s\s*/g, ' ');
};
// Plan Text Trim - whitespaces, convert to lowercase, only letters and digits
String.prototype.trimPt = function(){
    return !this?this:this.toLowerCase().replace(/<[/a-zA-Z][^>]*>/g, ' ').replace(/&nbsp;/g, ' ').replace(/&amp;/g, ' & ').replace(/ё/ig, 'е').replace(/&[a-z]{1,8};/g, ' ').replace(/[^a-zа-я0-9]/ig, ' ').trimWs();
};
// Strip tags
String.prototype.stripTags = function(){
    var tmp = document.createElement("DIV");
    tmp.innerHTML = this;
    return this.textContent || this.innerText || "";
};
// Checking URL
String.prototype.isURL = function(){
    return /^https?:\/\/([^.]*\.)?[^\.]+\.[^\/]+\/?[^$]*/.test(this);
};
// Session
jQuery(document).ready(function($){
  window.sess = setInterval(function(){
    var оbj ={url:url, form:'login2'},
        lpf = $('#alert-login').length;
    if(!lpf&&prz) $.post('/xhr_ssc', оbj, function(r){eval(r)});
  }, 30000);
});
// Enabling scripts caching
jQuery.ajaxSetup({
    cache: true
});

jQuery(document).ready(function($){
// Common variables
  var $window = $(window),
      $body = $('body');

// Pull-out menu in member zone
  var $wrapper = $('#main'),
      $adminBurger = $('.js-burger'),
      $pushmenu = $('.js-pushmenu'),
      $pushmenuClose = $('.js-pushmenu-close');

  $adminBurger.on('click', function(e){
    e.preventDefault();
    e.stopPropagation();

    if($pushmenu.hasClass('is-visible')){
      hidePushmenu();
    } else{
      $pushmenu.addClass('is-visible');
      $body.addClass('has-overfix');
      $wrapper.css('left', $pushmenu.width());
    }
  });

  $pushmenuClose.on('click', function(e){
    e.preventDefault();
    hidePushmenu();
  });

  $pushmenu.on('click', function(e){
    e.stopPropagation();
  });

  $window.click(function(){
    hidePushmenu();
  });

  function hidePushmenu(){
    $pushmenu.removeClass('is-visible');
    $body.removeClass('has-overfix');
    $wrapper.css('left', 'auto');
  }
});

// Jquery functions
jQuery(document).ready(function($){
// Getting value and performing simple trim
    $.fn.extend({
        vst: function(){
            var val = (this).val();
            return $.type(val) === "string" ? val.st():val;
        }
    });
// ESC closes popup
    $(document).on('keyup', function(e){
        e.keyCode == 27 && $('.js-modal').length > 0 && closePopup();
        
        if (typeof modModal.top !== 'undefined') {
        	$(window).scrollTop(modModal.top);
		}
    });
// Override alert
    window.alert = function(msg){
        popup('alert2', msg);
    };
// Override confirm
    window.confirm = function(msg){
        // Remove previous hadlers
        $('body').off('click', '.js-modal-confirm');
        // Launch confirm popup
        popup('confirm2', msg);
    };
});

function checkXhrResponse(response){
    if(response == 'access denied'){
        popup('login'); return;
    }else if(response == 'permission denied'){
        alert('Доступ запрещен.');
        return false;
    }else if(typeof response !== 'string'){
        return true;
    }else if(response.substr(0,7) == 'Ошибка!'){
        alert(response);
        return false;
    }
    return response ? true : false;
}

function popup(type, postObj){
    if($('.js-modal').length > 0){
        closePopup();
    }

    var data = typeof postObj == 'string' ?{ message: postObj } : postObj,
        time = new Date().getTime();

    $.post('/alert/'+type+'?'+time, data, function(message){
        if(!checkXhrResponse(message)) return false;
        closePopup();
        $('body').append(message);
        showPopup();
    });
}

function showPopup(){
    var $modal = $('.js-modal');

    shadowOn();
    if(!$modal.hasClass('is-visible')){
        $modal.addClass('is-visible');
    }
    $('body').addClass('no-scroll');
    $('.js-overlay, .js-modal-close').on('click', function(){
        closePopup();
    });
}

function closePopup(){
    shadowOff();
    $('.js-modal').remove();
    $('body').removeClass('no-scroll');
}

function shadowOn(){
    if($('.js-overlay').length === 0){
        $('body').append('<div class="overlay js-overlay"></div>');
    }
}

function shadowOff(){
    $('.js-overlay').remove();
}

function startLoader(){
    shadowOn();
    if(!$('.js-spinner').length > 0){
        $('body').append('<div class="spinner spinner--over js-spinner"></div>');
    }
}

function stopLoader(){
    shadowOff();
    $('.js-spinner').remove();
}

function generateUUID(){
    var d = new Date().getTime();
    if(typeof performance !== 'undefined' && typeof performance.now === 'function'){
        d += performance.now(); //use high-precision timer if available
    }
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c){
            var r = (d+Math.random() * 16) % 16 | 0;
            d = Math.floor(d / 16);
            return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
}

// Module Modal
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function(obj){ return typeof obj; } : function(obj){ return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var modModal = function(){

  var init = function init(settings){
    modModal.config ={
      type: null,
      title: null,
      content: null,
      width: null,
      hasClose: false,
      hasControl: false,
      hasScroll: false,
      urlContent: null,
      action:{
        name: null,
        callback: null
      },
      top: null,
      isMedia: null
    };

    $.extend(modModal.config, settings);
    modModal.top = modModal.config.top || $(window).scrollTop();
    remove();
    show(settings);
    modModal.bindEvents();
  };

  var create = function create(props){
    var classNameType = 'is-error';
    var classNameIE = '';
    var title = '';
    var hasClose = true;
    var hasScroll = "";
    var classAjax = "";
    var content = void 0,
        action = void 0,
        hasControl = void 0,
        isMedia = void 0,
        classOverlay = void 0,
        width = void 0;

    if(!props){
      title = '<div class="modal__head">\u0412\u043D\u0438\u043C\u0430\u043D\u0438\u0435</div>';
      content = 'Ошибка';
    }

    if(typeof props == 'string'){
      content = props;
      classOverlay = 'js-overlay';
    }

    if((typeof props === 'undefined' ? 'undefined' : _typeof(props)) == 'object'){
      classNameIE = isIE11 ? 'modal--ie' : '';
      classNameType = props.type ? 'is-'+props.type : '';
      content = props.content ? ''+props.content : '';
      title = props.title ? '<div class="modal__head">'+props.title+'</div>' : '';
      action = props.action ? '<button class="button button--action button--right button--adaptive js-modal-action">'+props.action.name+'</button>' : '';
      hasScroll = props.hasScroll ? ' has-scroll' : '';
      isMedia = props.isMedia ? ' modal--media' : '';
      hasClose = props.hasClose === true ? true : false;
      classOverlay = props.hasClose === 'disabled' ? '' : 'js-overlay';
      hasControl = props.hasControl ? true : false;
      width = props.width ? 'style="width: '+props.width+'px;"' : '';
      if(props.urlContent){
        classAjax = 'js-modal-body';
        $.get(props.urlContent).done(function(data){
          var $el = $('.'+classAjax);
          $el.hide();
          $el.append(data);
          if(props.onload) props.onload();
          $el.show();
          $(window).trigger('calc');
        });
      }
    }

    $('body').append('<div class="overlay '+classOverlay+'"></div>');

    return '<div class="modal '+classNameType+classNameIE+hasScroll+isMedia+' is-visible js-modal" '+width+'>\n'+
      (hasClose ? '<button class="modal__close js-modal-close">×</button>' : '')+'\n'+
      title+'\n <div class="modal__body js-modal-notice '+classAjax+'"> '+content+' </div>\n'+
      (hasControl ? '<div class="modal__control">'+'<button class="button button--adaptive js-modal-close">Отмена</button>'+action : '')+
      '\n<div class="js-modal-bottom"></div></div>\n</div>';
  };

  var show = function show(settings){
    $('body').addClass('no-scroll').append(modModal.create(settings));
    $('.js-modal').find('img').on('load', function(e){
      if(($(e.target).height() + 80) > $(window).height()){
        $('.js-modal').addClass('is-long');
        $('body').removeClass('no-scroll');
        $(window).scrollTop(0);
      }
    });
  };

  var remove = function remove(){
    $('.js-modal, .js-overlay').remove();
    $('body').removeClass('no-scroll');
    $(window).scrollTop(modModal.top);
  };

  var post = function post(type, postObj){
      if($('.js-modal').length){
          remove();
      }

      var data = typeof postObj == 'string' ? { message: postObj } : postObj,
          time = new Date().getTime();

      $.post('/alert/'+type+'?'+time, data, function(message){
          if(!checkXhrResponse(message)) return false;
          $('body').addClass('no-scroll').append(message+'<div class="overlay js-overlay"></div>');
          modModal.bindEvents();
      });
  };

  return{
    init: init,
    remove: remove,
    create: create,
    post: post,
    bindEvents: function bindEvents(){
      var $window = $(window),
          $body = $('body'),
          $modal = $('.js-modal'),
          callback = modModal.config ? modModal.config.action.callback : null,
          hasScroll = modModal.config ? modModal.config.hasScroll : null;
      $('.js-overlay, .js-modal-close').on('click', remove);
      $('.js-modal-action').on('click', callback);
      $window.on('calc resize', function(){
        var $bottomOfModal = $('.js-modal-bottom'),
            bottomVal = $bottomOfModal.length ? $bottomOfModal.offset().top : 0;

      // Hack for modal on iOS
        if (!!navigator.platform && /iPad|iPhone/.test(navigator.platform)) {
          $modal.addClass('is-ios');
        }

        if(hasScroll) return;
        if((bottomVal + $bottomOfModal.height()) > $window.height()){
          $modal.addClass('is-long');
          $body.removeClass('no-scroll');
          $window.scrollTop(0);
        }else{
          $modal.removeClass('is-long');
        }
      });
      $window.trigger('calc');
    }
  };
}();

modModal.bindEvents();

// Module Notice
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function(obj){ return typeof obj; } : function(obj){ return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var modNotice = function(){

  var init = function init(settings){
    modNotice.config ={
      wrapSelector: '.js-notice-wrap',
      type: null,
      message: null
    };
    $.extend(modNotice.config, settings);

    var wrap = $(''+modNotice.config.wrapSelector);

    switch(typeof settings === 'undefined' ? 'undefined' : _typeof(settings)){
      case 'object':
        wrap.prepend(modNotice.create(settings.type, settings.message));
        break;
      case 'string':
        wrap.prepend(modNotice.create('error', settings));
        break;
      default:
        wrap.prepend(modNotice.create('error', 'Ошибка'));
    }
    modNotice.bindEvents();
  };

  var remove = function remove(){
    $('.js-notice-body').remove();
  };

  var closeTargetNotice = function closeTargetNotice(){
    var $t = $(this),
        $holder = $t.closest('.js-notice-body');
    $holder.addClass('has-fading');
    setTimeout(function(){
      $holder.remove();
    }, 400);
  };

  return{
    init: init,
    remove: remove,
    create: function create(type, message){
      var classNameType = type ? 'notice--'+type : '';
      var content = message ? message : '...';

      remove();
      return '<div class="notice '+classNameType+' is-visible js-notice-body">\n                <div class="notice__text">'+content+'</div>\n                <div class="notice__close js-notice-close"></div>\n              </div>';
    },
    bindEvents: function bindEvents(){
      $('.js-notice-body').on('click', '.js-notice-close', closeTargetNotice);
    }
  };
}();

modNotice.bindEvents();


// Module Push
var modPush = function(){

  var init = function init(settings){
    modPush.config = {
      message: null,
      position: null,
      clear: true
    };
    $.extend(modPush.config, settings);

    var $holder = $('.js-pushbox'),
        classNamePos = settings.position === 'top' ? 'pushbox--top' : '';

    if($holder.length){
      $holder.addClass(classNamePos);
    }else{
      $('body').append('<div class="pushbox '+classNamePos+' js-pushbox"></div>');
      $holder = $('.js-pushbox');
    }

    if((settings.clear == undefined || settings.clear) && $('.js-pushbox-item').length <= 4){
      setTimeout(function () {
        modPush.remove(0);
      }, 3500);
    }else{
      modPush.remove(0);
    }

    switch(typeof settings){
      case 'object':
        $holder.append(modPush.create(settings.message));
        break;
      case 'string':
        $holder.append(modPush.create(settings));
        break;
      default:
        $holder.append(modPush.create('Выполнено'));
    }
    modPush.bindEvents();
  };

  var removeAll = function removeAll(){
    $('.js-pushbox-item').remove();
  };

  var remove = function remove(index){
    $('.js-pushbox-item').eq(index).remove();
  };

  var removeTargetPush = function removeTargetPush(){
    var $t = $(this),
        $holder = $t.closest('.js-pushbox-item');

    $holder.addClass('has-hidden');
    setTimeout(function(){
      $holder.remove();
    }, 300);
  };

  return {
    init: init,
    remove: remove,
    removeAll: removeAll,
    create: function create(message){
      return '<div class="pushbox__item js-pushbox-item">'+
          '<div class="pushbox__body">'+message+'</div>'+
          '<button class="pushbox__close js-pushbox-close"></button>'+
        '</div>';
    },
    bindEvents: function bindEvents(){
      $('.js-pushbox-item').on('click', '.js-pushbox-close', removeTargetPush);
    }
  };
}();

modPush.bindEvents();

// Utilites
var utils = function(){

  var validateEmail = function validateEmail(email){
    var regEmail = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

    return regEmail.test(email);
  };

// Error processing
  var showError = function showError(message, targetSel, wrapSel){
    requireElError(targetSel, wrapSel)
      .addClass('is-error')
      .attr('data-msg', message);
  };

  var displayError = function displayError(message, targetSel, wrapSel){
    requireElError(targetSel, wrapSel)
      .addClass('is-error')
      .append('<div class="field__error js-field-error">'+message+'</div>');
  };

  var showErrorList = function showErrorList(arr, targetSel, qna){
    var target = targetSel || '.js-editor-msg',
        qnaLink = qna || '/member/qna',
        tmpl =
        '<div class="field__msg-title">'+
          '<svg class="field__msg-icon">'+
            '<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/misc/i/d/set_icons_admin.svg#warning"></use>'+
          '</svg>'+
          'Ошибки в статье'+
        '</div>',
        footer = '<div class="field__msg-footer">Более подробная информация о требованиях к Статьям - «<a href="'+qnaLink+'" target="_blank">Вопросы и ответы</a>»</div>',
        items = '';

    arr.forEach(function(el){
      var msg;
      if(typeof el == 'object'){
        msg = '<div class="field__msg-left"><img src="'+el.img+'" class="field__msg-img"></div>'+
          '<div class="field__msg-src">'+el.text+'</div>';
      }else{
        msg = el;
      }
      items += '<div class="field__msg-wrap">'+msg+'</div>';
    });
    $(target).html('<div class="field__msg is-visible">'+tmpl+items+footer+'</div>');
  };

  var clearError = function clearError(targetSel, wrapSel){
    requireElError(targetSel, wrapSel)
      .removeClass('is-error')
      .attr('data-msg', '')
      .children('.js-field-error').remove();
  };

  var clearErrorList = function clearErrorList(targetSel){
    var target = targetSel || '.js-editor-msg';

    $(target).empty();
  };

  var reflowAnimation = function(className, elementAnimate){
    if(!elementAnimate) return;
    elementAnimate.classList.remove(className);
    void elementAnimate.offsetWidth;
    elementAnimate.classList.add(className);
  }

  function requireElError(targetSel, wrapSel){
    var wrap = wrapSel || '.js-field';

    return $(targetSel).closest(wrap);
  }

  return {
    validateEmail: validateEmail,
    showError: showError,
    displayError: displayError,
    showErrorList: showErrorList,
    clearError: clearError,
    clearErrorList: clearErrorList,
    reflowAnimation: reflowAnimation
  };
}();