$(document).ready(function() {
  function saveSettings() {
    OC.msg.startSaving('#registration_settings_msg');
    $.ajax({
      url: OC.generateUrl('/apps/registration/settings'),
      type: 'POST',
      data: $('#registration_settings_form').serialize(),
      success: function(data){
         
        OC.msg.finishedSaving('#registration_settings_msg', data);
        //新增域名后刷新页面
        if($('input[name="appPackage"]').val()){
            window.location.reload(); 
        }
        
      },
      error: function(data){
         
        OC.msg.finishedError('#registration_settings_msg', data.responseJSON.data.message);
      }
    });
  }
 
  $('#registration_settings_form').change(saveSettings);
  $('#registration').keypress(function(event) {
    if (event.keyCode === 13) {
      event.preventDefault();
    }
  });
  /*验证码确认框*/
  OC.yzCodeConfirmation = {
	callback: null,
	pageLoadTime: null,
	init: function() {
		//$('.password-confirm-required').on('click', _.bind(this.requirePasswordConfirmation, this));
		//this.pageLoadTime = moment.now();
	},
        requiresPasswordConfirmation : function(){
            return true;
        },
	/**
	 * @param {function} callback
	 */
	requirePasswordConfirmation: function(callback, options, rejectCallback) {
		options = typeof options !== 'undefined' ? options : {};                
		var defaults = {
			title: t('registration','Request activation'),
			text: t( 'registration', 'Please enter and confirm the verification code' ),
			confirm: t('core', 'Confirm'),
			label: t('registration','Verification Code'),
			error: '',
		};

		var config = _.extend(defaults, options);

		var self = this;

		if (this.requiresPasswordConfirmation()) {
			OC.dialogs.prompt(
				config.text,
				config.title,
				function (result, password) {
					if (result && password !== '') {
						self._confirmPassword(password, config);
					} else if (_.isFunction(rejectCallback)) {
						rejectCallback()
					}
				},
				true,
				config.label,
				false
			).then(function() {
				var $dialog = $('.oc-dialog:visible');
				$dialog.find('.ui-icon').remove();
				$dialog.addClass('password-confirmation');
				if (config.error !== '') {
					var $error = $('<p></p>').addClass('msg warning').text(config.error);
				}
				$dialog.find('.oc-dialog-content').append($error);
				$dialog.find('.oc-dialog-buttonrow').addClass('aside');
        $dialog.css({width:"350px"})
				var $buttons = $dialog.find('button');
				$buttons.eq(0).hide();
				$buttons.eq(1).text(config.confirm);
			});
		}

		this.callback = callback;
	},

	_confirmPassword: function(password, config) {
		var self = this;
		$.ajax({
			url: OC.generateUrl('/apps/registration/domainPanel'),
			data: {
        enews: 'confirm',
				password: password
			},
			type: 'POST',
			success: function(response) {
				 
				if (_.isFunction(self.callback)) {
					self.callback( password );
				}
			},
			error: function(jqXHR, textStatus, errorThrown) {
        console.log(jqXHR);                         
				config.error = t('registration', 'Failed to authenticate, try again');
				OC.yzCodeConfirmation.requirePasswordConfirmation(self.callback, config);
			}
		});
	}
};
  /*操作域名的接口类*/
  function checkDomainIsActive(index, domain){
      var nostr = $("tr[data-key='"+index+"']").data('nostr');
      $.ajax({
         url: OC.generateUrl('/apps/registration/domainPanel'),
         type: 'POST',
         data: "enews=validateLocalUrl&domain="+domain,
         success: function(data){  
           
           var msg = $('<p><font style="color:red">'+t('registration','not active')+' | </font><a class="msactive"><font style="color:blue">'+t('registration','Immediate activation')+'</font></a></p>');
           if(data.ret){
               if(data.ret.data.mac == nostr){
                   msg = $('<p><font style="color:green">'+t('registration','Activated')+'</font></p>');
                   
                   if(index==0){
                       msg.append('<font style="color:#999">[默认]</font>');
                   }else{
                       msg.append('<a class="needdig"><font> 设为默认</font></a>');
                   }
                 
                 }
              
               $("tr[data-key='"+index+"']").attr('data-regmac', data.ret.data.mac);
           }           
           
           //记录下返回的mac
           $("tr[data-key='"+index+"']").find(".dstatus").html(msg);            
           //设为默认 setDefault
           $("tr[data-key='"+index+"']").find(".needdig").click( function(){
               
              // if(confirm( t('registration','确定设置为默认吗？'))){
                  getCode( index,domain, setDefault );
              // }
           });
           //激活
           $("tr[data-key='"+index+"']").find(".msactive").click( function(){
               //激活按钮
              // if(confirm( t('registration','Are you sure you want to activate this domain name?'))){
                  getCode( index,domain, activeDomain );
              // }
           })
         },
         error: function(data){          
           OC.msg.finishedError('#registration_domain_msg', data.responseJSON.data.message);
         }
       });      
  }
  function getCode(index, domain, cabfunc ){
      var msg = $(' <font style="color:black">'+t('registration','Loading…')+'</font> ');
      $("tr[data-key='"+index+"']").find(".msactive").html(msg);  
      $.ajax({
         url: OC.generateUrl('/apps/registration/domainPanel'),
         type: 'POST',
         data: "enews=getCode&domain="+domain,
         success: function(data){ 
            if(!data.ret){
                msg = $(' <font style="color:blue">'+t('registration','Domain name activation failed')+'</font> ');
                $("tr[data-key='"+index+"']").find(".msactive").html(msg); 
                return false;
            }            
            if(data.ret.error.errorCode==0){
                /*检测收到的激活码 */
                 loaclCode(index, domain, cabfunc)
            }else{
               msg = $(' <font style="color:blue">'+t('registration','Domain name activation failed')+'</font> ');
                $("tr[data-key='"+index+"']").find(".msactive").html(msg); 
                return false;  
            }
         },
         error: function(data){          
           OC.msg.finishedError('#registration_domain_msg', data.responseJSON.data.message);
         }
       });  
  }
  function loaclCode(index, domain, cbFunc){
       $.ajax({
         url: OC.generateUrl('/apps/registration/domainPanel'),
         type: 'POST',
         data: "enews=loaclCode&domain="+domain,
         success: function(data){ 
             /*显示激活码 */
             if(data.ret){
                 var msg = '<font style="color:red">'+t('registration','Verification Code')+data.ret.data+'</font>';
                $("tr[data-key='"+index+"']").find(".msactive,.needdig").html(msg);
                if( _.isFunction(cbFunc)){
                    cbFunc(index, domain);
                    /*执行激活操作*/
                }
                
            }else{
              var msg = '<font style="color:red">Lost Url.</font>';
              $("tr[data-key='"+index+"']").find(".msactive,.needdig").html(msg);
            }
         },
         error: function(data){          
           OC.msg.finishedError('#registration_domain_msg', data.responseJSON.data.message);
         }
       });  
  }
  function activeDomain(index, domain){      
      //如果输入验证码正确就 提交激活请求
      var key = $("tr[data-key='"+index+"']").data('key');
      var domain = $("tr[data-key='"+index+"']").data('domain');
      var nostr = $("tr[data-key='"+index+"']").data('nostr');
      var regmac = $("tr[data-key='"+index+"']").data('regmac');
     
        OC.yzCodeConfirmation.requirePasswordConfirmation( function( password ){
            $.ajax({
                url: OC.generateUrl('/apps/registration/domainPanel'),
                type: 'POST',
                data: {
                    enews: 'activeDomain', domain: domain, nostr: nostr, regmac: regmac,
                    password: password, idx: key
                },  
                success: function(data){ 
                    if(data.ret){
                       var msg = $('<p><font style="color:green">'+t('registration','Successful activation')+'</font></p>');                                    
                   }else{
                       var msg = $('<p><font style="color:black">'+t('registration','Activation failed')+'</font></p>');
                   }
                    $("tr[data-key='"+index+"']").find(".dstatus").html(msg);        
                },
                error: function(data){          
                  OC.msg.finishedError('#registration_domain_msg', data.responseJSON.data.message);
                }
              });  
            
        },/*修改 激活文字*/
        {text: t( 'registration', 'Please enter and confirm the verification code' )           
             +' ,' + t( 'registration', 'To complete the activation of {domain} domain name.', {domain:domain} )
        }
       );
			 
      //弹出 验证密码框
  }
  //设置为默认域名
  function setDefault(index, domain){
    var key = $("tr[data-key='"+index+"']").data('key');
      var domain = $("tr[data-key='"+index+"']").data('domain');
      var nostr = $("tr[data-key='"+index+"']").data('nostr');
      var regmac = $("tr[data-key='"+index+"']").data('regmac');
     
        OC.yzCodeConfirmation.requirePasswordConfirmation( function( password ){
            $.ajax({
                url: OC.generateUrl('/apps/registration/domainPanel'),
                type: 'POST',
                data: {
                    enews: 'setDefault', domain: domain,   password: password, idx: key
                },  
                success: function(data){ 
                    if(data.ret){
                       var msg = $('<p><font style="color:green">'+t('registration','Saved')+'</font></p>');                                    
                   }else{
                       var msg = $('<p><font style="color:black">'+t('registration','Activation failed')+'</font></p>');
                   }
                    $("tr[data-key='"+index+"']").find(".dstatus").html(msg);
                    setTimeout( function(){ window.location.reload();}, 500);
                },
                error: function(data){          
                  OC.msg.finishedError('#registration_domain_msg', data.responseJSON.data.message);
                }
              });  
            
        }, {text: t( 'registration', 'Please enter and confirm the verification code' ) 
                   +' ,' + t( 'registration', 'To complete setting {domain} as the default domain name.', {domain:domain} )
        });   
  }
  function editDomain(index, modify){
      var domain = $("tr[data-key='"+index+"']").data('domain'); 
      var regmac = $("tr[data-key='"+index+"']").data('regmac');
      
      OC.msg.startSaving('#registration_domain_msg');
        $.ajax({
         url: OC.generateUrl('/apps/registration/domainPanel'),
         type: 'POST',
         data: {
             enews: 'editDomain',idx: index,  domain: domain, newdomain: modify,
             regmac: regmac
         },  
         success: function(data){             
           OC.msg.finishedSaving('#registration_domain_msg', data);
           window.location.reload();
         },
         error: function(data){          
           OC.msg.finishedError('#registration_domain_msg', data.responseJSON.data.message);
         }
       }); 
  }
  function deleteDomain(index,domain){
     var key = $("tr[data-key='"+index+"']").data('key');
      var domain = $("tr[data-key='"+index+"']").data('domain');
      var nostr = $("tr[data-key='"+index+"']").data('nostr');
      var regmac = $("tr[data-key='"+index+"']").data('regmac');
     
        OC.yzCodeConfirmation.requirePasswordConfirmation( function( password ){
            OC.msg.startSaving('#registration_domain_msg');
            $.ajax({
                url: OC.generateUrl('/apps/registration/domainPanel'),
                type: 'POST',
                data: {
                    enews: 'delete', domain: domain,   password: password, idx: key
                },  
                success: function(data){ 
                  $("tr[data-key='"+index+"']").remove();    
                  OC.msg.finishedSaving('#registration_domain_msg', data);
                },
                error: function(data){          
                  OC.msg.finishedError('#registration_domain_msg', data.responseJSON.data.message);
                }
              });  
            
        }, {text: t( 'registration', 'Please enter and confirm the verification code' ) 
                   +' ,' + t( 'registration', 'To complete deleted {domain} domain name.', {domain:domain} )
        });     
      
  }
  function _deleteDomain(index, domain){
      var regmac = $("tr[data-key='"+index+"']").data('regmac');
     
      OC.msg.startSaving('#registration_domain_msg');
        $.ajax({
         url: OC.generateUrl('/apps/registration/domainPanel'),
         type: 'POST',
         data: "enews=delete&domain="+domain + "&regmac="+regmac,
         success: function(data){  
           $("tr[data-key='"+index+"']").remove();     
           
           OC.msg.finishedSaving('#registration_domain_msg', data);
         },
         error: function(data){          
           OC.msg.finishedError('#registration_domain_msg', data.responseJSON.data.message);
         }
       }); 
      
  }
  /*检测 域名是否激活过 */
  var $trs = $("table.domaintable").find("tbody").find('tr');
  $trs.each(function(i){
      $tr = $(this);
      var key = $tr.data('key');     
      var domain = $tr.data('domain');
      checkDomainIsActive(key, domain);
      //可编辑
      $tr.find('.edit').click(function(){
          if( $(this).parents('tr') .data('key') == 0){
             return false;             
          }
          if($(this).find('input') .length){
              return false;
          }
          var host = $(this).html();
          var input = $('<input name="ehost" value="'+host+'" type="text"/>');
          $(this).html(input);
          $(this).find('input').addClass('w50').focus();
          input.blur(function(e){
              e.preventDefault();
              var vh = $(this).val();
              var key =  $(this).parents('tr') .data('key');
              $(this).parent('.edit').html( vh);
              editDomain(key, vh);
              
          });
          
      });
      //删除
      $tr.find('.ddelete').click(function(){ 
          var tr = $(this).parents("tr");
          var domain = tr.data('domain');
          var key = tr.data('key');
          var nostr = tr.data('nostr');
          var regmac = tr.data('regmac');
          console.log(nostr + '=='+regmac)
          //if(confirm( t('registration','Are you sure you want to delete this domain name?')) ){
          if(nostr == regmac){
               getCode( key ,domain, deleteDomain ); 
          }else{
              _deleteDomain(key ,domain)
          }
              
         // }
          
      })
      
      //
  })
  
});
