
let loadingTime = 5000;
let addViewTime = 30;

const link_opener = (e) => {
    console.log("Clicked id :",e.id);
    let duration = document.getElementsByClassName("duration"+e.id);
    console.log("Duration :",duration);

	let links = document.getElementById(e.id);
	let w;
	// addred for blog
	/* w = window.open(`${e.dataset.link}?offset=0&ui=${user_id}&ji=${e.id}&ri=${referer_id}&re=${referer_earn}&je=${job_earn}`, "_blank");
	window.focus(); */

	//old script 
	if (!w || w.closed) {
		$('td').css({ 'pointer-events': 'none', 'color': 'grey' });
		w = window.open(e.dataset.link, "_blank");
		window.focus();
		// console.log(w.document.readyState);

        let tim = 0;

        $(".ppcButton").attr("disabled",true);

        
		$(".duration"+e.id).html(`<span class="badge badge-pill badge-gradient-info">Loading...</span>`);
        console.log("Duration HTML :",duration.innerHTML);
        
		setTimeout(() => {
			let timer = setInterval(() => {
				if (w.closed == true) {
					$('button').css({ 'pointer-events': 'auto', 'color': 'black' });
                    $(".duration"+e.id).html(`<span class="badge badge-pill badge-gradient-danger">Error</span>`);
                    $(".ppcButton").attr("disabled",false);
					clearInterval(timer);
				} else {
					$(".duration"+e.id).html(`<span class="badge badge-pill badge-gradient-warning">${tim++}</span>`);
					if (tim > addViewTime) {
                        $(".ppcButton").attr("disabled",false);
						clearInterval(timer);
						$(".duration"+e.id).html(`<span class="badge badge-pill badge-gradient-success">Success</span>`);
                        console.log("Duration Else if condition :",duration.innerHTML);

						let data = {
							"user_id": user_id,
							"job_id": e.id,
							referer_id,
							job_earn,
							referer_earn
						};

						if (document.readyState === "complete") {
							$.ajax({
								type: "post",
								url: "https://" + window.location.hostname + "/index.php/" + "JobsCtrl/viewed_jobs",
								data: data,
								dataType: "json",
								success: function (response) {
									if (response.success == 1) {
                                        
										document.getElementById(e.id).removeAttribute("data-link");
										document.getElementById(e.id).removeAttribute("onclick");
									}
								}
							});
						}
					}else{
                        $(".ppcButton").attr("disabled",true);
                    }
				}
			}, 1000);

		}, loadingTime);

	} else {
		console.log('window is already opened');
	}

	w.focus();
}