// OPEN A PAGE IN A NEW WINDOW
// Create the new window
function openInNewWindow(e) {
	var event;
	if (!e) event = window.event;
	else event = e;
	// Abort if a modifier key is pressed
	if (event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) {
		return true;
	}
	else {
		var newWindow = window.open(this.getAttribute('href'));
		if (newWindow) {
			// For IE 8
			try {
				if (newWindow.focus()) {
					newWindow.focus();
				}
			}
			catch(err) {
				return false;
			}
		return false;
		}
	return true;
	}
}

// CALL THIS FUNCTION TO INITIATE FUNCTION THAT OPENS CERTAIN LINKS IN NEW WINDOWS
function getNewWindowLinks() {
	// Check that the browser is DOM compliant
	if (document.getElementById && document.createElement && document.appendChild) {
		// Find all links
		var link;
		var links = document.getElementsByTagName('a');
		for (var i = 0; i < links.length; i++) {
			link = links[i];
			// Find all links with a class name of "non-html" - Use for PDF documents and the like
			if (/\bnon\-html\b/.test(link.className)) {
				link.onclick = openInNewWindow;
			}
			// Find all links with a class name of "off-site"
			else if (/\boff\-site\b/.test(link.className)) {
				link.onclick = openInNewWindow;
			}
		}
	}
}

// LOOK FOR TABLES AND CREATE ALTERNATE ROWS
// Requires jQuery
// This auto adjusts alternate rows as new rows are added
function createAlternateRows() {
	$("td:odd").addClass("alt");
}

// LOOK FOR UNORDERED LISTS TO CREATED COLUMNAR LISTS
function createColumnarLists() {
	// Check that the browser is DOM compliant
	if (document.getElementById) {
		// Find all unordered lists
		var ul;
		var ullists = document.getElementsByTagName('ul');
		for (var i = 0; i < ullists.length; i++) {
			ul = ullists[i];
			// Find all lists with a class name of "columnar"
			if (/\bcolumnar\b/.test(ul.className)) {
				var counter = 0;
				// Get all children
				for (var j = 0; j < ul.childNodes.length; j++) {
					var li = ul.childNodes[j];
					// Check to make sure this is an element node rather than a white space (text) node
					if (li.nodeType == '1') {
						// Add classes to list items
						if (counter == 1) {
							li.className = 'column2';
							counter = 0;
						}
						else {
							li.className = 'column1';
							counter ++;
						}
						// Append additional class if no content exists
						if (li.innerHTML == '') {
							li.className = li.className + ' none';
						}
					}
				}
			}
		}
	}
}

// ==============================================================
// PSEUDO-SELECT MENU version 3 - Greg Laycock, Fahlgren
// Emulate SELECT element so that search engines can follow links
// ==============================================================
// Initialize PSEUDO-SELECT elements (use on-load)
function initPseudoSelects() {
	// Check that the browser is DOM compliant
	if (document.getElementsByTagName) {
		var theClass;
		var objDiv;
		var aryDivs = document.getElementsByTagName('div');
		for (var i = 0; i < aryDivs.length; i++) {
			objDiv = aryDivs[i];
			// Find all divs with a class name of "pseudo-select"
			if (/\bpseudo\-select\b/.test(objDiv.className)) {
				theClass = objDiv.className;
				objDiv.className = theClass + '-active';
				objDiv.onclick = emulateSelectElement;
			}
		}
	}
}
// Open and close PSEUDO-SELECT elements
function emulateSelectElement() {
	var on = 'pseudo-select-active on';
	var off = 'pseudo-select-active off';
	switch (this.className) {
		case on:
			this.className = off;
			break;
		case off:
		default:
			this.className = on;
			break;
	}
}

// LOOK FOR CLOAKED LINKS AND MAKE THEM CLICKABLE
// Hopefully this will help hide e-mail addresses from spam spiders
function createMailtoLinks() {
	// Check that the browser is DOM compliant
	if (document.getElementById && document.createElement && document.appendChild) {
		var email; // E-mail address
		var mailto; // The mailto hyperlink
		var cloak; // The mailto span element
		var spans = document.getElementsByTagName('span'); // Array of span elements
		for (var i = 0; i < spans.length; i++) {
			cloak = spans[i];
			// Find all span elements with a class name of "cloak"
			if (/\bcloak\b/.test(cloak.className)) {
				email = cloak.innerHTML;
				cloak.innerHTML = "";
				mailto = document.createElement('a');
				mailto.href = 'mailto:' + email;
				mailto.innerHTML = email;
				cloak.appendChild(mailto);
			}
		}
	}
}

// SET FOCUS ON PAGES WITH USER FORMS
// Requires jQuery
// Look for inputs tags with the class name of "first"
function goToFirstInput() {
	$("input.first").focus();
}

// LIGHTBOX
// Requires jQuery
function initLightbox() {
	$('a.lightbox').lightBox({
		imageBtnClose: 'http://7e221d26b6af51aa16963b01c427affa581c2b03.gripelements.com/img/jquery-lightbox-0_5/close.png'
	});
}

// JAVASCRIPT CHECK
// Requires jQuery
// Show elements that require JavaScript
function scriptCheck() {
	$(".req-js").removeClass('req-js');
}

// GOOGLE ANALYTICS GENERIC EVENT TRACKING v2.2
// Requires jQuery
function initEventTracking() {
	$(".track-event").click(function() {
		// 1. GET DATA FOR GA CATEGORY
		var aryCategories = new Array();//"video","image","lightbox","pdf","ms-word","ms-excel","text","off-site");
		var strCategory = "";
		var intCount = 0;
		// Loop through pre-defined categories (classes)
		for (intCount = 0; intCount <= aryCategories.length; intCount++) {
			if ($(this).hasClass(aryCategories[intCount])) {
				if (intCount > 0) {
					strCategory = strCategory + " ";
				}
				strCategory = strCategory + aryCategories[intCount];
			}
		}
		// No pre-defined categories
		if (strCategory == "") {
			strCategory = $(this).attr("id");
		}
		if (strCategory == "") {
			strCategory = this.nodeName.toLowerCase();
		}
		var gaCategory = strCategory;
		// 2. GET DATA FOR GA ACTION
		var strText;
		// Check to see if text is present
		if ($(this).text() != "") {
			strText = $(this).text();
		}
		// No HTML text
		else {
			// See if this is an image
			if ($(this).find("img").length > 0) {
				strText = $(this).find("img").attr("alt");
				if (strText == "") {
					strText = $(this).find("img").attr("src");
				}
			}
			// See if this is embedded content (typically Flash)
			else if ($(this).find("param[name=movie").length > 0) {
				strText = $(this).find("param[name=movie").attr("value");
			}
			else if ($(this).find("embed").length > 0) {
				strText = $(this).find("object").attr("src");
			}
			// No text
			if (strText == "") {
				strText = "No text";
			}
		}
		var gaAction = strText.replace(/["']{1}/gi,"");
		// 3. GET DATA FOR GA LABEL
		var gaLabel = window.location;
		// 4. TEST FUNCTION OR SEND DATA TO GOOGLE
		if (location.hash == "#test") {
			alert(gaCategory + ", " + gaAction + ", " + gaLabel);
			return false;
		}
		else {
			// INSERT GOOGLE TRACKING CODE HERE
			// Differs based on which version of GA is being used
			// pageTracker._trackEvent(gaCategory, gaAction, gaLabel);
			// _gaq.push(['_trackEvent', gaCategory, gaAction, gaLabel]);
		}
	});
}

// GOOGLE ANALYTICS VIRTUAL PAGE TRACKING v1.1
// Requires jQuery
// This method creates pseudo-pages in the Google Analytics dashboard
function initPageTracking() {
	$("a.track-page").click(function() {
		var strHref = $(this).attr("href");
		var aryHrefSplit = strHref.split("/");
		aryHrefSplit.reverse();
		var strFileName = aryHrefSplit[0];
		var strPath = "/downloads/" + strFileName;
		if (location.hash == "#test") {
			alert(strPath);
		}
		else {
			// INSERT GOOGLE TRACKING CODE HERE
			// Differs based on which version of GA is being used
			// urchinTracker(strPath);
			_gaq.push(['_trackPageview', strPath]);
		}
	});
}

// ADD CLASSES v3.0
// Requires jQuery
function addClasses() {
	// Add classes to different types of links to control behavior
	$("a[href^=http://],a[href^=https://],a[target=_blank]").addClass("off-site");
	$("a[href$=.pdf],a[href$=.jpg],a[href$=.gif],a[href$=.png],a[href$=.sflb],a[href$=doc],a[href$=docx],a[href$=xls],a[href$=xlsx],a[href$=txt],a[href$=avi],a[href$=wma],a[href$=mov]").addClass("non-html");
	$("a[href$=.jpg],a[href$=.gif],a[href$=.png]").addClass("image");
	$("a[href$=avi],a[href$=wma],a[href$=mov]").addClass("video");
	$("a[href$=pdf]").addClass("pdf");
	$("a[href$=doc],a[href$=docx]").addClass("ms-word");
	$("a[href$=xls],a[href$=xlsx]").addClass("ms-excel");
	$("a[href$=txt]").addClass("text");
	// Add event tracking trigger
	$("a.off-site,a.non-html").addClass("track-event");
	// Build selector for current host check
	var currentDomainSelector = "a[href*=" + window.location.host + "], a[href*=members.columbusmuseum.org], a[href*=www.columbusmuseum.org]";
	// Exclude certain links from updated behavior
	$(currentDomainSelector).removeClass("off-site");
	$("a[href*=/support-cma/donate/bellows-legacy-society.php]").addClass("off-site");
	$("a[rel~=lightbox],a[class~=lightbox]").removeClass("non-html");
	$("a[rel~=lightbox],a[class~=lightbox]").removeClass("off-site");
}

// Create a featured-img overlay on img.featured-img
function featured_img(){
	$('p.featured-img').each(function(){
		$(this).wrap('<div class="featured-img-wrap" />');
		var title = $(this).attr('title');
		$(this).after('<p class="featured-img-title">' + title + '</p>');
	});
}

function tabbed(){
	$('h3.tabbed, h4.tabbed').each(function(eq){
		if( $(this).hasClass( $(this).next('div').attr('id') ) ){
			var tabs = $(this).next('div');
			var n = $(tabs).children('.tabbed').length;
			$(tabs).children('.tabbed:not(:first)').hide();

			if( n > 1 ){
				var list = '';
				var i = 0;
				n = ( n <= 6 ? n : 6 );
				for(i=1; i<=n; i++){
					list += '<li>' + i + '</li>';
				}
				$(this).prepend('<ul class="tabbed-nav" id="tabbed-nav-' + eq + '">' + list + '</ul>');
				$('#tabbed-nav-' + eq + ' li:first').addClass('current');
				$('#tabbed-nav-' + eq + ' li').bind('click', function(){
					var index = $(this).index();
					$(this).siblings('.current').removeClass('current');
					$(this).addClass('current');
					$(tabs).children('.tabbed:visible').fadeTo(150, 0, function(){
						$(this).hide();
						$(tabs).children('.tabbed:eq(' + index + ')').fadeTo(150, 1);
					});
				});
			}
		}
	});
}

// Create a placeholder label based on an input.placeholder's "title" attribute
function placeholder(){
	$('input.placeholder').each(function(){
		var id = this.id;
		$(this).wrap('<span class="placeholder-wrap" />');
		$(this).before('<label for="' + id + '" class="placeholder">' + $(this).attr('title') + '</label>');

		if( $('#' + id).val() == ''){
			$('label.placeholder[for=' + id + ']').show();
		}

		$('#' + id).bind('blur', function(){
			if( $('#' + id).val() == ''){
				$('label.placeholder[for=' + id + ']').show();
			}	else {
				$('label.placeholder[for=' + id + ']').hide();
			}
		});

		$('#' + id).bind('focus', function(){
			$('label.placeholder[for=' + id + ']').hide();
		});
	});
}

// ON-LOAD EVENTS
// Requires jQuery
$(function() {
	scriptCheck();
	addClasses();
	// initEventTracking();
	// initPageTracking()
	getNewWindowLinks();
	// createMailtoLinks();
	goToFirstInput();
	createAlternateRows();
	// createColumnarLists();
	// initPseudoSelects();
	initLightbox();
	featured_img();
	tabbed();
	placeholder();
	// $.easy.navigation();
	// $.easy.tooltip();
	// $.easy.popup(); --> Has some issues in IE6, newer versions of Lightbox are better
	// $.easy.external(); --> External links already handled in more usable
	// $.easy.rotate();
	// $.easy.cycle();
	// $.easy.forms();
	// $.easy.showhide();
	// $.easy.jump();
});

