var timer = Date.now();

var textfieldedit = false;

var insidetextfield = false;

var javascriptpageloaded = false;

var zoomscriptpageloaded = false;

var textfieldid = "";

var idleTime = 0;

var blurryimageloaded = true;

var idsimagecall = "DiplomaPreviewWooSignatures"; //set the default in product js 

var thumbnaildisplay;

var thumbnaildisplayid;

var imagesdirectory = "";

var scriptdirectory = "";
var cssdirectory = "";

var debugmode = true;

var switchingsections = false;

var thumbnailwidth = 100;

var thumbnailheight = 100;

var thumbnailstep = 0.5;

var skipcurrentimagecall = false;

var callproductlevelrefreshimage = false;

var globalthumbnailtimestamp = null;

var delayedconsoledisplay = false;

var testsealelement;

const delay = ms => new Promise(res => setTimeout(res, ms)); 

var pagenavigationcontrol = false;
var addtocartjustclicked = false;

var skipuserroles = false;
var javascriptpage = "";

var manuallyclicksavedesign = false;

var busyreloadingvars = false;

var schoolnameexclusions;

var capgownsize = "";

jQuery(document).ready(function ($) {

	console.log("HomeschoolDiploma Main.js loaded");
    
	var jspageelement = document.getElementById("HomeschoolDiplomaProductSlug");
	if(!jspageelement)
	{
		console.log("no js located");
		//widget isn't present, exit
		return;
	}
/*
    //Code to fix the comments.  this inserts a <br> for every enter key ("\n").  if the <br> is deleted or malformed, it reinserts
	var commentsfield = document.getElementById("comment");
    if(commentsfield != null){
        commentsfield.addEventListener('keyup', function(event) {
            if(event.key == "Enter"){
                var myfield = this.value;
                var cursorpos = this.selectionStart;
                var index = -1;
                index = myfield.indexOf("\n");
                while(index > -1)
                {
                    if(index == (myfield.length-1))
                    {
                        //we are at the end
                        myfield = myfield + "<br>";
                        index = -1;
                        cursorpos += 4;
                    }
                    else
                    {
                        //somewhere in the middle, look for </br> after
                        if(myfield.charAt(index+1) == "\n")
                        {
                            myfield = myfield.substring(0, index+1) + "<br>" + myfield.substring(index+1);
                            cursorpos += 4;
                        }
                        else
                        {
                            //also fix any broken <br>'s
                            if(myfield.substring(index+1, index+5) != "<br>")
                            {
                                //fix it
                                myfield = myfield.substring(0, index+1) + "<br>" + myfield.substring(index+1);
                                cursorpos += 4;
                            }
                        }
                        index = myfield.indexOf("\n", index+1);
                    }
                }
                this.value = myfield;
                this.selectionStart = this.selectionEnd = cursorpos;
            }
            imageswitchcase = 0;
        });
    }
*/
    //ipad specific (also iphones)
    /*
    if(navigator.maxTouchPoints && navigator.userAgent.includes('Safari') && !navigator.userAgent.includes('Chrome'))
    {
        var mobileselects = document.querySelectorAll('select');

		for (const mobileselect of mobileselects) {



			if(mobileselect.className.includes("hd_"))

			{

				if(!mobileselect.firstElementChild.value.includes("_0"))

				{

					mobileselect.removeChild(mobileselect.firstElementChild);
				}

			}

		};
    }
    */

    //hide save to favorites for certain cases
    var hidesavetofavorites = false;
    //check to see if "have been added to your cart" is present
    if(document.URL.includes("cart_item_key"))
        hidesavetofavorites = true;
    if(document.URL.includes("umeta_id") && !document.URL.includes("design_nickname"))
    {
        hidesavetofavorites = true;
    }
    if(hidesavetofavorites)
    {
        var savetofavoriteslinks = document.getElementsByClassName("save_design_btn");
        if(savetofavoriteslinks[0])
        {
            savetofavoriteslinks[0].classList.add("hd_hideelement");
        }
    }


	 //hdwidget.className;//load the .js file based off the page
//	var jspageelement = document.querySelectorAll('[class*="homeschooldiplomawidgetjs"]');
//	var arrayconvert = Array.from(jspageelement);
//	var arraylength = arrayconvert.length;
//	if(arraylength < 1)


	javascriptpage = jspageelement.innerHTML;
//	var elementchild = jspageelement[0].firstElementChild.nextElementSibling;
//	javascriptpage = elementchild.innerHTML;
//	javascriptpage = javascriptpage.replace('<p>', '');
//	javascriptpage = javascriptpage.replace('</p>', '');
//	javascriptpage = javascriptpage.trimEnd();

/*
    var scripts = document.getElementsByTagName('script');
    for(var i=0; i<scripts.length; i++)

    {

        if(scripts[i].id.includes('hs-main-script-js'))

        {

            var start = 0;

            var scriptsrc = scripts[i].src;

            start = scriptsrc.indexOf('/homeschooldiploma/js/main.js');

            scriptdirectory = scriptsrc.substring(0, start);

            imagesdirectory = scriptdirectory + "/homeschooldiploma/images/";
			cssdirectory = scriptdirectory + "/homeschooldiploma/css/";
            scriptdirectory = scriptdirectory + "/homeschooldiploma/js/";

            break;

        }

    }
*/
	var hdbaseurl = document.getElementById("HomeschoolDiplomaBaseURL").innerHTML;
	imagesdirectory = hdbaseurl + "/homeschooldiploma/images/";
	cssdirectory = hdbaseurl + "/homeschooldiploma/css/";
	scriptdirectory = hdbaseurl + "/homeschooldiploma/js/";


	//zoom js is now loaded in php and deferred
//	var zoomjavascriptpage = scriptdirectory + 'js-image-zoom.js';

//	$.getScript( zoomjavascriptpage, function( data, textStatus, jqxhr ) {

//	  });

	//in timer function, if the zoom page is loaded, then set the vars

	thumbnaildisplayid = "NOTHUMBNAILS";

/*
	var mainimagename = ""; //hdwidget.className;//load the .js file based off the page
	var mainimageelement = document.querySelectorAll('[class*="homeschooldiplomawidgetimage"]');
	var mainimagearrayconvert = Array.from(mainimageelement);
	var mainimagearraylength = mainimagearrayconvert.length;
	if(mainimagearraylength < 1)
	{
	}
    else
    {
        var mainimageelementchild = mainimageelement[0].firstElementChild.nextElementSibling;
        mainimagesrc = mainimageelementchild.innerHTML;
        mainimagesrc = mainimagesrc.replace('<p>', '');
        mainimagesrc = mainimagesrc.replace('</p>', '');
        mainimagesrc = mainimagesrc.trimEnd();
        if(support_format_webp)
        {
            mainimagename = imagesdirectory + mainimagesrc + ".webp";
        }
        else
        {
            //webp not supported
            mainimagename = imagesdirectory + mainimagesrc + ".jpg";
        }
        RefreshMainImage(mainimagename, true);
    }
*/

    if(javascriptpage == "diploma-cover-customized-with-logo")
    {
        skipuserroles = true;
    }

	//var wooattribute = document.getElementsByClassName('woocommerce-product-attributes shop_attributes');
	//wooattribute[0].style.display = "none"; //not doing anything

	//load the js 
//	javascriptpage = scriptdirectory + javascriptpage + '.js';
//	$.getScript( javascriptpage, function( data, textStatus, jqxhr ) {
//	  });

	var producttabs = document.querySelectorAll('[class*="elementor-widget-woocommerce-product-data-tabs"]');
	if(producttabs.length == 1)
	{
		producttabs[0].parentNode.removeChild(producttabs[0]);
	}

	var idleInterval = setInterval(timerIncrement, 1000); //every second

	//remove red *
	var redastericks = document.querySelectorAll('[class*="tm-epo-required"]');
	redastericks.forEach(function(redasterick){
		redasterick.innerHTML = "";
	});

    //remove tassel large quantity message
    var largequantitymessage = document.getElementsByClassName("hd_Large_Quantity_Tassel");
    if(largequantitymessage.length > 0)
    {
        largequantitymessage[0].classList.add("hidden");
    }

    //move the umetainput into the main form
    var umetainput = document.getElementById("CHECK_FOR_UMETA");
    if(umetainput)
    {
        var addtocartbutton = document.getElementsByClassName("single_add_to_cart_button");
        if(addtocartbutton.length > 0)
            addtocartbutton[0].parentNode.appendChild(umetainput);
    }


	$(document).ready(function () {
        //process user roles
		HideCustomOptions();

        //insert deliverydate

//        var hdcalculateddeliverydate = document.getElementsByClassName("hdCalculatedDeliveryDate")[0];

//        var hddisplaydeliverydate = document.getElementsByClassName("hdDisplayDeliveryDate")[0];

//        if(hdcalculateddeliverydate)

//        {

//            if(hddisplaydeliverydate)

//            {

//                hddisplaydeliverydate.innerHTML = hdcalculateddeliverydate.innerHTML;

//            }

//        }



		//testing capture all clicks on document

//		document.addEventListener('click', AllClicks);

        var buttons = document.querySelectorAll('button');
        for(const button of buttons){
            if(button.name == 'add-to-cart')
            {
                button.addEventListener('click', AddToCartButton);
            }
        }

		var inputs = document.querySelectorAll('input');
		var selects = document.querySelectorAll('select');
		var textareas = document.querySelectorAll('textarea');
		for (const input of inputs) {
			input.addEventListener('change', InputListener);
			//add secondary listener for text fields
			if (input.id.includes("textfield")) {
				input.addEventListener('input', TextListener);
				input.addEventListener('keypress', function(event){
					if(event.key == 'Enter'){
						event.preventDefault();
					}
				});
            };
		};

		for (const select of selects) {
			select.addEventListener('change', SelectListener);
            //select.addEventListener('click', SelectInitRemoveFirstOption);
			select.addEventListener('onclick', MobileRemoveFirstOption);
		};

		for (const textarea of textareas)
		{
			textarea.innerHTML = textarea.innerHTML.replaceAll("&amp;#039;", "'");
			textarea.addEventListener('input', TextListener);
			textarea.addEventListener('change', InputListener);
		};

		//live preview image height removal
		let observer_livepreview = new MutationObserver(mutations =>{
			mutations.forEach(function(mutation){
				mutation.target.style.height = '';
			});
		});
		var imgwidget = document.getElementById("HomeschoolDiplomaLivePreview");
		observer_livepreview.observe(imgwidget, { attributes : true, attributeFilter : ['style'] });
/*		

		//plus signs

		let plusNode = document.createElement("span");

		plusNode.innerHTML = "+";

		plusNode.style.color = 'black';

		var plussigns = document.getElementsByClassName('tc-price-wrap');

		for(var i=0; i< plussigns.length; i++)

		{

			if(plussigns[i].firstElementChild.firstElementChild)

			{

				plussigns[i].insertBefore(plusNode.cloneNode(true), plussigns[i].firstElementChild);

			}

		}
*/

//        window.addEventListener('beforeunload', function (event) { 
//				var pagenavigationcontrol = GetPageNavigationControl();
//				if(pagenavigationcontrol)
//				{
//                	event.preventDefault();
//                	event.returnValue = '';
//				}
//        });
	});

	$(document).each(function () {
	});
});

function HideCustomOptions(){
	var hdcustomerrole = document.getElementById("hdcustomerrole");
    if(!hdcustomerrole)
        return;
    var roles = hdcustomerrole.innerHTML;
    var hd_umetadata_element = document.getElementById("hd_umetadata");
    var hd_umetadata = "";
    if(hd_umetadata_element)
        hd_umetadata = hd_umetadata_element.innerHTML;
    var umetavalue = "";
	if(hdcustomerrole && !skipuserroles)  //if user roles defined and not cover with logo
	{
		if(roles.includes('customerwithcustomdiplomaseal')){}
		else
		{
            umetavalue = SearchUmeta("hd_SealDesign", hd_umetadata);
            if(umetavalue != "Your Custom Design")
            {
                //delete it
                var hdcustomdipseal = document.querySelectorAll('input[value^="Your Custom Design"][class*="hd_SealDesign"]');
                if(hdcustomdipseal[0]){
                    hdcustomdipseal[0].parentElement.parentElement.parentElement.removeChild(hdcustomdipseal[0].parentElement.parentElement);
                }
            }
		}
		if(roles.includes('customerwithcustom2colordiplomaseal')){}
		else
		{
            umetavalue = SearchUmeta("hd_SealDesign", hd_umetadata);
            if(umetavalue != "Your Custom 2-Color Design")
            {
                //delete it
                var hdcustom2colordipseal = document.querySelectorAll('input[value^="Your Custom 2-Color Design"][class*="hd_SealDesign"]');
                if(hdcustom2colordipseal[0]){
                    hdcustom2colordipseal[0].parentElement.parentElement.parentElement.removeChild(hdcustom2colordipseal[0].parentElement.parentElement);
                }
            }
		}
		if(roles.includes('customerwithfoilstampingdie')){}
		else
		{
            umetavalue = SearchUmeta("hd_CoverDesign", hd_umetadata);
            if(umetavalue != "Your Custom Design")
            {
                //delete both cover customs
                var hdcustomcoverdesign = document.querySelectorAll('input[value^="Your Custom Design"][class*="hd_CoverDesign"]');
                if(hdcustomcoverdesign[0]){
                    hdcustomcoverdesign[0].parentElement.parentElement.parentElement.removeChild(hdcustomcoverdesign[0].parentElement.parentElement);
                }
            }
            if(umetavalue != "Your Custom Design With Text")
            {
                var hdcustomcovertextdesign = document.querySelectorAll('input[value^="Your Custom Design With Text"][class*="hd_CoverDesign"]');
                if(hdcustomcovertextdesign[0]){
                    //hdcustomcovertextdesign[0].parentElement.parentElement.style.display = "none";
                    hdcustomcovertextdesign[0].parentElement.parentElement.parentElement.removeChild(hdcustomcovertextdesign[0].parentElement.parentElement);
                }
            }
		}

		if(roles.includes('customerwithcustomannouncementseal')){}
		else
		{
            umetavalue = SearchUmeta("hd_Crest", hd_umetadata);
            if(umetavalue != "Your Custom Design")
            {
                var hdcustomannouncementseal = document.querySelectorAll('input[value^="Your Custom Design"][class*="hd_Crest"]');
                if(hdcustomannouncementseal[0]){
                    hdcustomannouncementseal[0].parentElement.parentElement.parentElement.removeChild(hdcustomannouncementseal[0].parentElement.parentElement);
                }
            }
		}
		if(roles.includes('customerwithextrasignaturelines')){}
		else
		{
            umetavalue = SearchUmeta("hd_Signatures", hd_umetadata);
            if(!umetavalue.includes("Custom Signature Line"))
            {
                var hdcustomlines = document.querySelectorAll('option[value*="Custom Signature Line"');
                if(hdcustomlines[2]){
                    hdcustomlines[2].parentElement.removeChild(hdcustomlines[2]);
                }
                if(hdcustomlines[1]){
                    hdcustomlines[1].parentElement.removeChild(hdcustomlines[1]);
                }
                if(hdcustomlines[0]){
                    hdcustomlines[0].parentElement.removeChild(hdcustomlines[0]);
                }
            }
		}
		if(roles.includes('customerwithcustomtext')){}
		else
		{
            umetavalue = SearchUmeta("hd_DiplomaWording", hd_umetadata);
            if(!umetavalue.includes("My Custom Wording"))
            {
                var hdcustomtext = document.querySelectorAll('option[value*="My Custom Wording"');
                if(hdcustomtext[0]){
                    hdcustomtext[0].parentElement.removeChild(hdcustomtext[0]);
                }
            }
		}
		if(roles.includes('customerwithprivateedseal')){}
		else
		{
            umetavalue = SearchUmeta("hd_SealDesign", hd_umetadata);
            if(!umetavalue.includes("Private Education"))
            {
                var hdprivateedseal = document.querySelectorAll('input[value*="\'Private Education\' Engraved"]');//****************not sure on wording */
                if(hdprivateedseal[0]){
                    hdprivateedseal[0].parentElement.parentElement.style.display = "none";
                }
            }
		}
        if(roles.includes('nodiplomacover')){}
        else
        {
            umetavalue = SearchUmeta("hd_CoverColor", hd_umetadata);
            if(umetavalue != "None")
            {
                var hdnodiplomacover = document.querySelectorAll('input[class*="hd_CoverColor"][value*="None"]');
                if(hdnodiplomacover[0]){
                    hdnodiplomacover[0].parentElement.parentElement.style.display = "none";
                }
            }
        }
        if(roles.includes('nosealoption')){}
        else
        {
            umetavalue = SearchUmeta("hd_SealDesign", hd_umetadata);
            if(umetavalue != "No Seal")
            {
                var hdnosealoption = document.querySelectorAll('input[class*="hd_SealDesign"][value*="No Seal"]');
                if(hdnosealoption[0]){
                    hdnosealoption[0].parentElement.parentElement.style.display = "none";
                }
            }
        }
        if(roles.includes('specialinstructions')){}
        else
        {
            umetavalue = SearchUmeta("hd_SpecialInstructions", hd_umetadata);
            if(umetavalue == "")
            {
                var hdspecialinstructions = document.querySelectorAll('input[class*="hd_SpecialInstructions"]');
                if(hdspecialinstructions[0]){
                    hdspecialinstructions[0].parentElement.parentElement.parentElement.style.display = "none";
                }
            }
        }
		if(roles.includes('customerwithshinygowns')){}
		else
		{
			var proceedtohideshiny = true;

			if(document.URL.includes("cart_item_key"))
				proceedtohideshiny = false;
			if(document.URL.includes("design_nickname"))
				proceedtohideshiny = false;
			if(document.URL.includes("umeta_id"))
				proceedtohideshiny = false;

			//if it is false, it is a package or coming from cart

			if(proceedtohideshiny)
			{
				var hd_umetadata_element = document.getElementById("hd_umetadata");
				var hd_umetadata = "";
				if(hd_umetadata_element)
				{
					hd_umetadata = hd_umetadata_element.innerHTML;
				}
				//hide all the shiny options in setup
				var hd_fabriccolorall = document.getElementsByClassName("hd_FabricColorAll");
				if(hd_fabriccolorall)
				{
					if(hd_fabriccolorall.length > 0)
					{
						for (var i=0; i<hd_fabriccolorall[0].length; i++) {
							if (hd_fabriccolorall[0].options[i].value.startsWith("Shiny "))
								hd_fabriccolorall[0].remove(i);
						}
					}
				}
				var hd_fabriccolorboys = document.getElementsByClassName("hd_FabricColorBoys");
				if(hd_fabriccolorboys)
				{
					if(hd_fabriccolorboys.length > 0)
					{
						for (var i=0; i<hd_fabriccolorboys[0].length; i++) {
							if (hd_fabriccolorboys[0].options[i].value.startsWith("Shiny "))
								hd_fabriccolorboys[0].remove(i);
						}
					}
				}
				var hd_fabriccolorgirls = document.getElementsByClassName("hd_FabricColorGirls");
				if(hd_fabriccolorgirls)
				{
					if(hd_fabriccolorgirls.length > 0)
					{
						for (var i=0; i<hd_fabriccolorgirls[0].length; i++) {
							if (hd_fabriccolorgirls[0].options[i].value.startsWith("Shiny "))
								hd_fabriccolorgirls[0].remove(i);
						}
					}
				}
			}
		}
	}
    else
    {
        //so far just cover logo needs some user roles work
        if(roles.includes('specialinstructions')){}
        else
        {
            umetavalue = SearchUmeta("hd_SpecialInstructions", hd_umetadata);
            if(umetavalue == "")
            {
                var hdspecialinstructions = document.querySelectorAll('input[class*="hd_SpecialInstructions"]');
                if(hdspecialinstructions[0]){
                    hdspecialinstructions[0].parentElement.parentElement.parentElement.style.display = "none";
                }
            }
        }
    }
}

function GetPageNavigationControl()
{
	return pagenavigationcontrol;
}

function AddToCartButton() {
    if(pagenavigationcontrol)
    {
		console.log("addtocartbutton");
        pagenavigationcontrol = false;
        addtocartjustclicked = true;
    }
}
function AllClicks(){
    if(addtocartjustclicked)
    {
		console.log("cart clicked")
        addtocartjustclicked = false;
        pagenavigationcontrol = true;
    }
	console.log("pagenavigationcontrol:  " + pagenavigationcontrol);
}

function displayconsole(event) {

	//displaying for testing only

	if(debugmode) console.log("Click:");

	if(debugmode) console.log(event.path);

};



function timerIncrement() {

	idleTime += 1;

	if(delayedconsoledisplay)

	{

		//this is for seals, if the year is changed and a year seal is selected, do not refresh

		//let the first refresh for all 3 go

		//testsealelement.click();

	}

	if (textfieldedit) {

		//after 3 seconds, load image and set textfieldedit to false to reset counters

		if (idleTime > 1) {

			textfieldedit = false;

			if(callproductlevelrefreshimage){

				ProductLevelRefreshImages();

			}

			else

				RefreshImage();

		};

	};

	if(!javascriptpageloaded){

		if(typeof BuildJSON == 'function'){

			javascriptpageloaded = true;

			MyDocumentReadyFunction();

            //save the umeta_id to the hd_Umeta_ID text for future reference
            var umeta_id_element = document.getElementsByClassName("hd_Umeta_ID");
            if(umeta_id_element[0])
            {
                if(document.URL.includes("umeta_id"))
                {
                    var umeta_id = getUrlParameter('umeta_id');
                    umeta_id_element[0].value = umeta_id;
                }
                //reinsert umeta_id div if returning from cart
                if(document.URL.includes("tm_cart_item_key"))
                {
                    var inputelement = document.createElement("input");
                    inputelement.setAttribute('type', 'hidden');
                    inputelement.setAttribute('id', 'CHECK_FOR_UMETA');
                    inputelement.setAttribute('name', 'CHECK_FOR_UMETA');
                    inputelement.value = umeta_id_element[0].value;
                    umeta_id_element[0].parentElement.appendChild(inputelement);
                }
            }
		};

	};

	if(!zoomscriptpageloaded){

		if(typeof ImageZoom == 'function'){
			console.log("zoom loaded");
			zoomscriptpageloaded = true;

			RefreshZoom();

		}
	};

	if(manuallyclicksavedesign)
	{
		manuallyclicksavedesign = false;
		ClickSaveToFavorites();
	}
};



function RefreshZoom(){

	var hdwidget = document.getElementById('HomeschoolDiplomaWidget');

	//get rid off any old zoom elements

	for (var i = hdwidget.children.length-1; i > -1; i--) {

		if (hdwidget.children[i].className.includes('js-image-zoom')) {

			hdwidget.removeChild(hdwidget.children[i]);

		}

	}

	var options1 = {

		fillContainer: true,

		offset: {vertical: 0, horizontal: 10},

		zoomPosition: 'original'

	};

	new ImageZoom(hdwidget, options1);
};



function InputListener() { //based off losing focus/changing
    if(!pagenavigationcontrol)
    {
        if(this.className.includes('hd_'))
        {
            pagenavigationcontrol = true;
        }
    }
	//if(ProductInputListener(this.id))//handle any special cases (x on radio)

	//	RefreshImage();

	if(delayedconsoledisplay){

		delayedconsoledisplay = false;

		return;

	}



	if(insidetextfield)

	{

		//leaving a text field

		insidetextfield = false;

		return;

	}

	if(testsealelement)

	{

		testsealelement = null;

		return;

	}
	if(MapVariables(this.className, this.value, this))

	{
		timer = Date.now() - 1000*(60*5);

		if(callproductlevelrefreshimage)

			ProductLevelRefreshImages();

		else

			RefreshImage();

	}

};



function TextListener() { //based off text changing
    if(!pagenavigationcontrol)
    {
        if(this.className.includes('hd_'))
        {
            pagenavigationcontrol = true;
        }
    }

	if (!textfieldedit) {

		//init in textfield

		textfieldedit = true;

	}

	if(!insidetextfield)

		insidetextfield = true;

	idleTime = 0;

	if(MapVariables(this.className, this.value, this))
    {
    }

	else

		textfieldedit = false;

	//no refreshimage here, handled in the timer function

};



function SelectListener() { //based off selects changing
    if(!pagenavigationcontrol)
    {
        if(this.className.includes('hd_'))
        {
            pagenavigationcontrol = true;
        }
    }

	timer = Date.now() - 1000*(60*5);

	if(MapVariables(this.className, this.value, this))

	{
		if(callproductlevelrefreshimage)

			ProductLevelRefreshImages();

		else

			RefreshImage();

	}
	else
	{
		if(document.URL.includes("clearance"))
		{
			//only clearance items check for oos
			var outofstockelement = document.getElementById("HomeschoolDiplomaOutOfStock");
			if(this.value.startsWith("Size "))
			{
				capgownsize = this.value;
				if(capgownsize.indexOf(")_") > -1)
				{
					capgownsize = capgownsize.substring(0, capgownsize.indexOf("(") - 1);
				}
				var searchstr = "Gown|" + capgownfabric + "|" + capgowncolor + "|" + capgownsize;
				if(outofstockelement.innerHTML.includes(searchstr))
				{
					alert("It looks like that combination of fabric, color, and size is out of stock.  Please consider moving up or down in size.");
				}
			}
		}
	}

};
/*
function SelectInitRemoveFirstOption(){
    if(!pagenavigationcontrol)
    {
        if(this.className.includes('hd_'))
        {
            pagenavigationcontrol = true;
        }
    }

    if(this.firstElementChild.value == "")

	{
        this.removeChild(this.firstElementChild);

		if(MapVariables(this.className, this.value, this)){}

		else
        {
			//console.log("selectinit map returned false");
        }
//		timer = Date.now() - 1000*(60*5);

//		if(callproductlevelrefreshimage)

//			ProductLevelRefreshImages();

//		else

//			RefreshImage();

	}

    this.removeEventListener('click', SelectInitRemoveFirstOption);

}
*/


function MobileRemoveFirstOption(){
    if(!pagenavigationcontrol)
    {
        if(this.className.includes('hd_'))
        {
            pagenavigationcontrol = true;
        }
    }

    if(this.firstElementChild.value == "")

	{
        this.removeChild(this.firstElementChild);

		MapVariables(this.className, this.value, this);

//		timer = Date.now() - 1000*(60*5);

//		if(callproductlevelrefreshimage)

//			ProductLevelRefreshImages();

//		else

//			RefreshImage();

	}

    this.removeEventListener('click', SelectInitRemoveFirstOption);

}



function IndividualKeys() {

	console.log(this.target);

}



async function RefreshImage(jsonstringtype = undefined, previewcall = idsimagecall, changethumbnail = thumbnaildisplayid, updatemainimage = true) {

	// jsonstringtype will override the global setting and call a specific json string

	// previewcall will talk to a specific ids script

	// changethumbnail will be the element id of the thumbnail you want changed

	// updatemainimage true/false for just thumbnail update or all

	if (switchingsections){

		//do nothing if just switching sections

		switchingsections = false;

		return;

	}

	if(skipcurrentimagecall)

	{

		skipcurrentimagecall = false;

		return;

	}



	//reset timer if < 3 seconds

	const seconds = Math.floor((Date.now() - timer) / 1000)

	if (seconds <= 1 && updatemainimage) {

		return;

	}

	timer = Date.now();

	//reset image
	url = 'https://images.homeschooldiploma.com/HomeschoolDiploma/indesign/create/' + previewcall;

	const imageelement = document.getElementById('HomeschoolDiplomaLivePreview');

	imageelement.classList.add("hd_blurimg");

	if(changethumbnail != "NOTHUMBNAILS"){

		const thumbelement = document.getElementById(changethumbnail);

		thumbelement.classList.add("hd_blurimg");		

	}

	var strImgURL = "";

	strImgURL = await GetJSONImageURL(jsonstringtype, previewcall);

	var img = new Image();

	img.crossOrigin = "Anonymous";

	img.onload = function() {

		if(updatemainimage) {

			RefreshMainImage(this.src);

			ProductLevelChangeThumbnails();

		}

		ProductLevelUpdateThumbnailURL(this.src, changethumbnail);

		RefreshThumbnailImage(img, thumbnailwidth, thumbnailstep, changethumbnail);

	}

	img.src = strImgURL;

};

function support_format_webp()
{
 var elem = document.createElement('canvas');

 if (!!(elem.getContext && elem.getContext('2d')))
 {
  // was able or not to get WebP representation
  return elem.toDataURL('image/webp').indexOf('data:image/webp') == 0;
 }
 else
 {
  // very old browser like IE 8, canvas not supported
  return false;
 }
}

function RefreshMainImage(img, skipzoom = false)

{

	const largeimage = document.getElementById('HomeschoolDiplomaLivePreview');

	largeimage.src = img;

	largeimage.classList.remove("hd_blurimg");

	switchingsections = false;

	if(!skipzoom)
        RefreshZoom();

}



function RefreshThumbnailImageURL(strImgURL, changethumbnail, skipblur = false){
	var img = new Image();
	img.crossOrigin = "Anonymous";
	img.onload = function() {
		RefreshThumbnailImage(img, thumbnailwidth, thumbnailstep, changethumbnail, skipblur);
	}
	img.src = strImgURL;
}



function RefreshThumbnailImageURLHeight(strImgURL, changethumbnail){
	var img = new Image();
	img.crossOrigin = "Anonymous";
	img.onload = function() {
		RefreshThumbnailImage(img, thumbnailheight, thumbnailstep, changethumbnail);
	}
	img.src = strImgURL;
}



function RefreshThumbnailImage(img, width, step, imgdisplayid, skipblur = false) {

	if(thumbnaildisplayid == "NOTHUMBNAILS")

	{

		return;

	}

	var canvas = document.createElement('canvas'),

	ctx = canvas.getContext("2d"),

	oc = document.createElement('canvas'),

	octx = oc.getContext('2d');



	// -- stepped scaling --



	canvas.width = width; // destination canvas size

	canvas.height = canvas.width * img.height / img.width;



	if (img.width * step > width) { // For performance avoid unnecessary drawing

		var mul = 1 / step;

		var cur = {

			width: Math.floor(img.width * step),

			height: Math.floor(img.height * step)

		}



		oc.width = cur.width;

		oc.height = cur.height;



		octx.drawImage(img, 0, 0, cur.width, cur.height);



		while (cur.width * step > width) {

			cur = {

				width: Math.floor(cur.width * step),

				height: Math.floor(cur.height * step)

			};

			octx.drawImage(oc, 0, 0, cur.width * mul, cur.height * mul, 0, 0, cur.width, cur.height);

		}



		ctx.drawImage(oc, 0, 0, cur.width, cur.height, 0, 0, canvas.width, canvas.height);

	} else {

		ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

	}

	document.getElementById(imgdisplayid).src = canvas.toDataURL();

	if(!skipblur)
		document.getElementById(imgdisplayid).classList.remove("hd_blurimg");
}





function RefreshThumbnailImageHeight(img, height, step, imgdisplayid) {

	if(thumbnaildisplayid == "NOTHUMBNAILS")

	{

		return;

	}

	var canvas = document.createElement('canvas'),

	ctx = canvas.getContext("2d"),

	oc = document.createElement('canvas'),

	octx = oc.getContext('2d');



	// -- stepped scaling --



	canvas.height = height; // destination canvas size

	canvas.width = canvas.width * img.height / img.height;



	if (img.height * step > height) { // For performance avoid unnecessary drawing

		var mul = 1 / step;

		var cur = {

			height: Math.floor(img.height * step),

			width: Math.floor(img.width * step)

		}



		oc.width = cur.width;

		oc.height = cur.height;



		octx.drawImage(img, 0, 0, cur.width, cur.height);



		while (cur.height * step > height) {

			cur = {

				width: Math.floor(cur.width * step),

				height: Math.floor(cur.height * step)

			};

			octx.drawImage(oc, 0, 0, cur.width * mul, cur.height * mul, 0, 0, cur.width, cur.height);

		}



		ctx.drawImage(oc, 0, 0, cur.width, cur.height, 0, 0, canvas.width, canvas.height);

	} else {

		ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

	}

	document.getElementById(imgdisplayid).src = canvas.toDataURL();

	document.getElementById(imgdisplayid).classList.remove("hd_blurimg");

}



async function ProductLevelRefreshSingleImage(jsonstringtype = undefined, previewcall = idsimagecall, changethumbnail = thumbnaildisplayid) {

	// jsonstringtype will override the global setting and call a specific json string

	// previewcall will talk to a specific ids script

	// changethumbnail will be the element id of the thumbnail you want changed

	// updatemainimage true/false for just thumbnail update or all



	//reset image

/*

	var jsonstring = BuildJSON(jsonstringtype);

	url = 'https://images.homeschooldiploma.com/HomeschoolDiploma/indesign/create/' + previewcall;

	const imageelement = document.getElementById('HomeschoolDiplomaLivePreview');

	const Http = new XMLHttpRequest();

	blurryimageloaded = false

	Http.onreadystatechange = async function(){

		if(Http.readyState == XMLHttpRequest.DONE && Http.status == 200){

			var image_url = JSON.parse(Http.response).image;



			var img = new Image();

			img.crossOrigin = "Anonymous";

			img.onload = function() {

				const largeimage = document.getElementById('HomeschoolDiplomaLivePreview');

				largeimage.src = this.src;

				largeimage.classList.remove("hd_blurimg");

				RefreshThumbnailImage(img, thumbnailwidth, thumbnailstep, changethumbnail);

			}

			img.src = image_url;

		}

		else if (Http.status == 500){

			console.log("ERROR LOADING JSON Single Image");

		}

		else{

			//display blurry image

			if(!blurryimageloaded){

				imageelement.classList.add("hd_blurimg");

				blurryimageloaded = true;

			};

		};

	};

	Http.open("POST", url, true);

	Http.setRequestHeader("Content-Type", "application/json");

	Http.send(jsonstring);

*/
	url = 'https://images.homeschooldiploma.com/HomeschoolDiploma/indesign/create/' + previewcall;

	const imageelement = document.getElementById('HomeschoolDiplomaLivePreview');

	imageelement.classList.add("hd_blurimg");

	const thumbelement = document.getElementById(changethumbnail);

	thumbelement.classList.add("hd_blurimg");

	var strImgURL = "";

	strImgURL = await GetJSONImageURL(jsonstringtype, previewcall);

	var img = new Image();

	img.crossOrigin = "Anonymous";

	img.onload = function() {

		if(updatemainimage) {

			const largeimage = document.getElementById('HomeschoolDiplomaLivePreview');

			largeimage.src = this.src;

			largeimage.classList.remove("hd_blurimg");

			ProductLevelChangeThumbnails();

		}

		ProductLevelUpdateThumbnailURL(this.src, changethumbnail);

		RefreshThumbnailImage(img, thumbnailwidth, thumbnailstep, changethumbnail);

	}

	img.src = strImgURL;

};



async function ProductLevelRefreshSingleThumbnail(jsonstringtype = undefined, previewcall = idsimagecall, changethumbnail = thumbnaildisplayid) {

	// jsonstringtype will override the global setting and call a specific json string

	// previewcall will talk to a specific ids script

	// changethumbnail will be the element id of the thumbnail you want changed

	// updatemainimage true/false for just thumbnail update or all



	//reset image

	url = 'https://images.homeschooldiploma.com/HomeschoolDiploma/indesign/create/' + previewcall;

	const imageelement = document.getElementById(changethumbnail);

	imageelement.classList.add("hd_blurimg");

	var strImgURL = "";

	strImgURL = await GetJSONImageURL(jsonstringtype, previewcall);

	var img = new Image();

	img.crossOrigin = "Anonymous";

	img.onload = function() {

		RefreshThumbnailImage(img, thumbnailwidth, thumbnailstep, changethumbnail);

		const imageelement = document.getElementById(changethumbnail);

		imageelement.classList.remove("hd_blurimg");

		ProductLevelUpdateThumbnailURL(this.src, changethumbnail);

	}

	img.src = strImgURL;

};



async function GetJSONImageURL(jsonstringtype = undefined, previewcall = idsimagecall) {

	// jsonstringtype will override the global setting and call a specific json string

	// previewcall will talk to a specific ids script

	// changethumbnail will be the element id of the thumbnail you want changed

	// updatemainimage true/false for just thumbnail update or all



	//reset image

	var jsonstring = BuildJSON(jsonstringtype);

	url = 'https://images.homeschooldiploma.com/HomeschoolDiploma/indesign/create/' + previewcall;

	const requestOptions = {

		method: 'POST',

		headers: { 'Content-Type': 'application/json' },

		body: jsonstring

	};

	var strImgURL = "";

	const response = await fetch(url, requestOptions)

//		.then(response => response.json())
		.then(response => {
			if(response.status === 500){
				console.log("***************** BAD IMAGE ***************");
				return;
			}
			else
				return response.json();
		})

		.then(json => strImgURL = json.image)

		.catch(error => console.error('fetch error:', error));

	return strImgURL;

};



function getFirstSpanWithClass(cssClass) {

	var elements = document.getElementsByTagName('span');
	for (var i = 0; i < elements.length; i++) {

		if((' ' + elements[i].className + ' ').indexOf(' ' + cssClass + ' ') > -1) {
			return elements[i];

		};

	};

	return null;

};

function getNthSpanWithClass(cssClass, intCount) {
	var elements = document.getElementsByTagName('span');
    var itemsfound = 0;
	for (var i = 0; i < elements.length; i++) {
		if((' ' + elements[i].className + ' ').indexOf(' ' + cssClass + ' ') > -1) {
            itemsfound++;
            if(itemsfound == intCount)
    			return elements[i];
		};
	};
	return null;
};

function sleep(milliseconds){

	var sleepstart = new Date().getTime();

	for(var i=0; i<1e7; i++){

		if((new Date().getTime() - sleepstart) > milliseconds){

			break;

		};

	};

};



function RemoveCharactersRemaining(){

	//remove "characters remaining"

	var charsremaining = document.querySelectorAll('[class*="tc-chars"]');

	charsremaining.forEach(function(charremaining){

		charremaining.remove();

	});

}



function ValidateLinesLengthAndUpdateElement(strLine, intLength, intNumLines, hd_element){

	//updates element and returns the corrected string

	var lines = strLine.split(/\r\n|\r|\n/);

	var strReturn = "";

	var tempstr = "";

	for(var i=0; i<lines.length; i++){

		if(i == intNumLines){

			//too many lines, quit formatting

			break;

		}

		tempstr = lines[i];

		if(tempstr.length > intLength)

			tempstr = tempstr.substring(0, intLength);

		strReturn = strReturn + tempstr;

		if(i<lines.length-1)

			strReturn += "\n";

	}

	hd_element.value = strReturn;

	return strReturn;

}



function ValidateMultipleLinesLengthAndNoUpdate(strLine, intLength, intNumLines){

	//just validates string, returns true/false

	var lines = strLine.split(/\r\n|\r|\n/);

	var strReturn = "";

	var tempstr = "";

	for(var i=0; i<lines.length; i++){

		if(i == intNumLines){

			//too many lines, quit formatting

			return false;

		}

		tempstr = lines[i];

		if(tempstr.length > intLength)

			return false

	}

	return true;

}



function ValidateSingleLineLengthNoUpdate(strLine, intLength, intNumLines){

	if(strLine.length > intLength)

		strLine = strLine.substring(0, intLength);

	return strLine;

}



function setSelectionRange(hd_element, selectionStart, selectionEnd) {

    if (hd_element.setSelectionRange) {

        hd_element.focus();

        hd_element.setSelectionRange(selectionStart, selectionEnd);

    }

    else if (hd_element.createTextRange) {

        var range = hd_element.createTextRange();

        range.collapse(true);

        range.moveEnd('character', selectionEnd);

        range.moveStart('character', selectionStart);

        range.select();

    }

}



function setCaretToPos (hd_element, pos) {

       setSelectionRange(hd_element, pos, pos);

}

function FixURLCharacters (strHDURL)
{
    var tempstr = strHDURL;
    tempstr = tempstr.replace(/ /g, "+");
    tempstr = tempstr.replace(/#/g, "%23");
    tempstr = tempstr.replace(/&/g, "%26");

    return tempstr;
}

function ShowAllHDElements(datatype, datavalue)
{
    var elementsearch = document.querySelectorAll('[' + datatype + '*="' + datavalue + '"');
    for(var i=0; i<elementsearch.length; i++)
    {
        elementsearch[i].classList.remove("tc-hidden");
        elementsearch[i].disabled = false;
    }
}

function GetHDVariable (strHDName, index=0, fromsaveddesign = false)

{

    var hd_Variable = document.getElementsByClassName(strHDName);

	if(hd_Variable.length <= index)

		return "";

    if(fromsaveddesign)
    {
        //hd_Variable[index].value = UnFixVariables(hd_Variable[index].value);
    }

	return FixVariables(hd_Variable[index].value);

}

function SetHDDropdown(dropdown, strHDValue)
{
    var trimmedoption = "";
    for(var i = 0;i < dropdown.options.length;i++){
        //trim off the _##
        trimmedoption = dropdown.options[i].value;
        trimmedoption = trimmedoption.substring(0, trimmedoption.lastIndexOf("_"));
        if(trimmedoption == strHDValue ){
            dropdown.options[i].selected = true;
        }
    }
}

function SetHDVariable( strHDName, strHDValue, index = 0)
{
    var hd_Variable = document.getElementsByClassName(strHDName);
    if(hd_Variable.length <= index)
        return;
    //make sure its a textarea
    if(hd_Variable[index].type != "text" && hd_Variable[index].type != "textarea")
        return;

    var formattedstring = strHDValue;
    formattedstring = formattedstring.replaceAll("\\r\\n", "\\n");

    var splitwords = formattedstring.split("\\n");
    formattedstring = "";
    splitwords.forEach(function (item){
            formattedstring += item + "\n"; 
        }
    );
    formattedstring = formattedstring.trim();

    hd_Variable[index].value = formattedstring;
    return;
}



function GetCleanHDVariable (strHDName, index=0)
{
	var hd_Variable = document.getElementsByClassName(strHDName);
	if(hd_Variable.length <= index)
		return "";
    var returnstr = ReturnCleanedHDVariable(hd_Variable[index].value);
	return FixVariables(returnstr);
}

function GetCheckedHDVariable(strHDName, index = 0, checkdisabled = true)
{
	var hd_Variable = document.getElementsByClassName(strHDName);
	if(hd_Variable.length <= index)
		return "";
	for(var i=0; i<hd_Variable.length; i++)
	{
        if(checkdisabled)
        {
            if(hd_Variable[i].checked && !hd_Variable[i].disabled)
			    return ReturnCleanedHDVariable(hd_Variable[i].value);
        }
        else
        {
            if(hd_Variable[i].checked)
			    return ReturnCleanedHDVariable(hd_Variable[i].value);
        }
	}
    return "";
}



function GetXRadioHDVariable(strHDName, index = 0, checkactive = true)

{
	var hd_Variable = document.getElementsByClassName(strHDName);
	if(hd_Variable.length <= index)
		return "";
	for(var i=0; i<hd_Variable.length; i++)
	{
        if(checkactive)
        {
		    if(hd_Variable[i].parentElement.parentElement.classList.contains("tc-active"))
			    return ReturnCleanedHDVariable(hd_Variable[i].value);
        }
        else
        {
            if(hd_Variable[i].checked)
			    return ReturnCleanedHDVariable(hd_Variable[i].value);
        }
	}
    return "";
}



function ReturnCleanedHDVariable(strHDVariable)
{
	if(strHDVariable.length == 0)
		return "";
	if(strHDVariable.includes('_'))
		return strHDVariable.substring(0, strHDVariable.indexOf('_'));
	else
		return strHDVariable;
}

function FixVariables(strHDVariable)
{
	if(strHDVariable.length == 0)
		return "";
    var returnstr = strHDVariable.replaceAll('\\', '\\\\');
    returnstr = returnstr.replaceAll('"', '\\"');
    return returnstr;
}

function UnFixVariables(strHDVariable)
{
	if(strHDVariable.length == 0)
		return "";
    //reverting some special chars because the save this design plugin returns weird code
    var returnstr = strHDVariable.replaceAll('\\\\', '\\');
    returnstr = returnstr.replaceAll('\\"', '"');
    return returnstr;
}

function CleanUnderscore(strHDVariable)
{
	if(strHDVariable.length == 0)
		return "";
    if(!strHDVariable.includes("_"))
        return strHDVariable;
    var returnstr = strHDVariable;
	if(returnstr.length < 3)
		return returnstr
	var secondtolastchar = returnstr.charAt(returnstr.length-2);
	if(secondtolastchar == "_")
		returnstr = returnstr.substring(0, returnstr.length-2); //new way look for the last _
	else
	    returnstr = returnstr.substring(0, returnstr.indexOf("_"));  //old way, returns empty
    return returnstr;
}
function CleanSlashes(strHDVariable)
{
	if(strHDVariable.length == 0)
		return "";
    var returnstr = strHDVariable;
    returnstr = returnstr.replaceAll("\\", "");
    return returnstr;
}
function CleanNewLines(strHDVariable)
{
	if(strHDVariable.length == 0)
		return "";
	var returnstr = strHDVariable;
	returnstr = returnstr.replaceAll("\\n", "");
	return returnstr;
}

function ClickOnElement(hd_ClassName, hd_Value, addcoverclass = true)  //finds all elements with this class name hd_ClassName, clicks it
{
    let hd_ClassNameElements = document.getElementsByClassName(hd_ClassName);
	var returnbool = false;
    for(i=0; i<hd_ClassNameElements.length; i++)
    {
        if(hd_ClassNameElements[i].getAttribute("checked") == "checked")
        {
            hd_ClassNameElements[i].removeAttribute("checked");
        }
        if(hd_ClassNameElements[i].value.includes(hd_Value) && hd_ClassNameElements[i].disabled)
        {
            hd_ClassNameElements[i].setAttribute("checked", "checked");
            //clear all other tc-actives
            let tcactives = hd_ClassNameElements[i].parentElement.parentElement.parentElement.firstElementChild
            while(tcactives)
            {
                tcactives.classList.remove("tc-active");
				if(addcoverclass)
	                tcactives.classList.remove("hd_coverclass");
                tcactives = tcactives.nextElementSibling;
            }
            hd_ClassNameElements[i].parentElement.parentElement.classList.add("tc-active");
			returnbool = true;
			if(addcoverclass)
	            hd_ClassNameElements[i].parentElement.parentElement.classList.add("hd_coverclass");
        }
    }
	return returnbool;
}
function ClickOnSingleElement(hd_ClassName, hd_Value, addcoverclass = false)  //finds all elements with this class name hd_ClassName, clicks it
{
    let hd_ClassNameElements = document.getElementsByClassName(hd_ClassName);
	var returnbool = false;
    for(i=0; i<hd_ClassNameElements.length; i++)
    {
        if(hd_ClassNameElements[i].value.includes(hd_Value))
        {
            hd_ClassNameElements[i].click();
            if(addcoverclass)
            {
                hd_ClassNameElements[i].parentElement.parentElement.classList.add("hd_coverclass");
            }
            return true;
        }
    }
	return returnbool;
}

function SearchUmeta(strSearchKey, strUmeta)
{
	if(strSearchKey.length == 0 || strUmeta.length == 0)
    {
		return "";
    }
	var index = 0, start = 0, end = 0;
	index = strUmeta.indexOf("\"" + strSearchKey + "\":\"");
	if(index < 0)
		return ""; //not found
	start = index + strSearchKey.length + 4;
	end = strUmeta.indexOf("\",\"", start);
	var returnstr = strUmeta.substring(start, end);
	index = strUmeta.indexOf("\"" + strSearchKey + "\":\"", end);
	if(index > -1)
		return ""; //found more than one
	returnstr = UnFixVariables(CleanHTML(returnstr));
    returnstr = returnstr.replaceAll('\\"', '"');
	if(returnstr.includes("\'"))
	{
		ClickOnSingleElement(strSearchKey, returnstr);
	}
	returnstr = CleanUnderscore(returnstr);
    //returnstr = returnstr.replaceAll("<br />", "\n");
    //returnstr = CleanHTML(returnstr);
    //returnstr = CleanSlashes(returnstr);
    SetHDVariable(strSearchKey, returnstr);
    returnstr = returnstr.replaceAll("\"", "\\\"");
	return returnstr;
}

function CleanHTML(strText)
{
	if(strText.length == 0)
		return "";
    var returnstr = strText;
	var newlinechar = "";
    if(strText.includes("<br"))
    {
        var index = 0;
        var start = 0;
        var end = 0;
        index = returnstr.indexOf("<br", index);
        while (index > -1)
        {
            start = index;
            end = returnstr.indexOf(">", start);
			//look for a new line char
			newlinechar = returnstr.substring(end+1, end+ 3);
			if(newlinechar != "\\n")
				returnstr = returnstr.slice(0, start) + "\\n" + returnstr.slice(end+1);
			else
				returnstr = returnstr.slice(0, start) + returnstr.slice(end+1);
            index = returnstr.indexOf("<br", index);
        }
    }
    return returnstr;
}

function ExtractHyperlink(strText)
{ //null if more than one
	if(strText.length == 0)
		return "";
    var returnstr = "";
    var workingtext = strText;
    if(workingtext.includes("http"))
    {
        var index = 0;
        var start = 0;
        var end = 0;
        index = workingtext.indexOf("http");
        start = index;
        end = workingtext.indexOf(" ", start);
        if(end > -1)
            returnstr += workingtext.substring(start, end);
        else
            returnstr += workingtext.substring(start);
        returnstr = returnstr.replaceAll("\\/", "\\");
        index = workingtext.indexOf("http", index+1);
        if(index > -1)
            returnstr = "";
    }
	returnstr = returnstr.replaceAll("HDQUESTIONMARK", "?");
	returnstr = returnstr.replaceAll("HDUNDERSCORE", "_");
    return returnstr;
}

function RemoveHyerlink(strText)
{
	if(strText.length == 0)
		return "";
    var returnstr = strText;
    var index = returnstr.indexOf("http");
	if(index < 0)
		return"";
    var end = returnstr.indexOf(" ", index);
    if(end > -1)
        returnstr = returnstr.slice(0, index) + returnstr.slice(end);
    else
        returnstr = returnstr.slice(0, index);
    return returnstr;
}

function ClickSaveToFavorites()
{
	var customclick = document.querySelectorAll('[id^="homeschool_save_this_design_"]')[0];
	customclick.click();
}

function getUrlParameter(sParam) {
    var sPageURL = window.location.search.substring(1),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
        }
    }
    return false;
}

function IsSchoolNameValid(strSchoolName)
{
	if(schoolnameexclusions.includes(strSchoolName))
		return false;
	else
		return true;
}