jQuery.fn.exists = function() {
    return this.length > 0;
}

var instoreTimeout = 900000;

$(document).ready(applyInstoreFixes);

function applyInstoreFixes() {
	instoreFixForResponsive();
}



function isBasketInUse() {
	return $("#cart_content > span").text() !== "0";
}


function instoreFixForResponsive() {
	//header colour
	var backgroundColour = "#3e3e3e";
	$(".header-wrapper").css("background-color", backgroundColour);

	//site logo
	$(".header-logo__link").css("background-image", "url(/staticcontent/instore/wickes-instore-logo.png)");

	//hide login link from header
	$("ul.header-top-line li:nth-child(1)").remove();

	//shrink the search bar & add the empty button.
	$(".header-right-wrapp .header-right__item:nth-child(2)").after("<li class=\"header-right__item\"><a href=\"/clear-cookies.html\" class=\"header-right__link swal-confirm\"><span class=\"btn__text\"><i class=\"fas fa-trash fa-2x\"></i></span><span class=\"header-right__link-title\">Empty</span></a></li>");
	//add swal
	$("head").append("<script src='https://unpkg.com/sweetalert/dist/sweetalert.min.js'></script>");
	//link swal
	$(".swal-confirm").click(function(e) {
		e.preventDefault();
		swal({
			title: "Are you sure?",
			text: "You will remove all the items from the basket, including any vouchers applied.",
			buttons: true,
			dangerMode: true
		}).then(function(willDelete) {
			if (willDelete) {
				// Redirect the user
				var link = e.target;
				window.location.href = $(link).attr('href');
			}
		});
	});
	
	//responsive checkout modifications
	if (window.location.href.indexOf('/checkout/') > -1) {
		if (window.location.href.indexOf("confirmation") <= 0 &&
			$("#inStoreCheckoutIndicator").length <= 0) {
			//we're in checkout but not the instore one
			window.location.replace("/cart/checkout");
		}
		//disable autocomplete on all input fields
		$("input[type='text']").each(function() {
			$(this).attr("autocomplete", "instore-disable")
		});
		$("input[type='email']").each(function() {
			$(this).attr("autocomplete", "instore-disable")
		});
		$("input[type='tel']").each(function() {
			$(this).attr("autocomplete", "instore-disable")
		});
		$("form").each(function() {
			$(this).attr("autocomplete", "off")
		});
		$("#payment_receipt_number").attr("autocomplete", "off");
		$("#payment_colleague_id").attr("autocomplete", "off");

		//disable the submit button after the form has been submitted to prevent double clicking.
		$("#inStoreSummaryForm").submit(function(event) {
			$("#inStoreSummaryForm > button").prop('disabled', true);
			console.log("Disabling...");
			setTimeout(function() {
				console.log("re-enabling");
				$("#inStoreSummaryForm > button").prop('disabled', false);

			}, 5000);

		});
	}

	if (window.location.href.indexOf('/checkout/hybrid/login') !== -1) {
			applyNoEmailFix();
		}

	if (window.location.href.indexOf('/checkout/') === -1) {



		//set timeout to display after X mins on page
		setTimeout(function() {
			showClearBasketPopup(true)
		}, instoreTimeout);

		//create user is active update loop
		setTimeout(userIsActive, 1000);

		if(checkIfUserHasBeenInactiveForALongTime()) {
			console.log("The user has been inactive for a long time prior to loading this page.");
			setTimeout(function() {
				showClearBasketPopup(false);
			}, 1000);
		}
	}


	fixWickesURLs();
	setTimeout(fixWickesURLs, 2000);
	setTimeout(fixWickesURLs, 5000);
}


function applyNoEmailFix() {
	console.log("In Login Page");
	$("#j_username").parent().parent().after("<div class='form-row'> " +
									"<div class='form-row__field'>" +
									"<label for='checkout-no-email' class='chb'> " +
						              "<input type='checkbox' id='checkout-no-email' > " +
						              "<ins><i class='fas fa-check'></i></ins> " +
						              "<span>Customer has no email address</span> " +
						            "</label>" +
						            "</div>" +
								"</div>");
	$("#checkout-no-email").click(selectNoEmail);
}

function selectNoEmail(event) {
	var userName = $("#j_username");
	var disabled = userName.is(":disabled");

	userName.attr('disabled', !disabled);

	if (!disabled) {
		userName.val("");
	}

}

function handleLoginFormSubmit() {
        	var noEmail = $('#checkout-no-email').is(':checked');

        	if (noEmail) {
        		swal({
        				title: "No email address?",
        				text: "Are you sure the customer doesn't have access to an email account? \nThis means the customer will not receive any confirmation, order updates, or refund updates. ",
        				buttons: true,
        				dangerMode: true
        			}).then(function(willDelete) {
        				if (willDelete) {
        					console.log("Going to populate with default and submit");
        					$("#j_username").attr('disabled', false);
        					$("#j_username").hide();
        					$("#j_username").val("noemailoli@wickes.co.uk");
        					$("#loginForm").unbind().submit();
        				} else {
        				    location.reload();
        					console.log("The user has decided not to continue");
        				}
        			});
        	}else{
        	    document.getElementById("loginForm").submit();
        	}
 }

function fixWickesURLs() {
	$("a").each(function(index) {
		var url = $(this).attr('href');
		if((typeof url !== 'undefined') &&  url.startsWith("https://www.wickes.co.uk/")) {
			$(this).attr('href', url.substring("https://www.wickes.co.uk".length, url.length));
		} else if((typeof url !== 'undefined') &&  url.startsWith("http://www.wickes.co.uk/")) {
			$(this).attr('href', url.substring("http://www.wickes.co.uk".length, url.length));
		}
	});

        $("area").each(function(index) {
                var url = $(this).attr('href');
                if((typeof url !== 'undefined') &&  url.startsWith("https://www.wickes.co.uk/")) {
                        $(this).attr('href', url.substring("https://www.wickes.co.uk".length, url.length));
                } else if((typeof url !== 'undefined') &&  url.startsWith("http://www.wickes.co.uk/")) {
                        $(this).attr('href', url.substring("http://www.wickes.co.uk".length, url.length));
                }
        });
}

function userIsActive() {
    var lastActiveTime = getCookie("instoreLastActiveTime");
	document.cookie = "instoreLastActiveTime=" + (new Date()).getTime() + "; expires=Thu, 1 Apr 2038 12:00:00 UTC; path=/";
	setTimeout(userIsActive, 1000);
}


function checkIfUserHasBeenInactiveForALongTime() {
	var lastActiveTime = getCookie("instoreLastActiveTime");
	return (lastActiveTime && ((new Date()).getTime() - (instoreTimeout / 15)) > lastActiveTime);

}

function showClearBasketPopup(timeout) {
    var message = "";
    if (timeout) {
        message = "You haven't used the site for 15 minutes, do you want to clear the basket for a new customer?";
    } else {
        message = "Do you want to clear the basket for a new customer?";
    }

	if (isBasketInUse()) {
		swal({
			title: "Clear existing basket?",
			text: message,
			buttons: true,
			dangerMode: true
		}).then(function(willDelete) {
			if (willDelete) {
				window.location.href = "/clear-cookies.html";
			}
		});
	} else {
		console.log("No items in the cart. Skipping.");
	}


}

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}