// JavaScript Document
var counselorData;
let siteUrl = fycData.siteUrl;
let ajaxUrl = fycData.ajaxUrl;
console.log(ajaxUrl);
function homeschoolCallback(response) {
	jQuery.each(response, function( i, field){
		if( field['meta']['butler_find_your_counselor']['student_type'].includes( 'homeschool-students' ) ) {
			counselorData = field;
		}
	});
	outputCounselor(counselorData, 'homeschool');
}

function homeschool() {
	window.homeschoolButton = true;
	jQuery.getJSON(siteUrl + '/wp-json/wp/v2/counselor?per_page=100', homeschoolCallback);
}

function getCounselor(counselorType) {
	jQuery.getJSON(siteUrl + '/wp-json/wp/v2/counselor?per_page=100', function(response) {
		jQuery.each(response, function( i, field){
			if( field['meta']['butler_find_your_counselor']['student_type'].includes(counselorType) ) {
				console.log(counselorType);
			console.log(field);
				counselorData = field;
			}
		});
		outputCounselor(counselorData, null);
	});
}

function ipsSelectCallBack(response) {
	jQuery.each(response, function( i, field){
		if( field['meta']['butler_find_your_counselor']['student_type'].includes( 'ips-students' ) ) {
			counselorData = field;
		}
	});
	outputCounselor(counselorData, 'zip');
}

function hamiltonSelectCallBack(response) {
	jQuery.each(response, function( i, field){
		if( field['meta']['butler_find_your_counselor']['student_type'].includes( 'hamilton-students' ) ) {
			counselorData = field;
		}
	});
	outputCounselor(counselorData, 'zip');
}

function ipsSelect() {
	var $schoolSystem = jQuery('#ipsSelect').val();
	if($schoolSystem == "ips") {
		jQuery.getJSON(siteUrl + '/wp-json/wp/v2/counselor?per_page=100', ipsSelectCallBack);
		jQuery('#ipsSelectLabel').remove();
	}
	if($schoolSystem == "hamilton") {
		jQuery.getJSON(siteUrl + '/wp-json/wp/v2/counselor?per_page=100', hamiltonSelectCallBack);
		jQuery('#ipsSelectLabel').remove();
	}
	if($schoolSystem == "other" ) {
		jQuery.getJSON(siteUrl + '/wp-json/wp/v2/counselor?per_page=100', ipsSelectCallBack);
		jQuery('#ipsSelectLabel').remove();
	}
}

function outputIpsSelect() {
	window.localSelect = true;
	jQuery('#fyc_form_container').addClass('hidden');
	var $markup = [];
	$markup += "<p id='ipsSelectLabel'>Please select your school system ";
	$markup += "<select id='ipsSelect' onchange='if (this.selectedIndex)ipsSelect();'><option>- PLEASE SELECT</option>"
	$markup += "<option value='ips'>IPS</option>";
	$markup += "<option value='hamilton'>HAMILTON</option>";
	$markup += "<option value='other'>OTHER</option>";
	$markup += "</select></p>"
	jQuery('#fyc_counselor_container').prepend($markup);
	var $counselorContainerHeight = jQuery('#fyc_counselor_container').css('height');
	jQuery('#fyc_counselor_container').css('height', $counselorContainerHeight);
	jQuery('#ipsSelect').focus();
}

function regionSelectCallBack(response) {
	outputCounselor(response, 'zip');
}

function regionSelect(){
	var $geoMarketId = jQuery('#regionSelect').val();
	jQuery.get('/ajax/id/'+$geoMarketId, regionSelectCallBack);
	jQuery('#regionSelectLabel').remove();
}

function outputSelect(response) {
	jQuery('#fyc_counselor_container').removeAttr('style');
	var $data = response.geomarketid;
	var $markup = [];
	$markup += "<p id='regionSelectLabel'>Please select your region "
	$markup += "<select id='regionSelect' onchange='if (this.selectedIndex)regionSelect();'><option>- PLEASE SELECT</option>"
	for (var i = 1; i < $data.length - 1; i++);
	jQuery.each($data, function() {
		var $description = this.description;
		var $tid = this.tid
		$markup += "<option name = '" + $description + "' value='" + $tid + "'>" + $description + "</option>";
	});
	$markup += "</select></p>"
	jQuery('#fyc_counselor_container').prepend($markup);
	var $counselorContainerHeight = jQuery('#fyc_counselor_container').css('height');
	jQuery('#fyc_counselor_container').css('height', $counselorContainerHeight);
}

function errorCounselor(){
	jQuery('#fyc_counselor_container').removeAttr('style');
		
	$markup = "<div class='counselor_error'>COMING SOON<br><br>We’re currently in the process of assigning an admission counselor to your high school. If you have questions or need assistance, please contact our office at admission@butler.edu or 888-940-8100. We’ll get you connected with a member of our team right away!</div>";

	jQuery('#fyc_form_container').css('height','0');
	jQuery('#fyc_counselor_container').prepend($markup);

	var $infoHeight = jQuery('.counselor_email').outerHeight();
	$infoHeight = $infoHeight + jQuery('.counselor_phone').outerHeight();
	$infoHeight = $infoHeight + jQuery('.counselor_more').outerHeight();

	var $headerWidth = jQuery('.counselor_email').outerWidth();
	$headerWidth = $headerWidth + jQuery('.counselor_image').outerWidth();
	$headerWidth = $headerWidth;

	jQuery('.counselor_image').css('height', $infoHeight);
	if (jQuery(window).width() >= 768) {
		$infoHeight = $infoHeight + jQuery('.counselor_header').outerHeight();
		jQuery('.counselor_image').css('height', $infoHeight);
	}
	jQuery('.fyc_page_container').css('height', '');
	setTimeout(function() {
		var $fycPageContainerHeight = jQuery('.fyc_page_container').css('height');
		jQuery('.fyc_page_container').css('height', $fycPageContainerHeight);
	}, 200);
	$counselorContainerHeight = jQuery('#fyc_counselor_container').css('height');
	jQuery('#fyc_counselor_container').css('height', $counselorContainerHeight);
	jQuery('.counselor_item').css('top', '0');
}

function outputCounselor(counselorData, ifyType) {
	console.log( counselorData );
	jQuery('#fyc_counselor_container').removeAttr('style');
	if(counselorData == null || counselorData.length == 0) {
		errorCounselor();
	} else {
		let id = counselorData['id'];
		let counselorSlug = counselorData['slug']
		let counselorName = counselorData['title']['rendered'];
		let counselorFirst = counselorData['meta']['butler_find_your_counselor']['first_name'];
		let counselorEmail = counselorData['meta']['butler_find_your_counselor']['email'];
		let counselorPhone = counselorData['meta']['butler_find_your_counselor']['phone_number'];
		let counselorPosition = counselorData['meta']['butler_find_your_counselor']['counselor_position'];
		let counselorContent = counselorData['content']['rendered'];
		let counselorImageDataURL = siteUrl + '/wp-json/wp/v2/media/' + counselorData['featured_media'];
		let imageUrl;
		let zipcode = jQuery('#geocode_input').val();
		let showResultsFor = (ifyType == 'zip') ? zipcode : ifyType; 
		jQuery.getJSON(counselorImageDataURL, function(json) {
			imageUrl = json['media_details']['sizes']['full']['source_url'];
		}).success(function(){
			let resultsBanner = '';
			if(ifyType != null) {
				resultsBanner = `<div class="fyc_results_banner" id="fyc_ify_results_banner_container">
						<div class="should-this-be-here">SHOWING RESULTS FOR <span class="show-results-for" onclick="$backStep();">${showResultsFor}</span>
							<button id="back-step-button" class="back-step-button butler-icon butler-icon-1x bi-arrow-left" aria-hidden="true" onclick="$backStep();"></button>
						</div>
					</div>`
			}
			markup = `${resultsBanner}
					<article id="counselor-${id}" class="counselor counselor-${id}">
						<header class="entry-header">
							<h2 class="entry-title counselor-name">${counselorName}</h2>
							<span class="counselor-position">${counselorPosition}</span>
						</header>
						<div class="entry-content">
							<div class="counselor-entry-content">
								${counselorContent}
							</div>
							<div class="counselor-contact-container">
								<img src="${imageUrl}" class="skip-lazy" />
								<div class="counselor-contact-container-inner">
									<span class="counselor-email"><a href="mailto:${counselorEmail}">${counselorEmail}</a></span><span class="counselor-phone">${counselorPhone}</span>
								</div>
							</div>
						</div><!-- .entry-content -->
					</article>`;
			jQuery('#fyc_counselor_container').html(markup);
			if(ifyType != null) {
				replaceDialog('dialog-container', 'homeschool-button', 'back-step-button');
				jQuery('#fyc_form_container').addClass('hidden');
			}
			if(window.localSelect) {
				jQuery('#back-step-button').focus();
			}
		}).error(function(ex){
			console.log('Call to image API failed: ' + ex.responseText );
		});
	}
}

function ajaxCall(counselor) {
	if(counselor == null || counselor.length == 0) {
		errorCounselor();
	} else {
		jQuery.getJSON(siteUrl + '/wp-json/wp/v2/counselor/' + counselor[0].ID, ajaxCallBack);
	}
}

function ajaxCallBack(response) {
	if (response.select == "true") {
		outputSelect(response);
		return;
	}
	if( response['meta']['butler_find_your_counselor']['student_type'].includes( "ips-students" ) ) {
		outputIpsSelect();
		return;
	}
	if ( response['meta']['butler_find_your_counselor']['student_type'].includes( "first-year-students") ) {
		outputCounselor(response, 'zip');
		return;
	}
}

jQuery( document ).ready(function() {
	function $resetStuff() {
		jQuery('#fyc_button_container, .fyc_button_graphic, .fyc_source_banner, .fyc_button_label, #fyc_form_container, #graphic_container, #graphic_container h1, #graphic_container p, #fyc_ify_results_banner_container, .fyc_page_container, #fyc_button_container').removeAttr('style');
		jQuery('.fyc_page_container, .fyc_source_banner, .fyc_results_banner_container, #fyc_counselor_container').html('');
		var $fycButtonContainerHeight = jQuery('#fyc_button_container').css('height');
		jQuery('#fyc_button_container').css('height',$fycButtonContainerHeight);
		var $graphicContainerPHeight = jQuery('#graphic_container p').css('height');
		jQuery('#graphic_container p').css('height', $graphicContainerPHeight);
	}

	var $graphicContainerPHeight = jQuery('#graphic_container p').css('height');
	jQuery('#graphic_container p').css('height', $graphicContainerPHeight);
	var $graphic_containerPaddingTop = jQuery('#graphic_container').css('padding-top');
	var $graphic_containerPaddingBottom = jQuery('#graphic_container').css('padding-bottom');
	var $graphic_containerPaddingTopVal = $graphic_containerPaddingTop.replace(/px/g, "");
	var $graphic_containerPaddingBottomVal = $graphic_containerPaddingTop.replace(/px/g, "");
	setTimeout(function(){  
		var $fycButtonContainerHeight = jQuery('#fyc_button_container').css('height');
		jQuery('#fyc_button_container').css('height',$fycButtonContainerHeight);
	}, 400);

	function $textAlign() {  
		jQuery('#graphic_container h1').css({
		  'text-align':'left',
		});
		jQuery('.fyc_source_banner').css({
		  'text-align':'left',
		  'padding-left':'1rem',
		});
	}
  
	function $graphic_containerCollapseSmaller() { 
		jQuery('#graphic_container p').css({
			'height':'0',
			'opacity':'0',	
		});
		jQuery('#graphic_container').css({
			'padding-top':(($graphic_containerPaddingTopVal/1.3) + "px"),
			'padding-bottom':'0',
		});
	}
	  
	function $graphic_containerCollapseSmall() { 
		jQuery('#graphic_container p').css({
			'height':'0',
			'opacity':'0',	
		});
		jQuery('#graphic_container').css({
			'padding-top':(($graphic_containerPaddingTopVal/2.2) + "px"),
			'padding-bottom':'0',
		});
	}

	function $graphic_containerCollapseMedium() { 
		jQuery('#graphic_container p').css({
			'height':'0',
			'opacity':'0',	
		});
		jQuery('#graphic_container').css({
			'padding-top':(($graphic_containerPaddingTopVal/3.5) + "px"),
			'padding-bottom':'0',
		});
	}

	function $graphic_containerCollapseLarge() { 
		jQuery('#graphic_container p').css({
			'height':'0',
			'opacity':'0',	
		});
		jQuery('#graphic_container').css({
			'padding-top':(($graphic_containerPaddingTopVal/6) + "px"),
			'padding-bottom':'0',
		});
	}

	function collapseGraphicOpenFycPage() {
		if (jQuery(window).width() < 640) {
			$graphic_containerCollapseSmall()
		}
		if (jQuery(window).width() < 400) {
			$graphic_containerCollapseSmaller()
		}
		if (jQuery(window).width() >= 640) {
			$graphic_containerCollapseMedium()
			$textAlign();
		}
		if (jQuery(window).width() >= 1024) {
			$graphic_containerCollapseLarge()
			$textAlign();
		}
		jQuery('#fyc_button_container').css('height','0');
		jQuery('.fyc_page_container').css({
			'right' : '0',
			'top' : '0',
			'position' : 'relative',
		});
	}
	  
	// Button Hover States
	jQuery('.fyc_button').hover(function() {
		var $graphic = jQuery(this).find('.fyc_button_graphic');
		var $label = jQuery(this).find('.fyc_button_label');

		var $labelSize = $label.css('font-size');
		$labelSize = $labelSize.replace(/px/g, "");
		$labelSize = $labelSize * 1.02;
		$label.css({
			'text-decoration':'underline',
			'opacity': '.95',
			'font-size': $labelSize,
		});
		$graphic.css({
			'opacity':'1',
		});
	}, function() {
		var $label = jQuery(this).find('.fyc_button_label');
		var $graphic = jQuery(this).find('.fyc_button_graphic');
		$label.removeAttr('style');
		$graphic.removeAttr('style');
	});

	function adjustBackgroundGraphic() {
		var $offset = jQuery('#graphic_container p').offset();
		$offset.top = $offset.top * .4;
		jQuery("html, body").animate({ scrollTop: $offset.top });
	}

	jQuery(document).on("click", ".fyc_button", function () {
		window.clickedBtnID = jQuery(this).attr('id');
		let clickData;
		let incomingFirstYearExtra = '';
		switch(window.clickedBtnID) {
			case 'fyc_ify_button':
				clickData = {counselorType: 'incoming-first-year', bannerText: 'INCOMING FIRST YEARS'}
				break;
			case 'fyc_is':
				clickData = {counselorType: 'international-students', bannerText: 'INTERNATIONAL STUDENTS'}
				break;
			case 'fyc_ts':
				clickData = {counselorType: 'transfer-students', bannerText: 'TRANSFER STUDENTS'}
				break;
			case 'fyc_gs':
				clickData = {counselorType: 'graduate-students', bannerText: 'GRADUATE STUDENTS'}		
				break;
		}

		collapseGraphicOpenFycPage();
		adjustBackgroundGraphic();

		let fycPageContainer = document.getElementById('fyc_page_container');

		if(clickData.counselorType == 'incoming-first-year') {
			incomingFirstYearExtra = '<div id="fyc_form_container"><p>Enter your high school zip code in the field to the right, or if a homeschool student click the button below.<br><span id="hs_toggle"><button id="homeschool-button" class="button-solid button-solid--color-white" onclick="homeschool();" >HOMESCHOOL STUDENT</button></span></p><form onsubmit="return false" id="ify_form"><input class="global-search__input" type="text" name="zip" value="" id="geocode_input" placeholder="ZIP CODE"></input><button class="button-solid button-solid--color-white t-p1 sketches__wrapper sketches__hover" href="#" onclick="zipSubmit()">SUBMIT</button></form></div>';
		}
		
		let markup = `<div class="fyc_source_banner" id="fyc_ify_banner"><div class="container">${clickData.bannerText}<button id="close-button" tabindex="0" onclick="closeSection(this)" class="butler-icon butler-icon-1x bi-close" aria-hidden="true"></button></div></div>${incomingFirstYearExtra}<div id="fyc_counselor_container" class="container"></div>`;

		fycPageContainer.setAttribute('open', '');
		jQuery('.fyc_page_container').prepend(markup);
		if(clickData.counselorType == 'incoming-first-year') {
			jQuery('#fyc_ify_results_banner_container').css('padding','0');
		}else{
			getCounselor(clickData.counselorType);
		}
		openDialog('dialog-container', window.clickedBtnID, '');
	});
});

function finishClose() {
	jQuery('.fyc_button_graphic, .fyc_button_label, #graphic_container p, #graphic_container, #fyc_form_container, #graphic_container h1, #fyc_ify_results_banner_container, .fyc_page_container, #fyc_button_container, .counselor_item').removeAttr('style');
	jQuery('.fyc_page_container, .fyc_source_banner, .fyc_results_banner_container').html('');
	jQuery('.fyc_results_banner_container').html('');
	jQuery('#' + window.clickedBtnID).focus();
}

function closeSection(closeButton) {
	var offset = jQuery('#graphic_container p').offset();
	offset.top = offset.top * .4;
	jQuery("html, body").animate({ scrollTop: offset.top });
	jQuery('.counselor_item').css('top','-90vh');
	jQuery('.fyc_page_container').css('height', '0');
	closeDialog(closeButton);
	finishClose();
}

function finishBackStep() {
	if(window.localSelect) {
		outputIpsSelect();
	}
	jQuery('#fyc_counselor_container').html('');
	jQuery('#fyc_form_container').css('height','');
	var $fycFormContainerHeight = jQuery('#fyc_form_container').css('height');
	jQuery('#fyc_form_container').css('height','0');
	jQuery('#fyc_form_container').css('height',$fycFormContainerHeight);
	jQuery('#hs_toggle input').attr('checked',false);	
	jQuery('.counselor_item').removeAttr('style');
	jQuery('#fyc_form_container').removeClass('hidden');

	if(window.homeschoolButton) {
		setTimeout(function () {
			jQuery('#homeschool-button').focus();
		}, 100);
		window.homeschoolButton = false;
	}
	if(window.zipButton) {
		setTimeout(function () {
			jQuery('#geocode_input').focus();
		}, 100);
		window.zipButton = false;
	}
}

function $backStep() {
	jQuery('#fyc_counselor_container').css('height', '0');
	jQuery('.counselor_item').css('top','-90vh');
	jQuery('.fyc_results_banner').html('');
	jQuery('.fyc_results_banner').css('padding', '0');
	finishBackStep();
}

//Fix Sticky Menu Snap
jQuery(window).scroll(function() {
	if (jQuery(window).width() >= 960) {
		if (jQuery('body').hasClass("sticky-menu")) {
			jQuery('#panels-ipe-regionid-hero .main-layout-pane').css('margin-top','2.75rem');
		} else {
			jQuery('.main-layout-pane').removeAttr('style');
		}
	}
});

function zipSubmit() {
	// Use Zipcode value to make results banner
	let zipcode = jQuery('#geocode_input').val();
	jQuery('#fyc_form_container').css('height','0');
	jQuery('#fyc_ify_results_banner_container').removeAttr('style');

	var $offset = jQuery('#geocode_input').offset();
	$offset.top = $offset.top * .4;
	jQuery("html, body").animate({ scrollTop: $offset.top });
	jQuery('#fyc_counselor_container').removeAttr('style');
	window.zipButton = true;
	getLocation();  
}

/*
 * Use the WP API to retreive Counselor data based on Zip code. This uses data stored in geo_zip a non WP table.
 */

function getLocation(){
	let zipcode = jQuery('#ify_form').find('input[name="zip"]').val();
	jQuery.ajax({
		url: ajaxUrl,
		type: 'POST',
		dataType: 'JSON',
		data: {
			action: 'query_zip_geo_table',
			zip: zipcode,
		},
		success: function (resp) {
			if( resp.success ) {
				ajaxCall(resp.data);
			}else{
				console.log ('Error: ' + resp.data );
			}
		},
		error: function( xhr, ajaxOptions, thrownError ) {
			console.log(xhr);
			console.log('Request Failed: ' + thrownError.message + xhr );
		}
	});
}

function foundInfo(counselor){
	ajaxCall(counselor);
}
