$(function(){
	if($("#travel-gallery").length < 1) {		
		linkList();
	}
	else if($("#travel-gallery").length = 1 && jQuery.browser.version <= "418.8" && !$.browser.safari) {
		$("body").addClass("jsEnabled");
	}
	
	initGetConnected("connect");
	tableStyles();
	jsHover("my-links");
	addCustomize("customization");
	styleSwitcher();
	$("a.gallery-link").click(function() {
		openGallery(this.getAttribute('href'));
		return false;
	});
});

/* Used to open a gallery in a new window
 *
 * Accepts the following parameters:
 *  theHref:  the href of the gallery
 */
function openGallery(theHref) {
	window.open(theHref, '_blank', 'width=721px,height=701px,fullscreen=no,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no'); 
}

/*
 * Used to show and hide content
 *
 * Accepts the following parameters:
 *	container:	the id of the containing element
 *	trigger:	the id of the element that triggers the slide when clicked
 *	contentContainer:	content that will be shown/hid
 *	isClosed:	boolean, sets default state to open (0) or closed (1)
 */
function toggleSlide(container, trigger, contentContainer, isClosed, speed) {
	if(container.charAt(0) != "." && container.charAt(0) != "#")
		container = "#" + container;
	$(container + " > div").each(function() {
		var parent = $(this);
		var t = $(this).children(trigger);
		var content = $(this).children(contentContainer);

		if(isClosed) {
			content.hide();		
			parent.addClass("closed");
		}
		if(!speed) speed = "slow";

		t.mouseover(function() {
			$(this).addClass("jsHover");
		});
		t.mouseout(function() {
			$(this).removeClass("jsHover");
		});
		t.click(function() {
			content.slideToggle(speed);
			parent.toggleClass("closed");
			return  false;
		});
	});
}

/*
 * Used to show and hide content
 *
 * Accepts the following parameters:
 *	container:	the id of the containing element
 *	trigger:	the id of the element that triggers the slide when clicked
 *	contentContainer:	content that will be shown/hid
 *	isClosed:	boolean, sets default state to open (0) or closed (1)
 */
function toggleSlideHome(container, trigger, contentContainer, isClosed, speed) {

	if(container.charAt(0) != "." && container.charAt(0) != "#")
		container = "#" + container;
	
	// On some browsers pollmonkey code will execute on each click, causing nasty issues
	// This code will remove the 2 script tags that cause the issue
	// and leave the other tags that are necessary for the poll to function
	var pollCode = $(container).find("script");
	pollCode.eq(0).remove();
	pollCode.eq(pollCode.length-1).remove();

	$(container + " > div").each(function() {
		
		var parent = $(this);
		var t = $(this).children(trigger);
		var content = $(this).children(contentContainer);
		var c = readCookie($(this).attr("id"));

		if (c == "open") {
			content.show();
		} else if (c == "closed") {
			content.hide();
			parent.addClass("closed");
		} else if(isClosed) {
			content.hide();
			parent.addClass("closed");
			createCookie($(this).parent().attr("id"), "closed", 365);
		} else {
			createCookie($(this).parent().attr("id"), "open", 365);
		}
		
		if(!speed) speed = "slow";

		t.mouseover(function() {
			$(this).addClass("jsHover");
		});
		t.mouseout(function() {
			$(this).removeClass("jsHover");
		});
		t.click(function() {

			content.slideToggle(speed);
			parent.toggleClass("closed");

			if(parent.attr("class").indexOf("closed") == -1) {				
				createCookie($(this).parent().attr("id"), "open", 365);
			}
			else {
				createCookie($(this).parent().attr("id"), "closed", 365);
			}

		});
	});
}

/*
 * Used to show and hide content
 *
 * Accepts the following parameters:
 *	container:	the id of the containing element
 *	trigger:	the id of the element that triggers the slide when clicked
 *	contentContainer:	content that will be shown/hid
 *	isClosed:	boolean, sets default state to open (0) or closed (1)
 */
function toggleSlideSingle(container, trigger, contentContainer, isClosed) {
	$("#" + container).each(function() {
		var parent = $(this);
		var t = $(this).children(trigger);
		var content = $(this).children(contentContainer);

		if(isClosed) {
			content.hide();
			parent.addClass("closed");
		}

		t.click(function() {
			content.hide();
			content.slideToggle("slow");
			parent.toggleClass("closed");
			return  false;
		});
	});
}

function initNav(container) {
	$("#" + container).append("<a href='#' id='top-level-trigger'>Hide Navigation</a>");
	$("#top-level-trigger").click(function(){
		if($(this).text() == "Hide Navigation") $(this).text("View Navigation");
		else $(this).text("Hide Navigation");
		
		$(this).siblings().slideToggle("slow");
		$(this).parent().toggleClass("closed");		
		
		return false;
	});
}

function initGetConnected(container) {
	var c = readCookie("connected-drawer");
	
	if (c || $("#featured-stories").length == 1) {
		$("#" + container).css("left", "0px");
	}
	else {
		$("#" + container).css("left", "200px");
	}
	
	var ie6;
	if(jQuery.browser.version == 6.0 && $.browser.msie) {
		ie6 = true;
	}
    
	if($("#" + container).css("left") == "200px") {
		$("#" + container).append("<a href='#' id='connect-trigger'>Open Get Connected</a>");
		$("#" + container).addClass("closed");
		
		if(ie6) {
			$("#" + container + " select").each(function() {
				$(this).hide()
				$(this).parent().prepend("<input id='swap' style='width: 175px;' type='text' />");
			});
		}
	}
	else if($("#" + container).css("left") == "0px") {
		$("#" + container).append("<a href='#' id='connect-trigger'>Hide Get Connected</a>");
		$("#" + container).removeClass("closed");
	}
	
	$("#connect-trigger").click(function(){		
		$("#" + container).toggleClass("closed");
		var cssClass = $("#" + container).attr("class");
		if(cssClass == undefined || cssClass.indexOf("closed") == -1) {	
			createCookie("connected-drawer", 1, 365);
		}
		else {
			eraseCookie("connected-drawer");
		}

		if($("#" + container).css("left") == "0px") {
			$("#" + container).animate({left: 200}, "slow");
			$(this).text("Open Get Connected");
			if(ie6) {
				$("#" + container + " select").each(function() {
					$(this).hide()
					$(this).parent().prepend("<input id='swap' style='width: 175px;' type='text' />");
				});
			}
		}
		else if($("#" + container).css("left") == "200px") {
			$("#" + container).animate({left: 0}, "slow", function(){
				if(ie6) {
					$("#" + container + " select").each(function() {
						$(this).show();
						$("#swap").hide();
					});
				}
			});
			$(this).text("Hide Get Connected");

		}
		return false;
	});
}

function jsHover(container) {
	$("#" + container).hover(
		function(){$(this).addClass("jsHover");},
		function(){$(this).removeClass("jsHover");}
	);
}

function tableStyles() {
	$("#content table").each(function(){
		if(!$(this).attr("class") && !$(this).attr("id")) {
			$(this).wrap("<div class='table-holder'></div>");
			zebraTable($(this));
		}
	});
}
function zebraTable(el) {
	$(el).each(function(){
		$("tr:nth-child(odd)").addClass("odd");
	});
}

function linkList() {
	$("#content li a").each(function() {
		var container = $(this).parent().parent().parent();
		var customPage = false;

		var colClass = container.attr("class") || "";
		var isCorrect = false;

		if(container.attr("id") != "content") {
			if(colClass.indexOf("col") == -1) {
				isCorrect = false;
			}
			else {
				isCorrect = true;
			}
		}
		else {
			isCorrect = true;
		}

		var theUL = $(this).parent().parent();
		//check for custom parents that will never have link list children
		if(theUL.attr("id") == "postcard-thumbs") customPage = true;
		if(theUL.attr("id") == "postcard-nav") customPage = true;
		if(theUL.attr("class") == "additional-links") customPage = true;
		if(container.attr("id") == "article-links") customPage = true;

		//check if the class of the body tags represents a custom page that will never contain a link list
		var bodyClass = $("body").attr("class");
		if(	bodyClass.indexOf("calendar") != -1 || 
			bodyClass.indexOf("directory") != -1 || 
			bodyClass.indexOf("smartrans") != -1) customPage = true;

		//check if anything else is contained in the <li> other than a single <a>
		var multipleItems = true;
		if($(this).parent().text().replace(/\s*$/, '') == $(this).text().replace(/\s*$/, '')) {
			multipleItems = false;
		}
		if($(this).parent().children().length > 1) {
			if($(this).parent().children("ul").length == 1) {
				multipleItems = false;
			}
			else {
				multipleItems = true;
			}
		}

		//if is is a link list, make it appear so
		if(!customPage && !multipleItems && isCorrect) {
			$(this).parent().addClass("link-list");
			$(this).append("&nbsp;<span>&rsaquo;</span>");
		}
	});
}

/*
 * Add text size +/- and color scheme changer html to the page
 */
function addCustomize(container) {
	$("#"+container).empty();
	$("#"+container).append(
		"<div id='change-scheme'><h4>Change Color Scheme</h4><ul><li id='previous-scheme'><a href='#addlink' >Previous color scheme</a></li><li id='next-scheme'><a href='#addlink' >Next color scheme</a></li></ul></div>");
}

/*
 * Controls the gallery on the home page
 */
function homeGallery() {
	$("#featured-stories li").each(function(){
		
		//Get source of black and white thumbnail, append "-color" to get the color version
		var thumbnail = $(this).children("dl").children("dt").children("img");
		var thumbSrc = $(thumbnail).attr("src");		
		if(thumbSrc != null) {
			var newThumbSrc = thumbSrc.replace("bw.jpg", "color.jpg");
		}
		
		$(this).hover(
			function(){
				$(this).addClass("jsHover");
				$(thumbnail).attr("src", newThumbSrc);
			},
			function(){
				$(this).removeClass("jsHover");
				if($(this).attr("class") != "active" && $(this).attr("class") != "jsHover active" && $(this).attr("class") != "active jsHover") {
					$(thumbnail).attr("src", thumbSrc);
				}
			}
		);
				
		// Get image url from link href
		var imageLink = $(this).find(".photo a"); 
		var imageSrc = $(imageLink).attr("href");
		var imageAlt = $(imageLink).text();
		var imageEl = imageLink.parent();

		// Set active item when clicked
		$(this).click(function() {
			// Get link properties
			var textLink = $(this).children().children(".text").children("p").children("a");
			var textSrc = $(textLink).attr("href");
			var textEl = textLink.parent().parent();

			if($(this).attr("id") != "default") {
				$("#default").hide();
			}
			$(this).siblings().each(function(){
				$(this).removeClass("active");
				var thumbnail = $(this).children("dl").children("dt").children("img");
				var thumbSrc = $(thumbnail).attr("src");		
				if(thumbSrc != null) {
					var newThumbSrc = thumbSrc.replace("color.jpg", "bw.jpg");
				}
				$(thumbnail).attr("src", newThumbSrc);
			});
			$(this).addClass("active");

			// Replace link to image with an img tag displaying the image
			imageEl.empty();
			imageEl.append('<a href="' + textSrc + '"><img alt="'+ imageAlt+'" src="'+imageSrc+'"/></a>');

			$(textEl).hover(
				function(){
					$(this).addClass("jsHover");
				},
				function(){
					$(this).removeClass("jsHover");
				}
			);

			// add click handler to the container to avoid IE6 png issues preventing clicking the link
			textEl.click(function() {window.location = textSrc});
			
			$(this).children().children(".photo").each( function() {
				$(this).parent().children(".text").addClass("jsActive");
			});
		});
	});
}

function travelGallery(increment, visibleItems, vertical) {
	//$("#travel-gallery #thumbs ul").wrap("<div id='slide-holder'></div>");
	$("#travel-gallery #thumbs ul").css("overflow", "visible");

	//Add buttons to scroll the gallery
	//$("#travel-gallery #thumbs").prepend("<a href='#next' id='scroll-up'>Scroll Up</a>");
	//$("#container").append("<a href='#next' id='scroll-up-alt'>Scroll Up</a>");
	//$("#travel-gallery #thumbs").append("<a href='#previous' id='scroll-down'>Scroll Down</a>");
	
	//Add Container for Full image and text
	$("#travel-gallery").append("<div id='showcase'></div>");

	//@deprecated TB 05/12/09
	//Wrap the ul in a holder tag
	//var totalImages = $("#travel-gallery #thumbs li").length;
		
	//var galleryItem = $("#travel-gallery #thumbs li:first");
	
	
	//get size of each item and any margin or padding	
	//var totalDimensions;
	//var itemSize = 0;
	//if(vertical) {
	//	itemSize = galleryItem.height();
	//	totalDimensions = new Array("margin-top", "margin-bottom", "padding-top", "padding-bottom");
	//}
	//else {
	//	itemSize = galleryItem.width();
	//	totalDimensions = new Array("margin-left", "margin-right", "padding-left", "padding-right");
	//}
		
	//for (var n = 0; n < totalDimensions.length; n++) {
	//	itemSize += Number(galleryItem.css(totalDimensions[n]).replace("px", ""));
	//}
		
	//var incrementAmount = increment * itemSize;
	//var visibleItemsSize = visibleItems * itemSize;
	//var maxOffset = (totalImages * itemSize) - visibleItemsSize;

	//var target = $("#travel-gallery #thumbs ul");
	//$("#scroll-up, #scroll-up-alt").click(function() {
	//	scroll(target, "up", incrementAmount, maxOffset);
	//	return false;
	//});
	//$("#scroll-down").click(function() {
	//	scroll(target, "down", incrementAmount, maxOffset);
	//	return false;
	//});

	$("#travel-gallery #thumbs li:first").each(function() {
		var link = $(this).children("a").attr("href");
		var thumbSrc = $(this).children("a").children("img").attr("src");
		var thumbAlt = $(this).children("a").children("img").attr("alt");
		var text = $(this).children("a").children("span").text();
		if(thumbSrc != null) var newThumbSrc = thumbSrc.replace("thumb.jpg", "full.jpg");

		$(this).siblings().removeClass("active");
		$(this).addClass("active");
		$("#showcase").empty();
		$("#showcase").prepend('<img alt="' + thumbAlt + '" src="' + newThumbSrc + '" />');
		$("#showcase").append("<p><a href='" + link + "' >" + text + "</a></p>");
	});
	
	$("#travel-gallery #thumbs li").each(function() {
		var link = $(this).children("a").attr("href");
		var thumbSrc = $(this).children("a").children("img").attr("src");
		var thumbAlt = $(this).children("a").children("img").attr("alt");
		var text = $(this).children("a").children("span").text();
		if(thumbSrc != null) {
			var newThumbSrc = thumbSrc.replace("thumb.jpg", "full.jpg");
		}
		
		$(this).click(function() {
			$(this).siblings().removeClass("active");
			$(this).addClass("active");
			$("#showcase").empty();
			$("#showcase").prepend('<img alt="' + thumbAlt + '" src="' + newThumbSrc + '" />');
			$("#showcase").append("<p><a href='" + link + "' >" + text + "</a></p>");
			return false;
		});
	});
	
	$("#showcase p").hover(
		function(){$(this).addClass("jsHover");},
		function(){$(this).removeClass("jsHover");}
	);
}

//@deprecated TB 05/12/09
function scroll(container, direction, amount, maxOffest) {
	var cur = container.css("top");
	
	if(cur == "auto") cur = 0;
	else cur = Number(cur.replace("px", ""));

	switch(direction) {
		case "up":
			cur = cur + amount;
			if(cur > 0) cur = 0;
			
			break;
		case "down":
			cur = cur - amount;
			if(cur < - maxOffest) cur = - maxOffest;
			break;
	}
	
	container.css("top", cur+"px");
}

/*
 * Allows text to be resized through on screen controls
 */
function textResize() {
	var c = readCookie('fontsize');
	if (c) {
		var d = Math.abs(c);
		$("h1, h2, h3, h4, h5, h6, p, a, span, label, input, select, option, li").each(function(){
			var curSize = $(this).css("fontSize");
			if(curSize.indexOf("px") != -1) {
				newSize = Number((curSize.replace("px","")));
				for(i=0; i<d; i++) {
					if(c < 0) newSize -= Math.round(newSize * 0.1);
					else newSize += Math.round(newSize * 0.1);
				}
				newSize = Number(newSize)+"px";
			}
			else if(curSize.indexOf("%") != -1) {
				newSize = Number((curSize.replace("%","")));
				for(i=0; i<d; i++) {				
					if(c < 0) newSize -= Math.round(newSize * 0.05);
					else newSize += Math.round(newSize * 0.05);
				}
				newSize = Number(newSize)+"%";
			}
			$(this).css("fontSize", newSize);
		});
	}
	
	var fontIncrement = c;
	
	$("#increase-type").click(function() {
		
		 fontIncrement++;
		 
		$("h1, h2, h3, h4, h5, h6, p, a, span, label, input, select, option, li").each(function(){
			var curSize = $(this).css("fontSize");
			var newSize;
			
			if(curSize.indexOf("px") != -1) {
				newSize = Number((curSize.replace("px","")));
				newSize += Math.round(newSize * 0.1);
				newSize = Number(newSize)+"px";
			}
			else if(curSize.indexOf("%") != -1) {
				newSize = Number((curSize.replace("%","")));
				newSize += Math.round(newSize * 0.05);
				newSize = Number(newSize)+"%";
			}
			
			$(this).css("fontSize", newSize);
			createCookie('fontsize', fontIncrement, 365);
		});
		return false;
	});
	
	$("#decrease-type").click(function() {
		
		fontIncrement--;

		$("h1, h2, h3, h4, h5, h6, p, a, span, label, input, select, option, li").each(function(){
			var curSize = $(this).css("fontSize");
			var newSize;
			
			if(curSize.indexOf("px") != -1) {
				newSize = Number((curSize.replace("px","")));
				newSize -= Math.round(newSize * 0.1);
				newSize = Number(newSize)+"px";
			}
			else if(curSize.indexOf("%") != -1) {
				newSize = Number((curSize.replace("%","")));
				newSize -= Math.round(newSize * 0.05);
				newSize = Number(newSize)+"%";
			}
			
			$(this).css("fontSize", newSize);
			createCookie('fontsize', fontIncrement, 365);
		});
		return false;
	});
}

/**
* Styleswitch stylesheet switcher built on jQuery
* Under an Attribution, Share Alike License
* By Kelvin Luck ( http://www.kelvinluck.com/ )
**/
function styleSwitcher() {	
	var cssArray = new Array();
	var styleIncrement = 0;
	var i = 0;
	var styleCookie = readCookie('style');

	$('link[@rel*=style][@title]').each(function() {
		cssArray[i] = this.getAttribute('title');
		if (this.getAttribute('title') == styleCookie) {
			styleIncrement = i;
		}
		i++;
	});

	$('#next-scheme').click(function() {
		if(styleIncrement < cssArray.length - 1) {styleIncrement += 1;}
		else {styleIncrement = 0;}
		
		switchStyle(cssArray[styleIncrement])
		return false;
	});

	$('#previous-scheme').click(function() {
		if(styleIncrement > 0) {styleIncrement -= 1;}
		else {styleIncrement = cssArray.length - 1;}
		
		switchStyle(cssArray[styleIncrement])
		return false;
	});
	
	var c = readCookie('style');
	if (c) {switchStyle(c);}
}

function switchStyle(styleName)
{
	$('link[@rel*=style][@title]').each(function(i) {
		this.disabled = true;
		if (this.getAttribute('title') == styleName) this.disabled = false;
	});
	createCookie('style', styleName, 365);
}
/* end style switcher */

/*
 * cookie functions http://www.quirksmode.org/js/cookies.html
 */
function createCookie(name,value,days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function eraseCookie(name)
{
	createCookie(name,"",-1);
}
/* end cookie functions */

/*
 * Adds specified class to an element if it does not already exists
 *	el - element to target
 *	className - class name to add
 */
function addClass(el, className) {
  var curClass = el.className;
  var pattern = new RegExp("(^|\\s)"+className+"(\\s|$)");
  if (!pattern.test(curClass))
  	el.className += " " + className;
}

/*
 * Next 3 functions support MyLinks -
 *  build a dynamic form for submittal,
 *  adds elements dynamically to the form object,
 *  adds the current page title and location to the form and submits it.
 */
   function getNewSubmitForm() {
    var submitForm = document.createElement("FORM");
    document.body.appendChild(submitForm);
    submitForm.method = "POST";
    return submitForm;
  }
  function addElementToForm(submitform, fieldname, fieldvalue) {
    var el = document.createElement("input");
    el.type = "hidden";
    el.name = fieldname;
    el.value = fieldvalue;
    submitform.appendChild(el);
  }
  function AddToMyLinks() {
    var pagetitle = document.title;
    var pageurl = location.href;
    var submitForm = getNewSubmitForm();
    addElementToForm(submitForm, "newpagetitle", pagetitle);
    addElementToForm(submitForm, "newpageurl", pageurl);
    submitForm.action= '/account/AddMyLink.dyn';
    submitForm.submit();    
  }

/*
* Code for reunion countdown.
*/
function reunionAddOnloadEvent(fnc){
 if ( typeof window.addEventListener != "undefined" )
   window.addEventListener( "load", fnc, false );
 else if ( typeof window.attachEvent != "undefined" ) {
   window.attachEvent( "onload", fnc );
 }
 else {
   if ( window.onload != null ) {
     var oldOnload = window.onload;
     window.onload = function ( e ) {
       oldOnload( e );
       window[fnc]();
     };
   }
   else
     window.onload = fnc;
 }
}

function reunionTimeToDays(inTime) {
return (Math.floor(inTime.getTime() / (1000 * 60 * 60 * 24)))
}

function reunionDaysUntil(inDate) {
var now = new Date;
return reunionTimeToDays(inDate) - reunionTimeToDays(now)
}

function reunionCountdown() {   var reunions = new Date ("June 4, 2009");
 if (window.location.href.match(/networks.Classes.TechReunions.index.jsp$/) || window.location.href.match(/networks.Classes.TechReunions.$/)){
   var scr = document.getElementsByTagName('h5');
   scr[0].innerHTML = "<p>Hold on to your brass rats! There are only " + reunionDaysUntil(reunions) + " days left until Tech Reunions 2009!</p>";
 }
}

reunionAddOnloadEvent(reunionCountdown); 