﻿// BEGIN CUSTOM CODE *****************************************************

var testing = (window.location.href.indexOf("admintest") > -1); // This is how we debug without having alerts show up for every visitor

//Position elements on CartGenie pages
window.onload = initPage;
window.onresize = handleResize;

function initPage() {
	//fixLogo(); // Logo doesn't show in IE until you resize the container DIV via JS. WTF?? --- FIXED: page needed DOCTYPE declaration. Duh, CartGenie.
	fillInElements();
	browserSpecific();
	expireClasses();
}

function fixLogo() {
	// Not necessary if page has DOCTYPE declaration: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
	var l = document.getElementById('mainlogo');
	l.style.width = "114px";
	l.style.height = "114px";
}

function fillInElements() {
	var content1 = getElementsByClassName(document, "table", "cg_paddedContent1")[0];
	if (content1) {
		var header = getElementPosition("myHeader");
		var footer = getElementPosition("footer");
		var h = (footer.top - header.top - 89); // 89 is height of header
		content1.style.height = h + "px";
	}
	else { // If the collage (contained in cg_paddedContent1) won't be shown display the top nav bar
		var topNavBar = getElementsByClassName(document, "table", "cg_navbarTop")[0];
		if (topNavBar) topNavBar.style.display = "";
	}
}

function handleResize() {}

function browserSpecific() {
	// Internet Explorer sucks: Adjust positions and widths
	if(BrowserDetect.browser == "Explorer" && BrowserDetect.OS == "Windows") {
		
		document.getElementById('mainMenu').style.paddingBottom = "13px";
		document.getElementById('myHeader').style.paddingRight = "13px";
		document.getElementById('footer').style.width = "790px";
		
		var headerPos = getElementPosition("myHeader");
		var footerPos = getElementPosition("footer");
		
		// For pages that contain the left nav bar (product pages, etc.)
		var content1 = getElementsByClassName(document, "table", "cg_paddedContent1")[0]; // there should only be one of these so we'll just use the 1st one
		if (content1) {
			var content1td = content1.getElementsByTagName("td")[0]; // the first td tag underneath
			content1td.style.paddingTop = "160px"; // height of collage + 20px
			content1td.style.paddingLeft = "20px";
			var h = (footerPos.top - headerPos.top - 89); // 89 is height of header
			content1.style.height = h + "px";
			content1.style.width = "640px";
			content1.style.borderRightWidth = "20px";
		}
		
		// For pages that do not contain the left nav bar (account.asp, cart.asp, etc.)
		var content2 = getElementsByClassName(document, "table", "cg_paddedContent2")[0]; // there should only be one of these so we'll just use the 1st one
		if (content2) {
			var content2td = content2.getElementsByTagName("td")[0]; // the first td tag underneath
			content2td.style.paddingTop = "20px";
			content2.style.paddingLeft = "40px"; // this line doesn't appear to work, but I've left it functional anyway; it doesn't give an error
			document.getElementById('myHeader').style.marginLeft = "1px";
			document.getElementById('footer').style.marginLeft = "1px";
			document.getElementById('myTopNavBar').style.marginLeft = "1px";
		}
		
	}
}

function expireClasses() {
	// This function is dependent upon entering (in CartGenie) the item descriptions in the following format:
	// 		Federal Way: 9/13: 6-9p
	//		(Location: Month/Day: Time)
	// and the feature descriptions in the following format:
	// 		Federal Way: Wednesday 9/13: 6-9p
	//		(Location: DayOfWeek Month/Day: Time)
	// and the item number in the following format:
	// 		2006F-0001
	// 		(YearSeason-####)
	// If this is not done, it may fail.
	// There is also a required ASP snippet in pg_CustomCode.asp that writes a meta tag called "timestamp". <meta name="timestamp" content="<%=current%>">
	var metas = document.getElementsByTagName("meta");
	var metaDate = "1/1/2000"; // Default value in case meta tag doesn't exist
	for (var i=0; i<metas.length; i++) {
		if (metas[i].name == "timestamp") metaDate = metas[i].content;
	}
	var metaDateSplit = metaDate.split("/"); // Month, Day, Year
	var _date = new Date();
	var metaDate = _date.setFullYear(metaDateSplit[2],metaDateSplit[0],metaDateSplit[1]);
	var classList = document.getElementById("Select2");
	var submitButton = document.getElementById("Submit2");
	var expiredClasses = new Array();
	var featuresList = document.getElementById("featureHighlights");
	if (featuresList) var listElems = featuresList.getElementsByTagName("li");
	var expiredFeatureListings = new Array();
	var alertString1 = "";
	if (classList) { // There is a drop-down list of classes on the page
		for (var i=0; i<classList.options.length; i++) {
			if (classList.options[i].value != 0) {
				var classText = classList.options[i].innerHTML;
				var c1 = classText.substring(classText.indexOf(":")+1);
				if (c1.charAt(0) == " ") c1 = c1.substring(1);
				if (c1.indexOf("day") > -1) { // Item description includes day of week - that's not supposed to be in there!
					var c1temp = c1.substring(c1.indexOf("day")+3);
					if (c1temp.charAt(0) == " ") c1temp = c1temp.substring(1);
					c1 = c1temp;
				}
				var c2 = c1.substring(0,c1.indexOf(":"));
				var c3 = c2.split("/"); // Month, Day
				var c4 = parseInt(classList.options[i].value.substring(0,4)); // Gets the year of the class from the Item Number (option value)
				if (c4 < parseInt(metaDateSplit[2])) {
					//var c4 = _date.getFullYear();
					if (parseInt(c3[0]) >= parseInt(metaDateSplit[0])) { // Item number year may be off
						//if (testing) alert("Item Number:\t" + classList.options[i].value + "\nClass details:\t" + c1 +"\n"+c3[0]+"-"+metaDateSplit[0]+"="+(parseInt(c3[0]) - parseInt(metaDateSplit[0])) + "\n"+ ((parseInt(c3[0]) - parseInt(metaDateSplit[0])) < 6));
						if ((parseInt(c3[0]) - parseInt(metaDateSplit[0])) < 6) c4 += 1;
					}
					else {
						/* This is the old, lame way of figuring the year
						*/
						if (parseInt(c3[0]) <= 5 && parseInt(metaDateSplit[0]) >= 10) c4 += 1; // If class month is low and today's month is high, most likely the class is in the future (evaluates Sept thru Dec for Jan thru May)
						else if (parseInt(c3[0]) >= 10 && parseInt(metaDateSplit[0]) <= 3) c4 -= 1; // If class month is very high and today's month is very low, most likely the class is in the past (evaluates Jan thru March for Oct thru Dec)
					}
				}
				var classDate = _date.setFullYear(c4,c3[0],c3[1]);
				// The following alert is useful for debugging dates
				if (testing) {
					var testVar1 = ((classDate-metaDate) < 0) ? "It will be REMOVED from the list." : "It will be DISPLAYED in the list.";
					alertString1 += "Item Number:\t" + classList.options[i].value + "\nClass details:\t" + c1 + "\nClass Date:\t" + c4+"/"+c3[0]+"/"+c3[1] + "\nToday's Date:\t" + metaDateSplit[2]+"/"+metaDateSplit[0]+"/"+metaDateSplit[1] + "\n\nThe class is " + Math.round((classDate-metaDate)/1000/60/60/24*10)/10 + " days from now.\n" + testVar1 + "\n------------------------\n";
					
				}
				// The following code expires classes on the day before the class
				// if ((classDate - metaDate) < 86400000) { // Class is less than 24 hours in the future (only uses date - not time)
				// The following code expires classes on the day after the class
				if ((classDate - metaDate) < 0) { // Class date has passed (only uses date - not time)
					expiredClasses.push(i);
				}
			}
		}
		if (testing) alert(alertString1);
	}
	// Hide the expired class items
	if (expiredClasses.length > 0) {
		expiredClasses.reverse(); // IMPORTANT!!
		for (var j=0; j<expiredClasses.length; j++) {
			classList.options[expiredClasses[j]] = null;
		}
		if (classList.options.length < 2) {
			if (classList.options.length == 0) {
				submitButton.value = "Registration Expired";
				submitButton.disabled = true;
				classList.disabled = true;
			}
			else if (classList.options.length == 1 && classList.options[0].value == "0") {
				submitButton.value = "Registration Expired";
				submitButton.disabled = true;
				classList.disabled = true;
			}
		}
	}
	
	var featuresListProcessing = 0; // Set to 1 or 0 to have the class dates filtered or not filtered in the Features list
	
	try {
		var yyyy = _date.getFullYear();
		if (featuresList) { // There is a features list on the page
			for (var i=0; i<listElems.length; i++) {
				var linkTag = listElems[i].getElementsByTagName("a");
				if (linkTag.length == 0) { // Good - no link tag; now let's see if it has some of the formatting we're looking for
					var cond1 = listElems[i].innerHTML.indexOf(":");
					var cond2 = listElems[i].innerHTML.indexOf("/");
					if (cond1 > -1 && cond2 > -1) { // Not the best test, but pretty sure it's a date now.
						var classText = listElems[i].innerHTML.substring(listElems[i].innerHTML.indexOf(":")+1);
						if (classText.indexOf("day") > -1) { // Feature description includes day of week
							var c1 = classText.substring(classText.indexOf("day")+3);
							if (c1.charAt(0) == ":") c1 = c1.substring(1);
							if (c1.charAt(0) == " ") c1 = c1.substring(1);
							var c2 = c1.substring(0,c1.indexOf(":"));
							var c3 = c2.split("/"); // Month, Day
							var c4 = yyyy;
							if (c3[0] <= 4 && metaDateSplit[0] >= 9) c4 += 1; // If class month is low and today's month is high, most likely the class is in the future (starts Sept., goes through April)
							var classDate = _date.setFullYear(c4,c3[0],c3[1]);
							// The following code expires classes on the day before the class
							// if ((classDate - metaDate) < 86400000) { // Class is less than 24 hours in the future (only uses date - not time)
							// The following code expires classes on the day after the class
							if ((classDate - metaDate) < 0) { // Class date has passed (only uses date - not time)
								expiredFeatureListings.push(i);
								// There is either no option to purchase on the page (i.e. not a class details page) or there is only one class option, in which case there is no drop-down list
								var classOption = document.getElementById("ItmSku");
								if (!classList && classOption && classOption.name == "ItmSku") { // There is a class available for purchase, so hide it
									submitButton.value = "Registration Expired";
									submitButton.disabled = true;
								}
							}
						}
						else { // Day of week was not entered in feature description (it should have been!!) or was entered incorrectly (i.e. Mon instead of Monday)
							var c1 = classText;
							if (c1.charAt(0) == " ") c1 = c1.substring(1);
							var c2 = c1.substring(0,c1.indexOf(":"));
							var c3 = c2.split("/"); // Month, Day
							var c4 = yyyy;
							if (c3[0] <= 4 && metaDateSplit[0] >= 9) c4 += 1; // If class month is low and today's month is high, most likely the class is in the future (starts Sept., goes through April)
							var classDate = _date.setFullYear(c4,c3[0],c3[1]);
							// The following code expires classes on the day before the class
							// if ((classDate - metaDate) < 86400000) { // Class is less than 24 hours in the future (only uses date - not time)
							// The following code expires classes on the day after the class
							alert("Class Date: "+classDate+"\nToday's Date: "+metaDate+"\nDifference: "+ classDate - metaDate);
							if ((classDate - metaDate) < 0) { // Class date has passed (only uses date - not time)
								expiredFeatureListings.push(i);
								// There is either no option to purchase on the page (i.e. not a class details page) or there is only one class option, in which case there is no drop-down list
								var classOption = document.getElementById("ItmSku");
								if (!classList && classOption && classOption.name == "ItmSku") { // There is a class available for purchase, so hide it
									submitButton.value = "Registration Expired";
									submitButton.disabled = true;
								}
							}
						}
					}
				}
			}
		}
	}
	catch (e) {  }
	// Hide the expired feature listings (if enabled)
	if (featuresListProcessing == 1 && expiredFeatureListings.length > 0) {
		expiredFeatureListings.reverse(); // IMPORTANT!!
		for (var j=0; j<expiredFeatureListings.length; j++) {
			listElems[expiredFeatureListings[j]].parentNode.removeChild(listElems[expiredFeatureListings[j]]);
		}
	}
}

function viewLocation(loc) {
	var list = document.getElementById('locations_list');
	var loading = document.getElementById('loading_classes');
	list.style.display = "none";
	loading.innerHTML = "<p>&nbsp;</p><p style=\"font-size: large; font-weight: bold;\">Loading class list for " + loc + ".</p><p style=\"font-size: small; font-style: italic;\">This may take a moment...</p>";
	loading.style.display = "";
	
	var frm = document.getElementById('customSearch');
	var searchTxt = frm['SearchFor'];
	searchTxt.value = loc;
	frm.submit();
}

function checkQuery() {
	var q = document.getElementById('SearchFor');
	return checkQuerySpecificity(q);
}

function checkQueryAdv() {
	var q = document.formAdvSearch.SearchFor;
	return checkQuerySpecificity(q);
}

function checkQuerySpecificity(q) {
	var badWords = new Array("sew","sewing","quilt","quilting","machine","embroider","embroidery","and","day","fun","you","class","show","club","decor","basic","supply","learn");
	var isOk = true;
	for (var i=0; i<badWords.length; i++) {
		if (q.value == badWords[i]) isOk = false;
	}
	if (!isOk) {
		msg = "Please be specific with your search words.\n\nGood examples of search words are: 'Trapunto', 'Angelina Fiber', 'beginner quilting' or search for a day of week that the class is on like Thursday or Saturday.\n\nSearches that are too broad like 'quilting' or 'sewing' or 'embroidery' may not work well.\n\nAre you sure you want to continue?";
		if (confirm(msg)) isOk = true;
	}
	return isOk;
}

function switcheroo() {
	if (window.location.href.indexOf(".htm") > -1) {
		var metas = document.getElementsByTagName("meta");
		var IdentifierURL = "";
		for (var i=0; i<metas.length; i++) {
			if (metas[i].name == "Identifier-URL") IdentifierURL = metas[i].content;
		}
		if (IdentifierURL != "") window.location.href = IdentifierURL;
	}
}

function getElementPosition(elemID) {
	var offsetTrail = document.getElementById(elemID);
	var offsetLeft = 0;
	var offsetTop = 0;
	while (offsetTrail) {
		offsetLeft += offsetTrail.offsetLeft;
		offsetTop += offsetTrail.offsetTop;
		offsetTrail = offsetTrail.offsetParent;
	}
	// The following Mac specific code only appears to screw things up
	/*if (whichPlatform() == "Mac" && typeof document.body.leftMargin != "undefined") {
		offsetLeft += document.body.leftMargin;
		offsetTop += document.body.topMargin;
	}*/
	return {left:offsetLeft, top:offsetTop};
}

function getElementsByClassName(oElm, strTagName, oClassNames) {
	var arrElements = (strTagName == "*" && oElm.all) ? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	var arrRegExpClassNames = new Array();
	if (typeof oClassNames == "object") {
		for (var i=0; i<oClassNames.length; i++) {
			arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames[i].replace(/\-/g, "\\-") + "(\\s|$)"));
		}
	}
	else {
		arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames.replace(/\-/g, "\\-") + "(\\s|$)"));
	}
	var oElement;
	var bMatchesAll;
	for (var j=0; j<arrElements.length; j++) {
		oElement = arrElements[j];
		bMatchesAll = true;
		for (var k=0; k<arrRegExpClassNames.length; k++) {
			if (!arrRegExpClassNames[k].test(oElement.className)) {
				bMatchesAll = false;
				break;                      
			}
		}
		if (bMatchesAll) {
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements)
}

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{	// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 	// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

// END CUSTOM CODE *****************************************************