$(document).ready(function () {

	calculateMenuPosition();
    
	DiagnosisToolUpload();
	
    // Blog Tag Clicks
    //
    $(".blog-tag-click").click(function(e){
      
        var dataID = "," + $(this).data("id") + ",";
        
        showBlogTiles($(this), dataID);

        e.preventDefault();
  	}); 

	
	//Case Studies Filters
	//
	$('.cs-filter-btn').click(function (e) {

		e.preventDefault();

		var t = $(this);
		var tagID = t.data("id");

		console.log(tagID);

		if (t.hasClass("active"))
		{
			t.removeClass("active");
			$(".case-study-card").show();
		} else {
			$(".cs-filter-btn").removeClass("active");
			t.addClass("active");
			$(".case-study-card").hide();
			$(".case-study-card[data-tagids*='," + tagID + ",']").show();
		}

	})

	
	

	// Set Accordian Input
	$(document).on("click", ".accordion-item h2", function (e) {
		var t = $(this).parent(".accordion-item");
		t.toggleClass("active");
		t.children(".accordion-expanded").slideToggle(500);
		e.preventDefault();
	});
	

    //////////////////////////////////
    //////////TEXT ROTATE////////////

	var TxtType = function(el, toRotate, period) {
			this.toRotate = toRotate;
			this.el = el;
			this.loopNum = 0;
			this.period = parseInt(period, 10) || 2000;
			this.txt = '';
			this.tick();
			this.isDeleting = false;
		};

		TxtType.prototype.tick = function() {
			var i = this.loopNum % this.toRotate.length;
			var fullTxt = this.toRotate[i];

			if (this.isDeleting) {
			this.txt = fullTxt.substring(0, this.txt.length - 1);
			} else {
			this.txt = fullTxt.substring(0, this.txt.length + 1);
			}

			this.el.innerHTML = '<span class="wrap">'+this.txt+'</span>';

			var that = this;
			var delta = 200 - Math.random() * 150;

			if (this.isDeleting) { delta /= 2; }

			if (!this.isDeleting && this.txt === fullTxt) {
			delta = this.period;
			this.isDeleting = true;
			} else if (this.isDeleting && this.txt === '') {
			this.isDeleting = false;
			this.loopNum++;
			delta = 500;
			}

			setTimeout(function() {
			that.tick();
			}, delta);
		};

		window.onload = function() {
			var elements = document.getElementsByClassName('typewrite');
			for (var i=0; i<elements.length; i++) {
				var toRotate = elements[i].getAttribute('data-type');
				var period = elements[i].getAttribute('data-period');
				if (toRotate) {
				  new TxtType(elements[i], JSON.parse(toRotate), period);
				}
			}
			// INJECT CSS
			var css = document.createElement("style");
			css.type = "text/css";
			css.innerHTML = ".typewrite > .wrap {}";
			document.body.appendChild(css);
		};
    //////////////////////////////////
    //////////////////////////////////
	
	/* SLICK */
	$('.testimonial-carousel').slick({
	  infinite: true,
	  arrows: false,
	  dots: true
	});
	
	$('.case-study-gallery').slick({
	  infinite: true,
	  arrows: true,
	  dots: true,
	  fade: true
	});
	
	$('.home-hero-text-carousel').slick({
		autoplay: true,
		infinite: true,
		arrows: false,
		dots: true,
		asNavFor: '.home-hero-bg-image-carousel',
		autoplaySpeed: 6000,
		speed: 900
	});
	
	$('.home-hero-bg-image-carousel').slick({
		autoplay: true,
		infinite: true,
		arrows: false,
		dots: false,
		fade: true,
		autoplaySpeed: 6000,
		speed: 900
	});
	
	$('.clients-carousel').slick({
	  infinite: true,
	  arrows: false,
	  dots: true,
	  slidesToShow: 4,
	  slidesToScroll: 4,
		responsive: [
			{
			  breakpoint: 960,
			  settings: {
				arrows: false,
				slidesToShow: 3,
				slidesToScroll: 1
			  }
			},
			{
			  breakpoint: 550,
			  settings: {
			  arrows: false,
			  slidesToShow: 2,
			  slidesToScroll: 1
			  }
			}
	  ]
	});

	
	/* TABBED CAROUSEL */
	$('.tabbed-carousel-content').slick({
		autoplay: false,
		infinite: true,
		arrows: false,
		dots: false,
		responsive: [
			{
			  breakpoint: 551,
			  settings: {
			  arrows: true,
			  dots: true,
			  appendDots: $('.tabbed-carousel-nav-mb'),
			  appendArrows: $('.tabbed-carousel-nav-mb')
			  }
			}
	  	]
	});
	
	/* SIMPLE SLIDER */
	$('.simple-slider').slick({
	  infinite: true,
	  arrows: true,
	  dots: false
	});

	/* IMAGE FADER */
	$('.bfc-image-carousel').slick({
	  infinite: true,
	  arrows: false,
	  dots: false,
	  fade: true
	});

	/* IMAGE CAROUSEL */
	$('.bfc-text-carousel').slick({
	  infinite: true,
	  arrows: true,
	  dots: true,
	  autoplay: true,
	  appendDots: $('.bfc-carousel-nav'),
	  appendArrows: $('.bfc-carousel-nav'),
	  asNavFor: '.bfc-image-carousel',
	  arrows: true,
	  dotsClass: 'custom_paging',
	  customPaging: function (slider, i) {
		//FYI just have a look at the object to find available information
		//press f12 to access the console in most browsers
		//you could also debug or look in the source
		console.log(slider);
		return  (i + 1) + '/' + slider.slideCount;
	  }
	});

	
	
	
	
	/* SKROLLR */
	if (!isMobile) {
		var s = skrollr.init({
			edgeStrategy: 'ease',
			smoothScrolling: true,
		});
	}
	
   $('.menu-toggle').click(function (e) {
        $(".main-nav").toggleClass('open');

        if ($(".main-nav").hasClass("open")) {
            $("html,body").css({"overflow-y": "hidden"});
            $(".nav-icon").addClass('open');
            $(".nav-secondary").fadeOut();

        } else {
          $("html,body").removeAttr("style");
          $(".nav-icon").removeClass('open');
          $(".nav-secondary").fadeIn();
        }

        e.preventDefault();
  	});     
	
	$('.toggle-more-info').click(function(){
		
		$(this).parents().next('.panel-more-info').slideToggle();
		$(this).toggleClass('active');
		
		
	});
	
	$('nav.main-nav ul li span').click(function(){

		$(this).siblings("ul").slideToggle();
		$(this).toggleClass('active');
		
	});

	// POPUP //
	$('.toggle-popup').click(function (e) {
		closePopup();
		e.preventDefault();
	});
	
	
	// This expands and collapes the Service Panel Section Text
	// 
	$(".section-copy-outer h4").click(function (e) {
		e.preventDefault();
		console.log(1);
		
		var t = $(this);
		
		if(t.hasClass("active")) {
			t.removeClass("active");
			t.next(".section-copy").slideUp();
		} else {
			t.addClass("active");
			t.next(".section-copy").slideDown();
		}
				
	});
	
	
	
	
    // Loop through each Service Panel and set the height of service-panel-text-intro to be the max in the row
	//
    $('.service-options-2024').each(function(){
		
		var windowWidth = window.innerWidth;
		var mobileBreakPoint = 641;
		
		// Dont match heaight on mobile
		//
		if (windowWidth>=mobileBreakPoint) 
		{
			var maxHeight = 0;
			var $panels = $(this).find('.service-panel-text-intro');

			// Find the max height of service-panel-text-intro elements in this ROW
			$panels.each(function(){
				var panelHeight = $(this).outerHeight();
				if(panelHeight > maxHeight){
					maxHeight = panelHeight;
				}
			});

			// Set all service-panel-text-intro elements to the max height
			$panels.css('min-height', maxHeight);
		
		}
		
    });
	
	
	
	
});









function showBlogTiles(el, dataID) {


    if (dataID==",0,") {
        $(".blog-tag-click").removeClass("tint");
        $(".blog-item").removeClass("disabled");

    } else {
        $(".blog-tag-click").addClass("tint");
        $(".blog-item").addClass("disabled");

        $(".blog-item").each(function(i, obj) {

            var datatags = $(this).data("blogtags");
            var instr = datatags.indexOf(dataID);
             //console.log ("datatags " + datatags);
             //console.log ("instr " + instr);

            if (instr>-1) {
                $(this).removeClass("disabled");
            }
        });

        $(el).removeClass("tint");
    }
}

function showPopUp() {
	$(".hidden").addClass("fadein")
}


function closePopup() {
	$('.popup-overlay').fadeToggle();
	$('.popup-content').toggleClass('animated');

	return false;
}


// Push level-3 menus to the left if close to edge of screen
//
window.onresize = calculateMenuPosition;

function calculateMenuPosition() {
	var w = window.innerWidth;
	var uls = $("body").find('.main-nav .menu-level-3');

	// Loop through each level-3 menu in main nav
	//
	for (var i = 0; i < uls.length; ++i) {
		var rect = uls[i].getBoundingClientRect();
		var a = 0;

		if ($(uls[i]).hasClass("ddLeft")) {
			// Placed on left so need to calculate original position 
			//
			a = 220 * 2;
		}

		if (rect.right + a + 20 > w) {
			// position left
			//
			uls[i].classList.add("ddLeft");
		}
		else {
			// position normal (right)
			//
			uls[i].classList.remove("ddLeft");
		}
	}
}

function ShowAlert(title, message, onclose) {
	var dlg = $("<div class=\"dialog alert\" title=\"" + title + "\"><p>" + message + "</p></div>");

	var body = $("body");

	body.addClass("no-scroll");

	console.log("SHOW ALERT", title, message);
	dlg = dlg.appendTo("body");
	dlg.dialog({
		modal: true,
		width: 400,
		dialogClass: "no-close alert",
		position: { my: "center", at: "center center", of: window },
		buttons: [
			{
				text: "OK",
				class: "btn btn-success",
				click: function () {
					$(this).dialog("close");
				}
			}
		],
		close: function (e) {
			body.removeClass("no-scroll");
			dlg.remove();

			if (typeof onclose == "function") {
				onclose();
			}
		}
	});
}

function setButtonWorking(btn) {
	$(btn).addClass("working").prop("disabled", true);
}

function setButtonActive(btn) {
	$(btn).removeClass("working").prop("disabled", false);
}

function resetAddressContactAsAbove() {
	var x = $(".contact-as-above").find("input[type=checkbox]")
		.off("change")
		.on("change", function (e) {
			var self = $(this);
			var uid = self.parent().attr("data-uid");
			var contact = $(".address-contact[data-uid='" + uid + "']");

			if (self.prop("checked")) {
				contact.slideUp(100);
			}
			else {
				contact.slideDown(100);
         }
		});
}

function checkMobile() {
	var windowWidth = window.innerWidth;
	var mobileBreakPoint = 641;

	if (windowWidth < mobileBreakPoint) {
		// Mobile
		return true;
	} else {
		// Desktop
		return false;
	}
}

function checkMobileImages() {

	var windowWidth = window.innerWidth;
	var mobileBreakPoint = 641;

	// Loop through all divs we want to check
	//
	$(".mobile-image-switch").each(function (i) {
		var useThisImage;

		var desktopImage = this.dataset.desktopimage;
		var mobileImage = this.dataset.mobileimage;
		var currImage = this.style.backgroundImage;

		//console.log('checkMobileImages', mobileImage);

		if (mobileImage == undefined) {
			mobileImage = desktopImage
		}
		else if (mobileImage.length < 1) {
			mobileImage = desktopImage;
		}

		if (windowWidth < mobileBreakPoint) {
			// Mobile
			useThisImage = mobileImage;
		} else {
			// Desktop
			useThisImage = desktopImage;
		}

		if (useThisImage === '' || useThisImage === undefined) {
			return;
		}

		useThisImage = 'url("' + useThisImage + '")';

		// If needed switch the image
		//
		if (useThisImage != currImage) {
			$(this).css("background-image", useThisImage);
		}
	});
}

$(window).on('resize', function () {
	checkMobileImages();
});

function DiagnosisToolUpload(s, si) {


	console.log("1")

	var uploader = new plupload.Uploader({
		runtimes: 'html5',
		browse_button: 'cpBody_selectfiles', //id of select file button
		url: '/_ajax/DiagnosisToolUploadFile.ashx',
		multi_selection: true,
		filters: {
			max_file_size: '10mb',
			mime_types: [{
				title: "Office files",
				extensions: "doc,docx,pdf,jpg,png"
			}]
		},

		init: {
			FilesAdded: function (up, files) {

				plupload.each(files, function (file) {
					//document.getElementById('filelist').innerHTML += '<span class="sub-title">File:</span> <div class=\"file-list\" id="' + file.id + '"><span id="remove-' + file.id + '" title="Remove file" class=\"remove delete-cv\">X</span> ' + file.name + ' <b></b> </div>';

					//Bind click event in order to delete file later on.

					//$(document).off('click', '.icon-del-diagnosis-tool');
					//$(document).on("click", '.icon-del-diagnosis-tool', function (e) {

					//	let filename = $(this).data('file');

					//	//up.removeFile(file.id);
					//	//$(this).parent().remove();
					//	DiagnosisToolDeleteFile(filename);
						
					//	/*$("#diagnosis-tool-file-name").empty();*/
					//	//$("#cpBody_hfFileName").val("");
					//	e.preventDefault();
					//});
				});


				uploader.start();

				//$("#uploadfiles").css("display", "inline-block");
				//$(".upload-files .moxie-shim-html5, #cpBody_selectfiles").hide();
			},

			FileUploaded: function (up, file, result) {
				// remove the file from the list
				up.removeFile(file);
			},

			UploadProgress: function (up, file) {
				$("#diagnosis-tool-upload-progress").html(file.name + ' ' + file.percent + "%");
			},

			UploadComplete: function (up, files) {
				//$("#uploadfiles").hide();

				//$("#diagnosis-tool-upload-progress").html('');

				DiagnosisToolGetFiles();

				//setTimeout(function () {
				//	$("#diagnosis-tool-upload-progress").empty();
				//	$("#diagnosis-tool-file-name").html(files[0].name + "<span class=\"icon-del-diagnosis-tool\" data-file=\"" + files[0].name + "\"></span>");
				//	$("#cpBody_hfFileName").val(files[0].name);
				//}, 200);
			},

			Error: function (up, err) {
				//debugger;
			}

			//Error: function (up, err) {
			//    document.getElementById('console').appendChild(document.createTextNode("\nError #" + err.code + ": " + err.message));
			//}
		}
	});

	uploader.init();
}

function DiagnosisToolGetFiles() {

	$.ajax({
		url: '_ajax/DiagnosisToolGetFiles.ashx',
		type: 'GET',
		cache: false,
		dataType: 'json',
		success: function (response) {

			console.log('getfiles', response);

			if (response.files.length > 0) {
				let html = [];
				let fileName = [];
				
				for (let file of response.files) {
					html.push('<li>' + file.name + "<span class=\"icon-del-diagnosis-tool\" data-file=\"" + file.name + "\"></span></li>");
					fileName.push(file.name);
				}

				$("#diagnosis-tool-file-name").html('<ul>' + html.join('') + '</ul>');
				$("#cpBody_hfFileName").val(fileName.join('|'));

				// clear click event
				$(document).off('click', '.icon-del-diagnosis-tool');

				$(document).on("click", '.icon-del-diagnosis-tool', function (e) {
					e.preventDefault();

					let filename = $(this).data('file');

					DiagnosisToolDeleteFile(filename);
				});

			} else {
				$(document).off('click', '.icon-del-diagnosis-tool');

				$("#diagnosis-tool-file-name").html('');
				$("#cpBody_hfFileName").val('');
			}

		}
	});

}

function DiagnosisToolDeleteFile(filename) {
	console.log('DiagnosisToolDeleteFile', filename);

	let data = JSON.stringify({
		'filename': filename
	});

	$.ajax({
		url: '/_ajax/DiagnosisToolDeleteFile.ashx',
		type: 'POST',
		contentType: 'application/json; charset=utf-8',
		dataType: 'json',
		data: data,
		success: function (response) {
			if (response.success) {
				//$("#filelist").fadeOut(500, function () {
					//$("#filelist").empty();
					//$(".upload-files .moxie-shim-html5, #cpBody_selectfiles").css("display", "inline-block");
				//});

				DiagnosisToolGetFiles();
			} else {
				alert("There was a problem removing this file. Please try again.");
			}
		},
		error: function (response) {
			alert("There was a problem removing this file. Please try again.");
		}
	});
}