﻿// BEGIN CUSTOM CODE *****************************************************

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;
	}
}

//Position elements on CartGenie pages
window.onload = initPage;
window.onresize = handleResize;

function initPage() {
	//positionElements();
	fillInElements();
	browserSpecific();
	expireClasses();
}

var testing = (window.location.href.indexOf("admintest") > -1); // This is how we debug without having alerts show up for every visitor

function handleResize() {
	//positionElements();
}

function positionElements() {
	var logo = document.getElementById("mainlogo");
	var header = getElementPosition("myHeader");
	logo.style.position = "absolute";
	logo.style.top = (header.top + 5) + "px";
	logo.style.left = (header.left + 14) + "px";
	logo.style.display = "";
	/*
	var purpleSidebar = document.getElementById("cg_purpleSidebar");
	var footer = getElementPosition("footer");
	purpleSidebar.style.position = "absolute";
	purpleSidebar.style.top = (hdr.top + 89) + "px";
	purpleSidebar.style.left = (hdr.left + 771) + "px";
	purpleSidebar.style.height = (footer.top - hdr.top - 89) + "px";
	purpleSidebar.style.display = "";
	*/
}

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 browserSpecific() {
	// Internet Explorer sucks: Adjust positions and widths
	if(BrowserDetect.browser == "Explorer" && BrowserDetect.OS == "Windows") {
		
		document.body.style.marginTop = "14px";
		
		var header = document.getElementById('myHeader');
		header.style.paddingRight = "13px";
		
		var topMenu = document.getElementById('top_menu');
		topMenu.style.paddingBottom = "14px";
		
		var footer = document.getElementById('footer');
		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 = "140px";
			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
			header.style.marginLeft = "1px";
			footer.style.marginLeft = "1px";
			var topNavBar = document.getElementById('myTopNavBar');
			topNavBar.style.marginLeft = "1px";
		}
		
	}
}

function expireClasses() {
	var month_uncertainty = 4;
	// 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();
	// 1/23/2012 8:13:55 PM
	//if (testing) alert(Date.parse("1/23/2012 8:13:55 PM"));
	//var metaDate = _date.setFullYear(metaDateSplit[2]);
	//var metaDate = _date.setMonth(metaDateSplit[0]);
	//var metaDate = _date.setDate(metaDateSplit[1]);
	var metaDate = _date.setFullYear(metaDateSplit[2],metaDateSplit[0],metaDateSplit[1]);
	if (testing) alert(_date);
	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 = "";
	var alertString2 = "";
	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;
				}
				else if (c1.toLowerCase().indexOf("mon:") == 0 || c1.toLowerCase().indexOf("tue:") == 0 || c1.toLowerCase().indexOf("wed:") == 0 || c1.toLowerCase().indexOf("thu:") == 0 || c1.toLowerCase().indexOf("fri:") == 0 || c1.toLowerCase().indexOf("sat:") == 0 || c1.toLowerCase().indexOf("sun:") == 0) { // Item description includes day of week - that's not supposed to be in there!
					var c1temp = c1.substring(4);
					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)
				
				var mo = parseInt(c3[0]);
				var da = parseInt(c3[1]);
				var smo = parseInt(metaDateSplit[0]);
				var sda = parseInt(metaDateSplit[1]);
				c4 += 1; // assume date is in the future, run the following tests to determine if it's not
				if (mo == smo && da <= sda) { // Month and date both match
					c4 -= 1;
					if (da == sda) {
						c4 -= 1; // expire on day of class
					}
				}
				else if ( (mo < smo) && (smo - mo <= month_uncertainty) ) { // Class month is lower than current month && month difference is within the uncertainty range
					c4 -= 1;
				}
				else if (smo <= 5 && mo >= 9 && (smo+12)-mo <= month_uncertainty) { // Dealing with year change && month difference is within the uncertainty range
					c4 -= 1;
				}
				
				var start_time = c1.substring(c1.indexOf(":")+1);
				start_time = start_time.substring(0,start_time.indexOf("-"));
				if (start_time.charAt(0) == " ") start_time = start_time.substring(1);
				if (start_time.charAt(0) == " ") start_time = start_time.substring(1); // seeing some double spaces in there, so including this a 2nd time
				// extremely crude method of figuring time
				var currentTime = new Date();
				var hours = currentTime.getHours();
				var minutes = currentTime.getMinutes();
				var pm = false;
				var c_mins = 0;
				if (start_time.indexOf(":") > -1) c_mins = parseInt(start_time.substring(start_time.indexOf(":")+1,start_time.indexOf(":")+3));
				if (start_time.indexOf("p") >= 0) pm = true;
				else if (start_time.indexOf("a") >= 0) pm = false;
				else if ((parseInt(start_time) >= 1 && parseInt(start_time) < 9) || parseInt(start_time) >= 12) pm = true;
				else if (parseInt(start_time) >= 9 && parseInt(start_time) < 12) pm = false;
				start_time = parseInt(start_time);
				if (pm && start_time < 12) start_time += 12; // now have hour in 24 hour format
				if (testing) alertString2 += start_time+":"+c_mins+" / "+hours+":"+minutes+"\n\n";
				
	//			var classDateTime = new Date(c4,month,date,hour,minute);
				
				//_date.setFullYear(c4);
				//_date.setMonth(mo);
				//_date.setDate(da);	
				_date.setFullYear(c4,mo,da);
				var classDate = _date;
				// 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) { // Too late to register
					expiredClasses.push(i);
				}
			}
		}
		if (testing) alert(alertString2);
		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 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();

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;
}

// END CUSTOM CODE *****************************************************
