window.onload = () => {
	if(window.jQuery){
		checkall();
	}
}

function checkall(){
    $('#checkall').change(function(){
        var checkboxes = $(this).closest('form').find('.checkall');
        if($(this).prop('checked')) {
            checkboxes.prop('checked', true);
        } else {
            checkboxes.prop('checked', false);
        }
    });

    $('#checkall2').change(function(){
        var checkboxes = $(this).closest('form').find('.checkall2');
        if($(this).prop('checked')) {
            checkboxes.prop('checked', true);
        } else {
            checkboxes.prop('checked', false);
        }
    });
}

function sowdeletionbar(){
	var referrals=$("input:checked[name^='ref']");
	var refslist=referrals.length;
	var raction = $("#descr").val();
	$("#priceref").hide();
	$("#priceref2").hide();
	$("#paybutton").hide();
	$("#addfunds").hide();
	if(refslist>0){
		$("#rentedbar").show();	
		if(raction == "delete"){
			var price = deletion_price*refslist;
			price = price.toFixed(3);
			var step1 = 'done';
		}
		if(step1 == 'done'){
			if(rental_balance >= price){
				$("#priceref").html(totaltopay+": $"+price);
				$("#priceref").show();
				$("#paybutton").show();
			}else{
				$("#priceref2").html(noenoughfunds);
				$("#priceref2").show();
			}
		}
	}else{
		$("#rentedbar").hide();	
	}
}

/* Allocate */
function calculatecredits(value){
	var newvalue = $("#allocate").val()*value;
	$("#creditcost").val(newvalue);	
}
function recalculatecredits(value){
	var newvalue = $("#creditcost").val()/value;
	$("#allocate").val(newvalue);		
}

/* Advertise */
function updatepack(){
	specialid = $("#spackformlist").val();
	specialtext = $("#spackformlist option[value="+specialid+"]").text();
	var packlist = "<strong>"+specialtext+"</strong>";
	packlist += '<ul>';
	for (var k in specialitemsList.specialitems){
		if(specialitemsList.specialitems[k].specialpack == specialid){
			packlist += "<li>"+specialitemsList.specialitems[k].amount+" "+specialitemsList.specialitems[k].title+"</li>";
		}
	}
	packlist += '<ul>';
	$("#specialpackdescr").html(packlist);
}

function advertiseItem(formModule, itemContainer='select')
{
	$('#Msgcheckoutform').remove();
	var formID = $('#'+formModule);
	const moduleName = formID.find('input[name="product"]').val();
	if(itemContainer === 'select'){
		itemID = formID.find('select[name="item"]').val();
		itemTXT = formID.find('select[name="item"]').children('[value="'+itemID+'"]').text();
	}else{
		itemTXT = formID.find('input[name="itemTXT"]').val();
	}
	$("#itemname").html(itemTXT);
	$("#productname").html(moduleName);
	$("#ads_list").hide();

	var payment_details = '';
	$.each(formID.serializeArray(), function(i, field) {
		payment_details += '<input type="hidden" name="'+field.name+'" id="'+field.name+'" value="'+field.value+'" />';
	});
	$("#checkoutform").append(payment_details);
	$("#payment_form").show();
	return false;
}

function cancel_payad(){
	$("#payment_form").hide();
	$("#ads_list").show();
}


/* Rent Referrals Options */
function showextensionbar(){
	var rented=$("input:checked[name^='ref']");
	var rentedlist=rented.length;
	var raction = $("#descr").val();
	$("#priceref").hide();
	$("#priceref2").hide();
	$("#paybutton").hide();
	$("#addfunds").hide();
	
	if(rentedlist>0){
		$("#rentedbar").show();	

		if(raction == ''){	
		}else
		if(raction == 'recycle'){
			var price = recycle_price*rentedlist;
			price = price.toFixed(3)							
		}else{
			var days = ref_extension[raction]/30;
			days = days.toFixed(2);
			var price = (renew_price*rentedlist)*days;
			var price = price - ((price*ref_discount[raction])/100);
			price = price.toFixed(3);
		}
		if(rental_balance >= price){
			$("#priceref").html(totaltopay+": $"+price);
			$("#priceref").show();
			$("#paybutton").show();
		}else{
			if(price != null){
			$("#priceref2").html(noenoughfunds);
			}
			$("#priceref2").show();
			$("#addfunds").show();
		}
	}else{
		$("#rentedbar").hide();	
	}
}


/* Ads Page */
function hideAdminAdvertisement(){
	$("#admin_advertisement").remove();
	$(".blockthis").l2unblock();
}
function hideAdvertisement(id){
	$("#"+id).addClass('disabled');
}
/* Validate ad without iframe */
var w=window;
var d=document;
advertisementValidationID=0;
secondsValidationLoaded = 0;
adValidationLoaded = false;
adValidationConfirmed = false;
adValidationSessToken = null;
adValidationTimer = 0;

function openValidationAd(adId, iFrame)
{
	advertisementValidationID = adId;
	adWindow = window.open('/account/advertiser-panel/ptc_ads/validate/'+adId, '_blank');
	if(iFrame === 2){
		var myModal = new bootstrap.Modal(document.getElementById('ptcAddModal'), {
			keyboard: false,
			backdrop: 'static'
		})
		myModal.show();
		secondsValidationLoaded = 0;
		myValidationInterval = setInterval('checkOpenedValidationAd();', 1000);
	}
}
function adWindowOpened(sessToken, adSeconds) {
	adValidationLoaded = true;
	adValidationTimer = parseInt(adSeconds);
	adValidationSessToken = sessToken;
}
function adWindowOpenedError(errorMsg) {
	showAdWarningMsg('Error: '+errorMsg);
	clearInterval(myInterval);
}
function checkOpenedValidationAd() {
	if(!adWindow){
		showAdValidationWarningMsg(msgModalBlocker);
		clearInterval(myValidationInterval);
	}else{
		if(!adWindow.closed){
			timeLeft = adValidationTimer-secondsValidationLoaded;
			if(adValidationLoaded === true){
				if(timeLeft >= 0){
					showValidationCounterMsg(adValidationTimer-secondsValidationLoaded);
					secondsValidationLoaded = secondsValidationLoaded+1;
				}else{

					$.ajax({
						url: '/account/advertiser-panel/ptc_ads/validate/'+advertisementValidationID+'/'+adValidationSessToken+'?getMagic=code',
						method: 'GET',
						dataType: 'json',
						cache: false,
						processData: false,
						contentType: false
					}).done(function(data) {
						if(data.status === 'success'){
							$('#adValidationSessToken').val(data.script);
							showValidationConfirmationMsg(data.msg);
						}else{
							showAdValidationWarningMsg(msgModalWrongAccess);
						}
					}).fail(function(jqXHR, textStatus, errorThrown) {
						showAdValidationWarningMsg(msgModalWrongAccess);
					});

					clearInterval(myValidationInterval);
				}
			}
		}else{
			if(adValidationConfirmed === true){
				console.log('Ad was closed.');
			}else{
				showAdValidationWarningMsg(msgModalAdClosed);
			}
			clearInterval(myValidationInterval);
		}
	}
}


function ptc_ad_validation(master_key){
	if(master_key==''){
		$("#surf_status").fadeOut('slow', function(){
			$("#captchaBlock").fadeIn('slow');
		});
		return false;
	}else{
		$("#captchaBlock").fadeOut('slow', function(){
			$(this).remove();
			$("#surf_status").fadeIn('slow');
		});
	}
	showAdValidationWarningMsg(msgPleaseWait);
	$("#adSelectedToken").val(master_key);

	dataForm = new FormData(document.getElementById('ptc_form'));
	$.ajax({
		url: '/account/advertiser-panel/ptc_ads/validate/'+advertisementValidationID+'/'+adValidationSessToken,
		method: 'POST',
		data: dataForm,
		dataType: 'json',
		cache: false,
		processData: false,
		contentType: false
	}).done(function(data) {
		if(data.status === 'success'){
			showAdValidationWarningMsg(data.msg);
			window.location.reload();
		}else{
			showAdValidationWarningMsg(data.msg);
		}
	}).fail(function(jqXHR, textStatus, errorThrown) {
		showAdValidationWarningMsg(msgModalWrongAccess);
	});
}

function showValidationCounterMsg(adMsg) {
	$('#modalCounterLine').text(adMsg);
	$('#modalCounterMsg').show();
	$('#modalWarningMsg').hide();
	$('#modalWaitMsg').hide();
	$('#modalConfirmationMsg').hide();
}

function showAdValidationWarningMsg(adMsg) {
	$('#modalWarningLine').text(adMsg);
	$('#modalWarningMsg').show();
	$('#modalWaitMsg').hide();
	$('#modalCounterMsg').hide();
	$('#modalConfirmationMsg').hide();
}

function showValidationConfirmationMsg(adMsg) {
	$('#modalConfirmationLine').html(msgUpside+'<br>'+adMsg);
	$('#modalConfirmationMsg').show();
	$('#modalWaitMsg').hide();
	$('#modalWarningMsg').hide();
	$('#modalCounterMsg').hide();
}

function closeValidationAdModal() {
	var myModal = bootstrap.Modal.getInstance(document.getElementById('ptcAddModal'))
	myModal.hide();
	$('#modalWaitMsg').show();
	$('#modalWarningMsg').hide();
	$('#modalCounterMsg').hide();
	$('#modalConfirmationMsg').hide();
	advertisementValidationID = 0;
	secondsValidationLoaded = 0;
	adValidationLoaded = false;
	adValidationConfirmed = false;
	adValidationSessToken = null;
}

/* Server Time */
function serverTime()
{
	const timerContainer = document.getElementById('timenow');
	if(timerContainer){
		var hours=mydate.getHours();
		var minutes=mydate.getMinutes();
		var seconds=mydate.getSeconds();
		if(hours<10){
			hours='0'+hours;
		}
		if(minutes<10){
			minutes='0'+minutes;
		}
		if(seconds<10){
			seconds='0'+seconds;
		}
		timerContainer.innerHTML = hours+":"+minutes+":"+seconds;
		mydate.setSeconds(mydate.getSeconds()+1);
		setTimeout("dateTimer()",1000);
	}
}

/* Style Picker */
var listStyle = ['blue','red','green','orange'];
function stylePicker(colorPicker)
{
	var finder = listStyle.find(e => e === colorPicker);
	if(typeof finder !== "undefined"){
		const el = document.getElementById('bootstrapStyle');
		if(el){
			el.setAttribute('href', '/assets/components/bootstrap5/css/'+colorPicker+'.css');
			localStorage.setItem('style', colorPicker);
		}
	}
}
function getCookieStyle()
{
	const currentStyle = localStorage.getItem('style');
	if(currentStyle === null || currentStyle === ''){
		return ""
	}else{
		return currentStyle;
	}
}