/*============================================*/
/*
Company: The Bravo Group
Client: U-GRO
Programmer: Joe Mallory
Date Created: 9.16.10

TOC:
	- JS ON-LOAD
		- DO SOMETHING
	- SITE GET URL
	- SUCKERFISH DROPDOWN MENUS
	- ADD & PRINT THIS (SOCIAL MEDIA LINKING)
	- SITE MODAL
		- INIT MODAL
		- OPEN/CLOSE CALLBACK METHOD
		- CUSTOM CALLS
	- BANNER ROTATOR
	- BANNER THUMBS
	- SITE HEADLINE BREAKS
	- SITE IMAGE AUTO BORDER
	- SITE PHOTO GALLERY
		- DELCARE VARS
		- INIT PHOTO GALLERY
	- SITE LOCATION SIDEBAR MENU
	- SITE LOCATION TAB BAR
	- SITE LOCATION TAB BAR PHOTO
	- SITE LOCATION LARGE GOOGLE MAPS
	- SITE LOCATION SMALL GOOGLE MAPS
	- SITE LOCATION CORE GOOGLE MAPS
	- SITE LOCATION RELOAD CALENDAR
	- SITE RESOURCE PANELS
	- SITE BLOG
	- SITE FORM EMAIL TO
	- SITE FORM VALIDATIONS
*/	
/*=============================================*/

/*============================================
	JS ON-LOAD
  ============================================*/
$(document).ready(function() {
	//----------------------------------------------------
	// SCRIPTS FOR ALL PAGE LOADS:
	//----------------------------------------------------
		// INIT SUCKERFISH DROP DOWN MENUS FOR MAIN NAVIGATION
		initSuperFish();
		
		// INIT ADDTHIS SOCIAL MEDIA LINKING & PRINT THIS
		initAddThis();
		initPrintThis();
		
		// INIT TABS & PANELS
		initTabs();
		
		// INIT HEADER BREAKS
		//initHeaderBreaks();
		initValidateForms();
		
		// INIT IMAGE AUTO BORDER
		//initImageAutoBorder();
		
		// IF BLOG...Move tags
		moveTags();
		
	//----------------------------------------------------
	// SCRIPTS FOR HOME PAGE LOAD:
	//----------------------------------------------------
		// INIT BANNER ROTATOR
		if ($("body#home").length > -1) {
			initBannerRotatorThumbs();
			initBannerRotator();
			
			// define global variables
			var currentStory;
			var nextStory;
			var newstimer;
			var newsCount;

			initHomeNews();
		}
	//----------------------------------------------------	
	// MODAL: SCRIPT FOR LOCATION FORMS
	//----------------------------------------------------
		initScheduleAVisitModal();
		//intervalSelect();
		// INIT EMAIL "TO:" FORM
		initEmailTo();
		eventPopupsInit();
	//----------------------------------------------------	
	// MODAL: SCRIPT FOR PAGES WITH PHOTO GALLERIES
	//----------------------------------------------------
		initGalleryModal();

	//----------------------------------------------------
	// SCHEDULE VISIT DROPDOWN REPLACE (GENERIC SCHEDULE VISIT PAGE)
	//----------------------------------------------------
	if(window.location.pathname == "/why-u-gro/schedule-a-visit/") scheduleVisitOptionsReplace();
	
});

/*============================================
	SITE GET URL
============================================*/

function getUrlPath()
{
	var url = ((window.location.href.split("//"))[1].split("/")); 
	return url;
}

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

/*============================================
	SUCKERFISH DROPDOWN MENUS
============================================*/

var initSuperFish = function() {
	$('ul.sf-menu').superfish({ 
		delay:       0,                                // one second delay on mouseout 
		animation:   {opacity:'show', height:'show'},  // fade-in and slide-down animation 
		speed:       150,                              // faster animation speed 
		autoArrows:  false,                            // disable generation of arrow mark-up 
		dropShadows: false                             // disable drop shadows 
	});
}

/*============================================
	ADD & PRINT THIS (SOCIAL MEDIA LINKING)
============================================*/
var initAddThis = function(){
	var tempInt = setInterval(function() {
		//if ($(".addthis_toolbox").find("span").length > -1) {
			$(".addthis_toolbox").find("span").each(function(i) {
				$(this).addClass("addThisIcon");
				$(this).text("Share This Page");
			});
			clearInterval(tempInt);
		//}
	}, 50);	
}

var initPrintThis = function(){
	$(".printThisIcon").click(function() {
		print();
		$(this).blur();
		return false;
	});
}

/*============================================
	SITE MODAL
============================================*/

// OPEN/CLOSE CALLBACK METHOD
var createModalWindow = function(_title, _width, _html, _loadCallback, _closeCallback) {
	$.modal("", { 
		position:["0", "50%"],
		onOpen:function(dialog) {
			dialog.overlay.css("opacity", .95);
			dialog.overlay.slideDown('slow', function () {
					$(".simplemodal-data").css({ display: "block", width: _width });
					$(".simplemodal-container").css({ height: "auto", display: "block" });
					$(".simplemodal-data").wrap("<div class=\"borderTL\"><div class=\"borderTR\"><div class=\"borderBR\"><div class=\"borderBL borderWrapper\"></div></div></div></div>").html(_html);
					$(".simplemodal-container .borderWrapper").prepend("<h1>" + _title + "</h1>");
					$(".simplemodal-container").css({
						top: -($(".simplemodal-container").height()+50),
						left: resizeModal(),
						width: $(".simplemodal-data").width()
					}).animate({ 
										top: 40
										},
										500,
										"linear", 
										function() {
											// DO SOMETHING
										}
					);
					_loadCallback();
					resizeModal();
			});
			
		},
		onClose: function (dialog) {
			$(".simplemodal-container").animate({
				top: -($(".simplemodal-container").height()+50)
				},
				500,
				"linear", 
				function() {
					dialog.overlay.slideUp('slow', function() {
						$.modal.close();
						$(".simplemodal-overlay").remove();
						$(".simplemodal-container").remove();
						_closeCallback();
					});
				}
			);
		},
		persist: false
	});	
}

var resizeModal = function() {
	var winX = ($(window).width()/2);
	var modX = ($(".simplemodal-container").width()/2);
	$(".simplemodal-container").css({ 
		top: 20,
		left: (winX - modX)
	});
}

/*============================================
	SITE MODAL: CUSTOM CALLS
============================================*/

// INIT MODAL
//var locationsSelect, closestLocation;
var initScheduleAVisitModal = function() {
	/*var clone = $('#visitForm').hide().clone();
	$(".btnAsideScheduleAVisit").unbind('click').click(
		function(e) {
			createModalWindow("Contact Form", 600, clone.show(), function() { 
				// Do Something
			},function() { 
				//close callback
			});
			setTimeout(intervalSelect, 1000);
			setTimeout(initValidateForms, 1000);
			return false;
		}
	);*/
    $(".btnAsideScheduleAVisit").click(function(){
       window.location="http://daycare.u-gro.com/Schedule-A-Visit/"; 
    });
}

var initGalleryModal = function() 
{ 
	// DO SOMETHING
	if ((getUrlPath())[1].indexOf("locations") > -1 && $(".btnAsidePhotoGallery").length > -1)
	{
		$(".btnAsidePhotoGallery").click(function(e) {
			createModalWindow(
							 	"Photo Gallery", 
							  	590, 
							  	initPhotoGallery(), 
								function() { 
									// DO LOAD CALLBACK
									initIS();
									initISGallery();
								}, 
								function() {
									// DO CLOSE CALLBACK;	
								}
			);
			e.preventDefault();
			return false;
		});

		var active_hash = window.location.hash.substring(1);
		if(active_hash == 'gallery'){
			createModalWindow(
							 	"Photo Gallery", 
							  	590, 
							  	initPhotoGallery(), 
								function() { 
									// DO LOAD CALLBACK
									initIS();
									initISGallery();
								}, 
								function() {
									// DO CLOSE CALLBACK;	
								}
			);
		}

	}
}

/*============================================
	BANNER ROTATOR
============================================*/

var banners                 = [];
var bannerDisplayArea       = "#bannerDisplay";
var bannerDisplayItems      = ".banner";
var bannerZBase             = 100;
var bannerActive            = null;
var bannerActiveNum         = null;
var bannerActiveNext        = null;
var bannerActiveNextNum     = null;

var bannerRotateTimer       = null
var bannerRotateActive      = false;
var bannerRotateAuto        = true;
var bannerRotateStart       = function(){};
var bannerRotateComplete    = function(){};
var bannerRotateInterval    = 8000;
var bannerDelayTimer        = null;
var bannerDelayInterval     = 12000;
var bannerFadeInterval      = 2000;

var initBannerRotator = function() {
	getBanners();
	setBannerZ(); 
	if (bannerRotateAuto == true)
	{
		autoRotateBanner();
	}
	showFirstBanner();
}

var getBanners = function() {
	$(bannerDisplayArea).find(bannerDisplayItems).each(function(i) {
		var myID = $(this).attr("id");
		banners[i] = myID; 
	});
}

var setBannerZ = function() {
	for(var i = 0; i < banners.length; i++) {
		bannerZBase -= 1;
		$("#" + banners[i]).css("zIndex", bannerZBase);
	}
};

var showFirstBanner = function() {
	showNextBanner(0);
}

var autoRotateBanner = function() {
	bannerRotateTimer= setInterval(function() {
		if (bannerActive == banners[(banners.length-1)] || bannerActive === null) {
			showFirstBanner();
		} 
		else
		{
			showNextBanner((bannerActiveNum+1));
		}
	}, bannerRotateInterval);
}

var autoRotateBannerClear = function() {
	clearInterval(bannerRotateTimer);
};

var delayRotateBanner = function() {
	autoRotateBannerClear();
	var myCounter = 0;
	bannerDelayTimer = setInterval(function() {
		if (myCounter == 1) {
			delayRotateBannerClear();
			autoRotateBanner();
			showNextBanner((bannerActiveNum+1));
		}
		myCounter++;
	}, bannerDelayInterval);
}

var delayRotateBannerClear = function() {
	clearInterval(bannerDelayTimer);
}

var showNextBanner = function(_num) {
	if (!bannerRotateActive) {
		disableBannerRoation();
		if (!_num || bannerActive === null || _num > (banners.length-1))
		{
			$("#" + banners[0]).fadeIn(bannerFadeInterval, function() {
				enableBannerRoation();
				bannerRotateComplete();
			});
			bannerActive = banners[0];
			bannerActiveNum = 0;
		}
		else 
		{
			$("#" + bannerActive).fadeOut(bannerFadeInterval);
			$("#" + banners[_num]).fadeIn(bannerFadeInterval, function() {
				enableBannerRoation();
				bannerRotateComplete();
			});
			bannerActive = banners[_num];
			bannerActiveNum = _num;
		}
		bannerRotateStart();
	}

}

var disableBannerRoation = function() {
	bannerRotateActive= true;	
}

var enableBannerRoation = function() {
	bannerRotateActive = false;	
}

/*============================================
	BANNER ROTATOR THUMBS
============================================*/

var thumbs                 = [];
var thumbDisplayArea       = "#thumbContainer";
var thumbDisplayItems      = ".thumb";
var thumbActive            = null;
var thumbActiveNum         = null;
var thumbRotateActive      = false;

var thumbFadeInterval      = 400;
var thumbFadeEasing        = 'linear';
var thumbFadeOpacity       = 1;


var initBannerRotatorThumbs = function() {
	getThumbs();
	
	$(thumbDisplayArea).find(thumbDisplayItems).each(function(i) {
		$(this).mouseover(function() {
			$(this).css("cursor", "pointer");
		});
		$(this).click(function() {
			if (!bannerRotateActive) {
				delayRotateBanner();
				showNextBanner(i);
				$(this).blur();
				return false;
			}
		});
	});
	
	// Hook into the banner rotation start callback
	bannerRotateStart = function() {
		thumbRotateActive = true;
		disableThumb(bannerActiveNum);
	}
	// Hook into the banner rotation complete callback
	bannerRotateComplete = function() {
		// Do Something
	}
}

var getThumbs = function() {
	$(thumbDisplayArea).find(thumbDisplayItems).each(function(i) {
		var myID = $(this).attr("id");
		thumbs[i] = myID;	   
	});
}

var enableThumb = function() {
	for(var i = 0; i < (thumbs.length); i++) {
		$("#" + thumbs[i] + " img").attr("src", "lib/images/buttons/btnOrangeDot.jpg");
		if ($("#" + thumbs[i]).css("opacity") !== thumbFadeOpacity) {
			$("#" + thumbs[i]).animate(
				{ opacity: thumbFadeOpacity },
				thumbFadeInterval, 
				thumbFadeEasing,
				function() {
					// Complete Thumb Fade-Out
					thumbRotateActive = false;
				}
			);							
		}
	}
}

var disableThumb = function(_num) {
	thumbDisabled = thumbActive;
	
	if (thumbActive === null || _num === null) {
		thumbActive = thumbs[0];
		thumbActiveNum = 0;
	} 
	else 
	{
		thumbActive = thumbs[_num];
		thumbActiveNum = _num;
	}
	
	enableThumb();
	$("#" + thumbActive + " img").attr("src", "lib/images/buttons/btnBlueDot.jpg");
	$("#" + thumbActive).animate(
		{ opacity: thumbFadeOpacity },
		thumbFadeInterval, 
		thumbFadeEasing,
		function() {
			// Complete Thumb Fade-In
		}
	);
}

/*============================================
	SITE HEADLINE BREAKS
	------------------------------------------
	Dunamically adds breask before each <h> tag
	...this is to allow for better flowing images
============================================*/

var initHeaderBreaks = function(){
	$("#leftCol").find("h1, h2, h3, h4, h5, h6").each(function(i) {	
		$(this).before("<div class=\"headlineBreak\"></div>");
	});
};
	
/*============================================
	SITE IMAGE AUTO BORDER
	------------------------------------------
	Dunamically wrap all inline images from 
	the cms with a styled border
============================================*/

var initImageAutoBorder = function() {
	$("#leftCol").find("img").each(function(i) {
		if (!$(this).hasClass("noImageBorder")) {
			
			var alignment;
			var attAlignment;
			var imgWidth = $(this).width();
			if ($(this).attr("align") === "right") {
				alignment = " borderAlignLeft";
				attrAlignment = "left";
			}
			else if ($(this).attr("align") === "left") {
				alignment = " borderAlignRight";
				attrAlignment = "right";
			}
			else
			{
				alignment = "";
				attrAlignment = "";
			}
			
			$(this).wrap("<span class=\"borderTL" + alignment + "\" width=\"" + imgWidth + "\" align=\"" + attrAlignment + "\"><span class=\"borderTR\" width=\"" + imgWidth + "\"><span class=\"borderBR\" width=\"" + imgWidth + "\"><span class=\"borderBL borderWrapper\" width=\"" + imgWidth + "\"></span></span></span></span>");
			
			
			// IE6/7 FIX : STRIP THE IMAGE ATTRIBUTE SETTING
			$(this).removeAttr("align");
			
		}
	});
}

/*============================================
	PHOTO GALLERY
============================================*/

var ISTimer;
var ISTimerCount          = 0;
var ISDelayInt            = 2500;
var ISResumeInt           = 8000;
var ISAnimateInt          = 1200;
var ISAnimateType         = "linear";

var IS                    = "imageSlider";
var ISWidth;

var ISContainer           = "imageSliderContainer";
var ISContainerWidth;

var ISSlideDirection      = "Horizontal";
var ISSlideXStart;
var ISSlideXEnd;
var ISSlideStart           = function(){}
var ISSlideComplete        = function(){}

var ISActiveNum            = 1;
var ISActiveDir            = "left";

var ISReset                = false;

// INIT IMAGE SLIDER
var initIS = function() {
	$("#imageSlideLeft").click(function() {
		ISSlideRight();
		$(this).blur();
		$(this).find("a").css("outline", "none");
		return false;
	});
	$("#imageSlideRight").click(function() {
		ISSlideLeft();
		$(this).blur();
		$(this).find("a").css("outline", "none");
		return false;
	});
	
	ISTimer = setInterval(function() {
		var forceWidth = getSlideWidthMax();
		$("#" + ISContainer).width(forceWidth);
		//clearInterval(ISTimer);
	}, ISDelayInt);
	
	var ISSlideLeft = function() {
		ISActiveDir = "left";
		ISSlideX();
	}
	
	var ISSlideRight = function() {
		ISActiveDir = "right";
		ISSlideX();
	}
	
	var ISSlideX = function() {
		
		ISSlideStart();
		$("#" + IS + " #" + ISContainer).animate({
										marginLeft: getSlideX()
										},
										ISAnimateInt,
										ISAnimateType, 
										function() {
											ISSlideComplete();
										}
		);
	}
	
	var getX = function() {
		var myX = Number(($("#" + ISContainer).css("margin-left").split("px"))[0]);
		return myX;
	}
	
	var getSlideX = function() {
		var myX;
		var myNum = ISActiveNum;
		
		if (getSlideXBounds()) {
			var objWidth = $("#" + ISContainer).find(":nth-child(" + ISActiveNum + ")").outerWidth(true);
			
			if (ISActiveDir == "left" && ISActiveNum !== getImageCount()) {
				ISActiveNum+=1;
				myX = getX() - objWidth;
			} else {
				ISActiveNum-=1;
				myX = getX() + objWidth;
			}
			
			return myX;
		} else {
			return getX();	
		}
	}
	
	var getSlideXBounds = function() {
		var currX = getX();
		var leftXBounds = getSlideXMax() - (getSlideXMax()*2);
		var rightXBounds = 0;
		if ((ISActiveDir === "left" && currX !== leftXBounds) || (ISActiveDir === "right" && currX !== rightXBounds)) {
			return true;
		} else {
			return false;	
		}
	}
	
	var getSlideXMax = function() {
		var myCounter = 0;
		var myMaxWidth = 0;
		$("#" + ISContainer).find("img").each(function(i) {
			myCounter++;
			if (myCounter <= (getImageCount()-1)) {
				myMaxWidth += $(this).width();
			}
		});
		return myMaxWidth;	
	}
	
	var getSlideWidthMax = function() {
		var myMaxWidth = 0;
		$("#" + ISContainer).find("img").each(function(i) {
				myMaxWidth += ($(this).width()*2); // Multiply by 2 to get the last thumb to show in the scroller
		});
		return myMaxWidth;	
	}
	
	var getImageCount = function() {
		return $("#" + ISContainer).find("img").length;
	}
	
	var setSliderThumbClasses = function() {
		var thumbCount = 0;
		$("#" + ISContainer).find("li").each(function(i) {
			thumbCount++;
		});
		$("#" + ISContainer).find("li").each(function(i) {
			if (i == 0) {
				$(this).addClass("first");	
			}
			if (i == (thumbCount-1)) {
				$(this).addClass("last");	
			}
		});
	}
	
	setSliderThumbClasses();
}

var ISGallery             = "imageGallery";
var ISGalleryHolder1      = "imageGalleryHolder1";
var ISGalleryHolder2      = "imageGalleryHolder2";
var ISGalleryLoader       = "imageGalleryPreloader";
var ISGalleryMidZ         = 1022;
var ISGalleryBotZ         = 1021;
var ISGalleryMaxZ  	      = 1023;
var ISGalleryActiveHolder = "";
var ISGalleryActiveTitle  = "";
var ISGalleryActiveDesc   = "";
var ISGalleryActiveImage  = "";

var currPath;
var fullSizeImg; 
		
// INIT IMAGE GALLERY
var initISGallery = function() { 

	// Required reset of VARS
	ISGalleryActiveHolder = "";
		ISGalleryActiveTitle  = "";
		ISGalleryActiveDesc   = "";
		ISGalleryActiveImage  = "";
	
	
	$("#" + ISGallery + " #" + ISGalleryHolder1).css("zIndex", ISGalleryMidZ);
	$("#" + ISGallery + " #" + ISGalleryHolder2).css("zIndex", ISGalleryBotZ);
	$("#" + ISGallery).prepend("<div id=\"" + ISGalleryLoader + "\"></div>");
	$("#" + ISGallery + " #" + ISGalleryLoader).css("zIndex", ISGalleryMaxZ);
	$("#" + ISGallery + " #" + ISGalleryLoader).hide();
	
	$("#" + ISContainer).find("img").each(function(i) {
		$(this).click(function(e) {
			parseImageInfo($(this));
			$(this).blur();
			e.preventDefault();
			return false;
		});
	});
	
	var parseImageInfo = function(_obj) {
		fullSizeImg = $(_obj).parent().attr("href");
		fullSizeTitle = $(_obj).attr("title");
		fullSizeDesc = $(_obj).attr("alt");
		if (ISGalleryActiveImage !== fullSizeImg) {
			loadImage(fullSizeImg, fullSizeTitle, fullSizeDesc);
			ISGalleryActiveImage = fullSizeImg;
		}
	}
	
	var createImageOverlay = function(_title, _desc) {
		if ($("#" + ISGallery + " #" + ISGalleryActiveHolder + "#imageGalleryOverlay")) {
			$("#" + ISGallery + " #" + ISGalleryActiveHolder + "#imageGalleryOverlay").remove();
		}
		$("#" + ISGallery + " #" + ISGalleryActiveHolder).prepend("<div id=\"imageGalleryOverlay\"><h4>" + _title + "</h4><p>" + _desc + "</p></div>");
		
	}
	
	var loadImage = function(_img, _title, _desc) {
		if (ISGalleryActiveHolder == ISGalleryHolder1) { 
			$("#" + ISGallery + " #" + ISGalleryHolder1).css("zIndex", ISGalleryBotZ);
			$("#" + ISGallery + " #" + ISGalleryHolder2).css("zIndex", ISGalleryMidZ);
			ISGalleryActiveHolder = ISGalleryHolder2;
		} else { 
			$("#" + ISGallery + " #" + ISGalleryHolder1).css("zIndex", ISGalleryMidZ);
			$("#" + ISGallery + " #" + ISGalleryHolder2).css("zIndex", ISGalleryBotZ);
			ISGalleryActiveHolder = ISGalleryHolder1;
		}
		
		$("#" + ISGallery + " #" + ISGalleryActiveHolder).hide().parent();
		$("#" + ISGallery + " #" + ISGalleryLoader).fadeIn();
		
		//var myImg = (((_img.split("//"))[1].split("/")).slice(3,7)).join("+");
		var myImg = (_img.split("/")).join("%2F");
		var myURL = "http://www.u-gro.com/wp/wp-content/themes/u-gro/photoGalleryImage.php?img=" + myImg;

		$("#" + ISGallery + " #" + ISGalleryActiveHolder).load(myURL, { }, function(response, status, xhr) {
			//alert(xhr.statusText);
			//alert(img);
			//alert(response);
			//alert(status);
			$("#" + ISGallery + " #" + ISGalleryActiveHolder).delay(600).fadeIn(1200);
			$("#" + ISGallery + " #" + ISGalleryLoader).delay(300).fadeOut();
		});
		
		/*
		var newImg = new Image();
		$(newImg).load(_img, function () {
			 $(this).css("display", "none");
			  $("#" + ISGallery + " #" + ISGalleryActiveHolder).delay(400).html("<img src=\"" + _img + "\" border=\"0\" />");
			  $("#" + ISGallery + " #" + ISGalleryActiveHolder).delay(600).fadeIn(1200);
			  $("#" + ISGallery + " #" + ISGalleryLoader).delay(300).fadeOut();
			  
			  ISGalleryActiveImage = fullSizeImg;
		});
		*/
	}
	
	$("#" + ISContainer).find(":nth-child(1) img").each(function(i) {
		if (i == 0) {
			parseImageInfo($(this));
		}
	});
}


var photoGallery; // Array Contains Second Array of Thumb and Large Images [thumb, large]
var initPhotoGallery = function() {
	var myItems;
	for (var i=0; i < photoGallery.length; i++) {
		if (i == 0) {
			myItems	= "<li><a href='" + photoGallery[i][1] + "'><img src='" + photoGallery[i][0] + "' class=\"noImageBorder\" border=\"0\" alt=\" \" /></a></li>";
		} else {
			myItems	+= "<li><a href='" + photoGallery[i][1] + "'><img src='" + photoGallery[i][0] + "' class=\"noImageBorder\" border=\"0\" alt=\" \" /></a></li>";
		}
	}
	return photoGalleryHTML = "<div id=\"imageSliderWrapper\">" +
								"<div id=\"imageSlideLeft\"><a href=\"#\">Left</a></div>" +
								"<div id=\"imageSlideRight\"><a href=\"#\">Right</a></div>" + 
								"<div id=\"imageSlider\">" +
									"<ul id=\"imageSliderContainer\">" + 
										myItems +
									"</ul>" + 
								  "</div>" + 
							"</div>" +
							"<div id=\"imageGalleryWrapper\">" +
								"<div id=\"imageGallery\">" +
									"<div id=\"imageGalleryHolder1\"></div>" +
									"<div id=\"imageGalleryHolder2\"></div>" +
								"</div>" + 
							"</div>";
}

/*============================================
	SITE LOCATION SIDEBAR MENU
============================================*/

var sidebarMenuLocations = function() {
	$(".subnav a").click(function() {
		if ($(this).parent().parent().hasClass("children") == false && $(this).next().hasClass("children")) {
			if (!$(this).hasClass("selected")) {
				$(this).next().show();
				$(this).addClass("selected");
			} else {
				$(this).next().hide();
				$(this).removeClass("selected");
			}
			$(this).blur();
			return false;
		}
	});
}

/*============================================
	SITE LOCATION TAB BAR
============================================*/

var tabBar             = [];
var tabBarTabs         = [];
var tabBarPanels       = [];
var tabBarDefaultIndex = 0;
var tabBarInitialized  = function(){};
var tabBarClicked      = function(){};

var initTabs = function() {
	$("#leftCol").find(".tabBar").each(function(i) {
		tabBar[i] = $(this).attr("id");
		indexTabBarTabs(tabBar[i]);
		indexTabBarPanels(tabBar[i]);
		initTabBarTabPanelBinding(tabBar[i]);
		// INIT ACTIVATION FOR ALL TAB/PANELS AT INDEX 0
		changeTabBarTabs(tabBar[i], tabBarDefaultIndex);
		changeTabBarPanels(tabBar[i], tabBarDefaultIndex);
		// INIT CALLBACK FOR TABBAR INITIALIZATION
		tabBarInitialized(tabBar[i], tabBarDefaultIndex);
	});
}


var indexTabBarTabs = function(_tabBar) {
	$("#" + _tabBar).find("li").each(function(i) {
		if ($(this).parent().attr("id") === _tabBar) {
			if (!$(this).attr("id")) {
				$(this).attr("id", (_tabBar + "_tab_" + i));
			}
		}
	});
}

var indexTabBarPanels = function(_tabBar) {
	// Used So Nested Tab Panels Are Not Counted
	var myCount = 0;
	
	$("#" + _tabBar).next().find("div.panel").each(function(i) {
		if ((($(this).parent().prev().attr("id").split("_"))[0]).indexOf(_tabBar) > -1) {
			$(this).attr("id", (_tabBar + "_panel_" + myCount));
			myCount++;
		}
	});
}

var initTabBarTabPanelBinding = function(_tabBar) {
	$("#" + _tabBar).find("li").each(function(i) {
		$(this).click(function() {
			var assocIndex = ($(this).attr("id").split("_"))[2];
			changeTabBarTabs(_tabBar, assocIndex);
			changeTabBarPanels(_tabBar, assocIndex);
			tabBarClicked(_tabBar, assocIndex);
			$(this).blur();
			$(this).find("a").blur();
			return false;
		});
	});
}

var changeTabBarTabs = function(_tabBar, _index) {
	$("#" + _tabBar).find("li.tab").each(function(i) {
		if ($(this).parent().attr("id") === _tabBar) {
			if (i == _index) {
				$(this).addClass("tabActive");	
			}
			else
			{
				$(this).removeClass("tabActive");	
			}
		}
	});
}

var changeTabBarPanels = function(_tabBar, _index) {
	// Used So Nested Tab Panels Are Not Counted
	var myCount = 0;
	
	if ($("#" + _tabBar).next().attr("class", "tabPanel")) {
		$("#" + _tabBar).next().find("div.panel").each(function(i) {
			if ($(this).parent().prev().attr("id") === _tabBar && (($(this).attr("id").split("_"))[0]).indexOf(_tabBar) > -1) {
				if (myCount == _index) {
					$(this).addClass("panelActive");	
				}
				else
				{
					$(this).removeClass("panelActive");	
				}
				myCount++;
			}
		});
	}
}

/*============================================
	SITE LOCATION TAB BAR PHOTO
============================================*/

tabBarInitialized = function(_tabBar, _index) {
	indexTabBarImages(_tabBar, _index);
}

tabBarClicked = function(_tabBar, _index) {
	if (_tabBar === "locationTabBar") {
		$("#locationTabImages .panelActive").removeClass("panelActive");
		$("#locationTabImages").find("li").each(function(i) {
			if (i == _index) {
				$(this).addClass("panelActive");
			}
		});
	}
}

var indexTabBarImages = function(_tabBar, _index) {
	if (!$("#locationTabImages").find("li:first-child").attr("id")) {
		$("#locationTabImages").find("li").each(function(i) {
			if (i == _index) {
				$(this).addClass("panelActive");	
			}
			$(this).attr("id", _tabBar + "_image_" + i);
		});
	}
}

/*============================================
	SITE LOCATION LARGE GOOGLE MAPS
============================================*/

function initLargeGoogleMaps() {
	var myOptions = {
		zoom: 9,
		center: new google.maps.LatLng(40.2517195,-76.8191126),
		mapTypeId: google.maps.MapTypeId.ROADMAP
	}
	var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
	setMarkers(map, markers, true);
}

/*============================================
	SITE LOCATION RELOAD CALENDAR
============================================*/

var reloadLunchCalendar = function(_y, _m) {
	var myURL = "/wp/wp-content/themes/u-gro/lunchCalendar.php?y=" + _y + "&m=" + _m;
	//var myURL = "/wp/wp-content/themes/u-gro/testimonials.inc";
	$("#lunchCalendar").load(myURL, {}, function(response, status, xhr) {
  		//alert(xhr.statusText);
		//alert(response);
	});
}


/*============================================
	SITE LOCATION RELOAD EVENTS
============================================*/

var reloadEventCalendar = function(_y, _m, _l) {
	var myURL = "/wp/wp-content/themes/u-gro/eventCalendar.php?y=" + _y + "&m=" + _m + "&l=" + _l;
	$("#eventCalendar").load(myURL, {}, function(response, status, xhr) {
		eventPopupsInit();
	});
}


/*============================================
	SITE LOCATION SMALL GOOGLE MAPS
============================================*/

function initSmallGoogleMaps() {
	var myOptions = {
		zoom: 7,
		center: new google.maps.LatLng(markers[0]["lat"], markers[0]["lon"]),
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		navigationControl: false,
		disableDefaultUI: true
	  }
  	var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
	setMarkers(map, markers, false);
}

/*============================================
	SITE LOCATION CORE GOOGLE MAPS
============================================*/

/**
 * Data for the markers consisting of a name, a LatLng and a zIndex for
 * the order in which these markers should display on top of each
 * other.
 */
var infowindow = null;
var markers = {};

function setMarkers(_map, _locations, _infoWindowBool) {
	var count = 0;
	for (var _loc in _locations) {
		var myLatLng = new google.maps.LatLng(_locations[_loc]["lat"], _locations[_loc]["lon"]);
		var marker = new google.maps.Marker({
			position: myLatLng,
			map: _map,
			clickable: true,
			cursor: "pointer",
			title: _locations[_loc]["title"],
			zIndex: count
		});
		if (_infoWindowBool) {
			attachInfoWindow(_map, marker, _locations[_loc]["img"], _locations[_loc]["name"], _locations[_loc]["address"], [_locations[_loc]["lon"],_locations[_loc]["lat"]], _locations[_loc]["permalink"]);
		} else {
			attachQuickLink(_locations[_loc]["address"]);	
		}
		count++;
	}
}

function closeInfoWindows() {
	$("#map_canvas").find(".gmnoprint").each(function($i) {
		$(this).remove();													   
	});	
}

function attachInfoWindow(_map,_marker, _img, _name, _address, _coords, _permalink) {
	
	google.maps.event.addListener(_marker, 'click', function() {
		closeInfoWindows(); // Close any existing open info windows.
		var address = _address.split(",");
		address = address[0] + ", " + address[1] + ", " + address[2];
		infowindow = new google.maps.InfoWindow({
			content: "<div id=\"infoWindow\" style=\"overflow: hidden; width: 440px; height: 130px;\"><div id=\"bodyContent\"><div id=\"img\" style=\"width: 200px; float: left; display: inline; margin-right: 20px;\"><img src=\"" + _img + "\" style=\"margin: 0;\" border=\"0\" alt=\" \" /></div><div id=\"content\" style=\"width: 190px; float: left; display: inline;\"><h3>" + _name + "</h3><p>" + address + "<br /><a href=" + _permalink + ">Learn More</a></p><form style=\"float: left; display: inline; width: 100%; margin-top: -4px; \"><input type=\"text\" value=\"Enter Your Address\"/></form><br /><a href=\"http://maps.google.com/maps?saddr=" + _address + "\ target=\"_blank\" class=\"directions\" style=\"float: left; display: block; width: 100%; margin-top: 4px; \">Get Directions</a></div></div></div>"
		});
		infowindow.open(_map,_marker);
		
		var tempIntCount = 0;
		var tempInt = setInterval(function() {
			if (tempIntCount > 0) {
				$("#map_canvas #content").find("input").each(function(i) {
					var defaultVal = "Enter Your Address";
					$(this).val(defaultVal);
					$(this).mouseover(function() {
						if ($(this).val() == defaultVal) {
							$(this).val(" ");					
						}
					}).mouseout(function() {
						if ($(this).val() === " ") {
							$(this).val(defaultVal);
						}
					});
				});
				$("#map_canvas #content").find("a.directions").each(function() {
					$(this).mouseover(function() {
						if($("#map_canvas #content").find("input").val() === "" || $("#map_canvas #content").find("input").val() === "Enter Your Address") {
							$(this).attr("href", "#");
						} else {
							$(this).attr("href", "http://maps.google.com/maps?saddr=" + $("#map_canvas #content").find("input").val() + "&daddr=" + _address);
						}
					});
				});
				clearInterval(tempInt);
			}
			tempIntCount++;
		}, 500);
	});
}

function attachQuickLink(_address) {
		var tempIntCount = 0;
		var tempInt = setInterval(function() {
			if (tempIntCount > 0) {
				$("#map_canvas").find("map").each(function() {
					$(this).click(function() {
						$(this).blur();
						window.location.href = String("http://maps.google.com/maps?daddr=" + _address);
					});
				});
				$(".btnAsideGetDirections").click(function() {
					$(this).blur();
					window.location.href = String("http://maps.google.com/maps?daddr=" + _address);								   
				});
				clearInterval(tempInt);
			}
			tempIntCount++;
		}, 200);

}

/*============================================
	SITE RESOURCE PANELS
============================================*/

var initResourcePanels = function() { 
	if ($(".longPanelTabWrapper").length > -1) 
	{
		// Do Something
		$(".longPanelTabWrapper").find("a").each(function(i) {
			$(this).click(function() {
				// Hide/show tabs
				$(this).parent().parent().find(".active").removeClass("active");
				$(this).parent().addClass("active");
				$(this).blur();
				$(this).css({"outline": "none"});
				
				// Hide/show panels
				var myPanel      = $(this).attr("href");
				$(this).parent().parent().next().find("dl.active").removeClass("active");
				$(myPanel).addClass("active");
				
				// Return false
				return false;
			});
		});
		
		$(document).find("dt").each(function(i) {
			$(this).click(function() {
				$(this).find("span").each(function() {
					if ($(this).html().indexOf("+") > -1) 
					{
						$(this).html("[-]");	
					} 
					else 
					{
						$(this).html("[+]");
					}
				});
				$(this).next().toggle("slow");
				$(this).blur();
				$(this).css({"outline": "none"});
				return false;
			});
		});
	}
}


/*============================================
	SITE BLOG
============================================*/

var moveTags = function() {
	if ($(".post-tag")) {
		var postTag = $(".post-tag");
		$(".post-tag").remove()
		$(".post-info").after(postTag);
		$(".post-tag").css({ "margin-bottom" : "4px" });
	}
}

/*============================================
	SITE FORMS EMAIL TO
============================================*/

var emailAddress;
var initEmailTo = function() {
	if (emailAddress) {
		$('<input />')
			.attr('type','hidden')
			.attr('id','recipient')
			.attr('name','recipient')
			.val(emailAddress)
			.appendTo(".wpcf7-form");
	}
}
/*============================================
	SITE VALIDATE FORMS
============================================*/

var initValidateForms = function() {
	//set class for submit button
	$('input[type="submit"]').addClass('submit');
	//give all input's an id
	$('input,textarea').attr('id', function() {	return this.name;	});
	$(':text,textarea').attr('title', function() {
		return $('label[for="'+this.name+'"]:last').text();
	});
	//remove border from images
	$('#leftCol form img').addClass('noImageBorder').css('float','right');
	$('#errormsg').hide();

	//inline labels
	//initLabelsOnFocus();
	initLabelsOnClick();

	$('.wpcf7-form').validate({
		rules : {
			fname: "required",
			lname: "required",
			address1: "required",
			city: "required",
			state: "required",
			zip: "required",
			email: {
				required: true,
				email: true
			},
			location: "required",
			phone: "required",
			contactmethod: "required",
			contacttime: "required",
			age: "required",
			comments: "required",
			"optin[]": "required"
		},
		messages : {
			fname: "Your first name is required",
			lname: "Your last name is required",
			address1: "A valid address is required",
			city: "Your city is required",
			state: "Your state is required",
			zip: "Your zip code is required",
			email: "A valid email address is required",
			location: "Please select your closest location",
			phone: "A valid phone number is required",
			contactmethod: "Please choose how we should contact you",
			contacttime: "Please choose when you would like to be contacted",
			age: "Your children's ages are required",
			comments: "You forgot to include a message",
			"optin[]": "In order to receive future communications, you must check the box."
		},
		errorLabelContainer: "#errormsg",
		highlight : function(element, errorClass) {
			$(element).filter(':text,textarea').addClass('formElementError');
		},
		unhighlight: function(element, errorClass) {
			$(element).removeClass('formElementError');
		},
		wrapper: "div",
		invalidHandler : function(form, validator) {
			$('#errormsg').slideDown('slow');
			$(':text,textarea').blur();
		}
	});
}

var initLabelsOnClick = function() {
	$(":text,textarea").each(function (i) {
		$('label[for="'+$(this).attr('name')+'"]:last').hide();
		var labelText = $('label[for="'+$(this).attr('name')+'"]:last').hide().text();
		if ($(this).val() == "") {
			$(this).attr('value',labelText);
		}
		$(this).addClass('focus');
    });
    $(":text,textarea").focus(function() {
        if($('label[for="'+this.id+'"]:last').text() == this.value){
            this.value = "";
			$(this).addClass("focus");
        }
    });
    $(":text,textarea").keydown(function() {
        $(this).removeClass("focus").addClass("typing");
     });
    $(":text,textarea").blur(function() {
        $(this).removeClass("focus").removeClass("typing");
        if(this.value == ""){
			$(this).attr('value',$('label[for="'+$(this).attr('name')+'"]:last').text());
        }
    });
	$('form').submit(function() {
		$(':text,textarea').each(function() {
			if (this.value == $('label[for="'+this.id+'"]:last').text())
				this.value = '';
		});
	});

}

var initLabelsOnFocus = function() {
	$.fn.setCursorPosition = function(pos) {
        if ($(this).get(0).setSelectionRange) {
            $(this).get(0).setSelectionRange(pos, pos);
        } else if ($(this).get(0).createTextRange) {
        var range = $(this).get(0).createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
        }
    }
    $(":text,textarea").each(function (i) {
        $(this).attr('value',$('label[for="'+$(this).attr('name')+'"]:last').hide().text()).addClass('focus');
    });
    $(":text,textarea").focus(function() {
        if($('label[for="'+this.id+'"]:last').text() == this.value){
            $(this).addClass("focus").setCursorPosition(0);
        }
    });
    $(":text,textarea").keydown(function() {
        if($('label[for="'+this.id+'"]:last').text() == this.value){
            this.value = "";
            $(this).removeClass("focus").addClass("typing");
        }
    });
    $(":text,textarea").blur(function() {
        $(this).removeClass("focus").removeClass("typing");
        if(this.value == ""){
			$(this).attr('value',$('label[for="'+$(this).attr('name')+'"]:last').text());
        }
    });
	$('form').submit(function() {
		$(':text,textarea').each(function() {
			if (this.value == $('label[for="'+this.id+'"]:last').text())
				this.value = '';
		});
	});
}

var unpopulated = true;
var intervalSelect = function() {
	if(unpopulated) {
		var o = $('#locationsPop').children();
		
		$('select[name="location"]').children().remove();
		$('select[name="location"]').append('<option value="">--------</option>');

		$('select[name="location"]').append(o);
		$('select[name="location"] option').eq(0).attr('selected','selected');	

		/*var o = locationsSelect;
		$('select[name="location"]').each(function() {
			for(var i = 0; i < o.length; ++i) {
				$(document.createElement('option')).attr('value',o[i]['value']).text(o[i]['text']).appendTo($(this));
			}
		});*/
		unpopulated = false;
	}
	if (typeof closestLocation != 'undefined')
		$('select[name="location"] option[value$="'+closestLocation+'"]').attr('selected','selected');
}

function scheduleVisitOptionsReplace() {
	var o = $('#locationsPop').children();
		
	$('select[name="location"]').children().remove();
	$('select[name="location"]').append('<option value="">--------</option>');

	$('select[name="location"]').append(o);
	$('select[name="location"] option').eq(0).attr('selected','selected');
}

/*============================================
	HOME PAGE NEWS ROTATOR
============================================*/
var initHomeNews = function(){
	$("#newsStories").css('position','relative').css('height','150px');
	$("#newsStories .article").css('position','absolute').css('top','0px').css('left','0px').hide();
	$("#newsStories .article").eq(0).addClass('active').show();

	newsCount = $("#newsStories .article").length;
	var current = $("#newsStories .active").index();

	if(current != (newsCount - 1)){
		var next = current + 1;
		startNewsTimer(current, next);
	}
}
function startNewsTimer(current, next)
{
	newstimer = setInterval(function(){
		makeNewsFade(current, next);
		current = currentStory;
		next = nextStory;
	}, 8000);
}
function makeNewsFade(current, next)
	{
		// do the fade
		$("#newsStories .article").eq(current).removeClass('active').fadeOut('slow');
		$("#newsStories .article").eq(next).addClass('active').fadeIn('slow');
		
		// increment or reset the count
		current = next;
		if(next != newsCount -1) next++;
		else next = 0;
		
		// update the count holders
		currentStory = current;
		nextStory = next;
	}

/*=============================================
	CALENDAR POPUPS
==============================================*/
function eventPopupsInit(){
	$("span.hasdetails").click(function(){
		$(this).parent().children(".eventDetails").show();
	});
	$("span.closeDetails").click(function(){
		$(this).parent().hide();
	});
}

