var $ = jQuery;

/////////////////////////////////////////////////////////////

$(document).on("keyup", '#unify_domain_name', function () {
    if ($(this).val().replace(/[^.]/g, "").length < 2){
    	message = "Please provide a valid domain";
    	$("#unify_domain_name-error").remove();
    	$("#unify_domain_name").after('<label id="unify_domain_name-error" class="text-danger" for="unify_domain_name">'+message+'.</label>');
  	}else{
   		$("#unify_domain_name-error").remove();
  	}
});

$(document).on("keyup", '#unify_pro_license_key', function () {
    if ($(this).val()===''){
    	message = "Unify Pro License Key";
    	$("#unify_pro_license_key-error").remove();
    	$("#unify_pro_license_key").after('<label id="unify_pro_license_key-error" class="text-danger" for="unify_pro_license_key">'+message+' is a required field.</label>');
  	}else{
   		$("#unify_pro_license_key-error").remove();
  	}
});

$(document).ready(function(){

  $('#submit_cancellation').click(function(){
    $.validator.addMethod("customemail", 
        function(value, element) {
            return /^(([^<>()\[\]\\.,;:\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,}))$/.test(value);
        }, 
        ""
    );

    
    $("#request_cancellation_form").validate({ // initialize the plugin
      rules: {
        first_name: {
          required: true
        },
        last_name: {
          required: true
        },
        email: {
          required: true,
          customemail: true,
        },
        mobile: {
          required : true,
          number: true,
          minlength: 10,
          maxlength: 15,
        },
        reason: {
          required: true
        },
      },
      messages :{
        first_name: {
          required: 'First Name is a required field.'
        },
        last_name: {
          required: 'Last Name is a required field.'
        },
        email: {
          required: 'Email Address is a required field.',
          email: 'Please provide a valid email address.',
        },
        mobile: {
          required : 'Phone Number is a required field.',
          digits: 'Please provide a valid phone number.'
        },
        reason: {
          required: 'Comment is a required field.'
        },
      },
      errorClass:'error',
      errorPlacement: function (error, element) {
        $(this).addClass('error');
      }
    });
    
    if($("#request_cancellation_form").valid()){
      requestCancellation();
      return true;
    }
    return false;
  });
})

function redeemLicense(){

	let proLicenseKey = $("#unify_pro_license_key").val();
	let domainName = $("#unify_domain_name").val(); 

	let paramArray = []; 
	paramArray['license-key'] = proLicenseKey; 
	paramArray['domain-name'] = domainName;

	var v = valid_pro_license_fields();
    if (v) {
      ajax_to_validate_license(paramArray);
    }	
}



function valid_pro_license_fields() {
    let valid = true;
    let message = '';
    let proLicenseKey = $("#unify_pro_license_key").val();
	let domainName = $("#unify_domain_name").val(); 

   	if (proLicenseKey === '') {
       valid = false;
       message = "Unify Pro License Key";
       $("#unify_pro_license_key-error").remove();
       $("#unify_pro_license_key").after('<label id="unify_pro_license_key-error" class="text-danger" for="unify_pro_license_key">'+message+' is a required field.</label>');
    }


    if (domainName === '') {
	    valid = false;
	    message = "Domain";
	    $("#unify_domain_name-error").remove();
	    $("#unify_domain_name").after('<label id="unify_domain_name-error" class="text-danger" for="unify_domain_name">'+message+' is a required field.</label>');
	}

	if (domainName !== '' && domainName.replace(/[^.]/g, "").length < 2){
		valid = false;
    	message = "Please provide a valid domain name";
    	$("#unify_domain_name-error").remove();
    	$("#unify_domain_name").after('<label id="unify_domain_name-error" class="text-danger" for="unify_domain_name">'+message+'. </label>');
  	}
      
    if (valid) {
    	return true;
    } else {
        return false;
    }
}


function ajax_to_validate_license(param){
  var testing_domain = localStorage.getItem("testing_domain");

	$.ajax({
		beforeSend: function () {
			$('.overlayDiv').show();
		},
		data: {
			'action': 'validate_pro_license',
			'unify_pro_license_key' : param['license-key'],
			'unify_domain' : param['domain-name'],
      'testing_domain' : testing_domain,
		},
		dataType: 'json',
		type: 'POST',
		url: ajaxurl,
		success: function (response) {
			 var msg = response.msg;
			 var color = "";
			 var response_code = response.status;
			 var redirect_url = response.redirect;



			 if(response_code == 0){
			 	msg = msg+" <i class='fa fa-exclamation-triangle' aria-hidden='true'></i>";color = "red";
			  $(".validated_msg").css({"position": "absolute","bottom": "12px","left":0});
       }else{
			 	$('#unify_pro_license_key').prop('readonly', true);
			 	msg = msg+" <i class='fa fa-check-circle' aria-hidden='true'></i>";color = "green";					
        closeModal('proLicenseModal');
        openModal('proLicenseSuccessModal');
			 }
       $(".validated_msg").html(msg);$(".validated_msg").css("color",color);
       $(".validated_msg").css("display",'inline-block');
       
       $(".validated_msg").delay(5000).fadeOut('slow');
			 
		},
		error: function (response){
			color = "red";msg = "Invalid Credential <i class='fa fa-exclamation-triangle' aria-hidden='true'></i>";
			$(".validated_msg").html(msg);
			$(".validated_msg").css("color",color);
			$(".validated_msg").css("display",'inline-block');
			$('.validated_msg').delay(5000).fadeOut('slow');
		},
		complete: function (response) {
      		$('.overlayDiv').hide(); 
     	}
	});
}

function openModal(ele){
        var element = document.getElementById(ele); 
        element.classList.add("show-flex");
    }

function closeModal(ele){
        var element = document.getElementById(ele); 
        element.classList.remove("show-flex");
    }


/************************************Canvas JS**********************************/
var canvas, stage, exportRoot, anim_container, dom_overlay_container, fnStartAnimation;
function init() {
  canvas = document.getElementById("canvas");
  anim_container = document.getElementById("animation_container");
  dom_overlay_container = document.getElementById("dom_overlay_container");
  var comp=AdobeAn.getComposition("5AE0EAACF0C348F0B55971AF7A711973");
  var lib=comp.getLibrary();
  createjs.MotionGuidePlugin.install();
  var loader = new createjs.LoadQueue(false);
  loader.addEventListener("fileload", function(evt){handleFileLoad(evt,comp)});
  loader.addEventListener("complete", function(evt){handleComplete(evt,comp)});
  var lib=comp.getLibrary();
  loader.loadManifest(lib.properties.manifest);
}
function handleFileLoad(evt, comp) {
  var images=comp.getImages();  
  if (evt && (evt.item.type == "image")) { images[evt.item.id] = evt.result; }  
}
function handleComplete(evt,comp) {
  //This function is always called, irrespective of the content. You can use the variable "stage" after it is created in token create_stage.
  var lib=comp.getLibrary();
  var ss=comp.getSpriteSheet();
  var queue = evt.target;
  var ssMetadata = lib.ssMetadata;
  for(i=0; i<ssMetadata.length; i++) {
    ss[ssMetadata[i].name] = new createjs.SpriteSheet( {"images": [queue.getResult(ssMetadata[i].name)], "frames": ssMetadata[i].frames} )
  }
  exportRoot = new lib.unifywordpresstransfer_HTML5Canvas();
  stage = new lib.Stage(canvas);  
  //Registers the "tick" event listener.
  fnStartAnimation = function() {
    stage.addChild(exportRoot);
    createjs.Ticker.framerate = lib.properties.fps;
    createjs.Ticker.addEventListener("tick", stage);
  }     
  //Code to support hidpi screens and responsive scaling.
  AdobeAn.makeResponsive(true,'both',false,1,[canvas,anim_container,dom_overlay_container]);  
  AdobeAn.compositionLoaded(lib.properties.id);
  fnStartAnimation();
}
/*************************************Canvas JS**********************************/

function downgrade(){

$.ajax({
    beforeSend: function () {
      $('.progress-text').html('100%');
      $('.progress-bar').addClass('w-100');
      $('.product-info').html('Rolling back all settings…'); 
      init();
      closeModal('downgradeModal');
      $("#transeferringModal").addClass("downgrade");
      openModal('transeferringModal');
    },
    data: {
      'action': 'downgrading',
      'unify_plugin_downgrade': '1',
      '_wpnonce': unifySettings.downgrade_nonce,
    },
    dataType: 'json',
    type: 'POST',
    url: ajaxurl,
    success: function (response) {   
          setTimeout(function(){
            $('.progress-bar').removeClass('w-100');
            $('.progress-bar').addClass('w-75');
            $('.progress-text').html('75%'); 
          }, 2000);
          setTimeout(function(){
            $('.progress-bar').removeClass('w-75');
            $('.progress-bar').addClass('w-50');
            $('.progress-text').html('50%'); 
          }, 6000);  
            setTimeout(function(){
              $('.progress-bar').removeClass('w-50');
              $('.progress-bar').addClass('w-25');
              $('.progress-text').html('25%');  
            }, 12000);  
            setTimeout(function(){
              $("#transeferringModal").removeClass("downgrade");
              closeModal('transeferringModal');
              openModal('rollBackModal'); 
            }, 13000);
        },
        error: function (response){
          // color = "red";msg = "Invalid Credential <i class='fa fa-exclamation-triangle' aria-hidden='true'></i>";
          // $(".validated_msg").html(msg);
          // $(".validated_msg").css("color",color);
          // $(".validated_msg").css("display",'inline-block');
          // $('.validated_msg').delay(5000).fadeOut('slow');
        },
        complete: function (response) {
              //$('.overlayDiv').hide(); 
          }
  });


  

}
//function startTransefer(param = 2){
function startTransefer(){
  var testing_domain = localStorage.getItem("testing_domain");

	$.ajax({
		beforeSend: function () {
			init();
			closeModal('proLicenseSuccessModal');
			openModal('transeferringModal');
		},
		data: {
			'action': 'configurationDataCollection',
      'from-button':'1',
      'testing_domain':testing_domain,
		},
		dataType: 'json',
		type: 'POST',
		url: ajaxurl,
		success: function (response) {
			const status = response.status;
      const redirect_url = response.redirect;
      const msg = response.msg;
            var cls = '';
            if(status == 1){
                setTimeout(function(){
                     $('.progress-bar').removeClass('w-25');
                     $('.progress-bar').addClass('w-50');
                     $('.progress-text').html('50%'); 
                     $('.product-info').html('Transferring your shipping information…'); 
                 }, 2000);
                    setTimeout(function(){
                     $('.progress-bar').removeClass('w-50');
                     $('.progress-bar').addClass('w-75');
                     $('.progress-text').html('75%'); 
                     $('.product-info').html('Transferring all your settings…'); 
                 }, 6000);  
                    setTimeout(function(){
                     $('.progress-bar').removeClass('w-75');
                     $('.progress-bar').addClass('w-100');
                     $('.progress-text').html('100%');  
                 }, 12000);  
                setTimeout(function(){
                  closeModal('transeferringModal');
				          openModal('transeferCompleteModal'); 
                  
             }, 13000);  
                
            }else{
              closeModal('transeferringModal');
              $(".transfer_fail").html(msg);
              openModal('TransferFailedModal');
            }
			
		},
		error: function (response){
			closeModal('transeferringModal');
      openModal('TransferFailedModal');
		},
		complete: function (response) {
     	}
	});
}


/**
 * truncate unnecessery components from endpoint
 */
function validate_endpoint(v){
   var url = v.value;
   checked_url = url.replace(/^(?:https?:\/\/)?(?:www\.)?/i, "").split('/')[0];
   $("#unify_domain_name").val(checked_url);  
}


function requestCancellation(){
  $.ajax({
    beforeSend: function () {
      $('.overlayDiv').show();
    },
    data: {
      'action': 'requestCancellation',
      'x': $('#request_cancellation_form').serialize()
    },
    dataType: 'json',
    type: 'POST',
    url: ajaxurl,
    success: function (response) {
      const status = response.status;
      const msg = response.msg;
      const color = "green";
      if(status == 1){
        $(".request_cancel_form").css("display","none");
        $(".upgrade-request").css("display","flex");
      }
      $(".validated_msg").html(msg);$(".validated_msg").css("color",color);
      $(".validated_msg").css("display",'inline-block');
      $(".validated_msg").delay(5000).fadeOut('slow');
    },
    error: function (response){
      color = "red";msg = "Some error occured <i class='fa fa-exclamation-triangle' aria-hidden='true'></i>";
      $(".validated_msg").html(msg);
      $(".validated_msg").css("color",color);
      $(".validated_msg").css("display",'inline-block');
      $('.validated_msg').delay(5000).fadeOut('slow');
    },
    complete: function (response) {
          $('.overlayDiv').hide(); 
      }
  });
}



