cMaxSize = 225;
cMinSize = 180;

cMinTitleSize = 180;
cMaxTitleSize = 225;
doResize = 0;
cGutterSize = 5;

cMinCols = 4;
cMaxCols = 15;

cMinCategory = 3;
cMaxCategory = 7;
cAffinityCategory = 1;

cTargetSize = 188;

numCols = cMinCols;

var timeoutLazyLoad;
var doResize = 0;
var timeOut = 0;
var timeOutIncrement = 100;

var curSize = cTargetSize;

var toLayout;

var vidIndex = 0;

var commentsActive = 0;
var slidesNum = 6;
var slidesPage = 1;
var maxSlidesPage = 1;
var sliderPageWidth = 0;
var activeSlide = 1;

var clickAction = "";

var loadDelay = 500;

var strPreloadImage = "";
var strPreloadImage2 = "";

var toPi1, toPi2;

var innerNav1, innerNav2, innerNav3;

var flowLoaded = 0;

(function($){

	var Shelby = {
		ondomready: function(){

			//$(document).pngFix();
			Shelby.init();
			
			if (doResize == 1)
			{
				//Shelby.setCategoryLength();
				Shelby.insertVideo(0, 1);
				$(window).resize(function() {
					clearTimeout(toLayout);
					toLayout = setTimeout("Shelby.resetVideos();", 50);
					$("#videoPlayer").hide();
				});
			}
			
			if (doResize == 2)
			{
				// sub page
				Shelby.buildSecondaryGrid(Shelby.getFixedColumns(188), 0);
			}
			
			if (doResize == 3)
			{
				// sub page with double height left nav
				Shelby.buildSecondaryGrid(Shelby.getFixedColumns(188), 1);
			}
			
			Shelby.initialLayout();
			
			Shelby.linkLogo();
			
			Shelby.buildHome(numCols);

			Shelby.buildHovers();
			Shelby.buildLightbox();
			
			Shelby.buildFiltering();	
			Shelby.buildMotion();

			Shelby.buildArchive();
			
			Shelby.handleSort();
			
			Shelby.buildSetDetail();
			
					
			Shelby.buildClientForm();
			
			Shelby.positionPreloader();
			
			Shelby.buildBiography();
			
			Shelby.handleiDevices();
			
			Shelby.fixTags();
		},
		
		fixTags: function() {
			if ($(".tags").length <= 0) {
				$("#setsTitle").hide();
			}
		},
		
		handleiDevices: function() {
			if ((navigator.userAgent.indexOf('iPhone') != -1) || (navigator.userAgent.indexOf('iPod') != -1) || (navigator.userAgent.indexOf('iPad') != -1)) {
				$(".footer").hide();
			}
		},
		
		buildBiography: function() {
			var bindex = 0;
			$(".page_bio .imageBox").each(function() {
				if (bindex > 0)
				{
				
					var percent = 25;
					var num = Math.random()*100;
					
					if (num<= percent) {
						if (num < (percent/2) || 1==1)
						{
							$(this).toggleClass("bioWhite", true);
						} else {
							$(this).toggleClass("bioBlack", true);
						}
					}
				}
				bindex++;
			});
		},
		
		positionPreloader: function() {
			wid = $(window).width();
			hei = $(window).height();
			
			$(".preloaderHolder").css({left: (wid/2-8)+"px", top: (hei/2-8)+"px"});
		},
		
		buildClientForm: function() {
			$(".clientForm .submit").click(function(event) {
				event.preventDefault();
				$("#clientForm").submit();
			});
		},
		
		buildMotion: function() {
			$(".page_category .categoryTitle ul li a").click(function(event) {
				event.preventDefault();
				
			});
			$(".page_motion .categoryBox:not(.categoryTitle)").click(function() {
						
						
				if ($("#theVideo").length>0 || $("#flowPlayer").length>0)
				{
				
				
					strVid = $(this).find(".videoFile").html();

					if (isMobile) {
						video = $("#theVideo").get(0);
						video.volume = 1;
						video.pause();
						video.src = $(this).find(".videoFile").html();
						video.load();
						video.addEventListener("canplaythrough", Shelby.autoPlay, false);
						
						video.addEventListener("ended", Shelby.handleVideoEnd, false);
					
					
					} else {
						$("#flowPlayer").show();
						$f("flowPlayer", "/js/flowplayer.commercial-3.2.7.swf", {
							clip: {
								url: strVid,
								autoPlay: true,
								autoBuffering: true,
								scaling: "orig"
							},
							canvas: {
								backgroundGradient: 'none',
								bckgroundColor: '#000000'
							},
							plugins: {
								controls: {
									url: "/js/flowplayer.controls-3.2.5.swf",
									
									time: false,
									volume: false,
									
									backgroundGradient: 'none'
								}
							},
							key: '$2ad92a22191ce0c9326'
							
						});
					}
					
					
					$("#videoPlayer .vcontent").html($(this).find(".text_more").html());
					$("#videoPlayer h3").html($(this).find("h3").html());
					$("#videoPlayer").css({position: "fixed", left: 200+"px", top: 77+"px", width: "700px", height: "640px"});
					//$("#videoPlayer").css({position: "fixed", left: 200+"px", top: 192+"px", width: 890+"px", height: 667+"px"});
					$("#videoPlayer").fadeIn("slow", function() {
						$(".category").fadeTo(0.5, 0.3);
					});
					
					
					return false;
				} else {	
					return false;
				}	
			});

			$("#videoPlayer .close").click(function() {
			
				if (isMobile) {
					var video = $("#theVideo").get(0);
					video.pause();
					video.volume = 0;
				} else {
					$f().stop();
					$("#flowPlayer").fadeOut("fast");
				}
				$("#videoPlayer").fadeOut("slow", function() {
					$(".category").fadeTo(0.5, 1);				
				});		
				$(".category .box, .category .videoBox").each(function() {
					$(this).css("opacity", 1);
				});					
				return false;
			});
			
			/*$(".page_motion #videoPlayer .close").click();*/
			
			$(".page_motion .categoryTitle a").click(function(event) {
				event.preventDefault();
				eventid = $(this).next(".id").html();
				
				$(".categoryBox .meta .entryid:contains("+eventid+")").parent().parent().click();
			});
		
		},
		
		buildFiltering: function() {
		
			$(".page_category .categoryTitle ul li a, .page_motion .categoryTitle ul li a").click(function(event) {
				event.preventDefault();
				
				if ($(this).hasClass("active"))
				{
					// disable
					$(this).toggleClass("active", false);
					$(".categoryBox").not(".categoryTitle").show();
				} else {
					// enable
					$(this).toggleClass("active", true);
					$(".categoryBox").not(".categoryTitle").hide();
					$(".categoryBox .set:contains("+$(this).html()+")").parent().show();
				}
				return false;
			});
		},
		
		buildInnerNav: function(s1, s2, s3) {
			str = "<a href='/home/index.php' class='backicon'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a>";
			
			str+= "<a href='/portfolio/' class='homeback'>/ " + s1 + " /</a>";
			
			if (s2 != "") {
				if (s3 != "") {
					str += "<a href='#' class='innerback'> " + s2 + " /</a>";
				} else {
					str += " " + s2;
				}
			}
			
			if (s3 != "") {
				str += " " + s3;
			}
						
			$(".identity .back").html(str);
			
			/*
			$(".backicon").unbind("click");
			$(".backicon").click(function(event) {
				event.preventDefault();
				commentsActive = 0;
				$(".popupHolder").fadeOut("fast");
				$(".primary_navigation").fadeIn("fast");
				$(".identity").toggleClass("activeSub", false);
				$(".identity .back").fadeOut("fast");
				$(".popupHolder").html("");
				$(".category").show();
				$(".previous a, .next a").click(function() { return false; });
				$(".previous a, .next a").unbind("click");
				
			});			
			*/
			
			$(".innerback").unbind("click");
			$(".innerback").click(function() {
				commentsActive = 0;
				$(".slideshowDetail").fadeOut("fast");		
				$(".slideshowHolder .toolbox, .slideshowHolder .photo").fadeIn("fast");
				innerNav3 = "";
				Shelby.buildInnerNav(innerNav1, innerNav2, innerNav3);
				return false;
			});
			
			
		},
		
		buildSetDetail: function() {
			$(".page_category .categoryBox:not(.categoryTitle) a").click(function(event) {
				event.preventDefault();
				
				innerNav1 = "Photography";
				innerNav2 = $(this).parent().children("h3").html();
				innerNav3 = "";
				
				
				Shelby.buildInnerNav(innerNav1, innerNav2, innerNav3);
				
				
				
				//$(".preloaderHolder").fadeIn("fast");
				$(".category").fadeOut("slow");
				$(".primary_navigation").fadeOut("slow");
				
				$(".identity").toggleClass("activeSub", true);

				$(".popupHolder").hide();


				$(".popupHolder").load($(this).attr("href"), function() {
					
					Shelby.buildSetActions(1);
					$(this).delay(loadDelay).fadeIn("slow", function() {
						Shelby.buildSetActions(2);
						$(".preloaderHolder").fadeOut("fast");
						$(".category").hide();
					});
					$(".identity .back").delay(loadDelay).fadeIn("fast");
				});
				return false;
			});
			
			$(".page_home .section .box").not(".videoBox .box").click(function(event) {
				event.preventDefault();
				//$(".preloaderHolder").fadeIn("fast");
				
				innerNav1 = "Photography";
				innerNav2 = $(this).parent().children(".boxTitle").children("h3").html();
				innerNav3 = "";
				Shelby.buildInnerNav(innerNav1, innerNav2, innerNav3);

				$(".category").fadeOut("slow");
				$(".popupHolder").hide();
				$(".popupHolder").load($(this).find("a").attr("href"), function() {
					$(".identity").toggleClass("activeSub", true);
					Shelby.buildSetActions(1);
					$(this).delay(loadDelay).fadeIn("slow", function() {
						Shelby.buildSetActions(2);
						$(".preloaderHolder").fadeOut("fast");
						$(".category").hide();
					});
					$(".primary_navigation").delay(loadDelay).fadeOut("fast");
					$(".identity .back").delay(loadDelay).fadeIn("fast");
				});
				return false;
			});
			

			
		},
		
		preloadImage: function(strImage) {
			$(".photo img.preload1").attr("src", strImage);
		},
		
		preloadImage2: function(strImage) {
			$(".photo img.preload2").attr("src", strImage);
		},
		
		buildSetActions: function(step) {
			var winHeight = $(window).height()-150;
			var winWidth = $(window).width();
			
			var areaWidth = $(".slideshowHolder").width() - $(".info").width() - 20;

			if (step==1)
			{
				$(".slideshowHolder .slides").hide();
				$(".slideshowHolder .slidesLeft").hide();
				$(".slideshowHolder .slidesRight").hide();
				
			} else {
			
				//$(".slideshowHolder .slides").css({left: (photoHeight/2-130)+"px"});
				$(".slideshowHolder .slides").css({left: (areaWidth/2-150)+"px"}).show();
				$(".slideshowHolder .slidesLeft").css({left: (areaWidth/2-170)+"px"}).show();
				$(".slideshowHolder .slidesRight").css({left: (areaWidth/2+180)+"px"}).show();
			
			}
			
			$(".slideshowHolder").css("height", winHeight+"px");
			var photoHeight = winHeight - 90;
			$(".slideshowHolder .photo img.loading").css({top: (photoHeight/2-7)+"px", left: ((photoHeight/2)-7)+"px"});
			$(".slideshowHolder .photo img").not(".loading").css({height: photoHeight+"px", width: photoHeight+"px"});
			$(".slideshowHolder .photo").css({width: (photoHeight+95)+"px", height: (photoHeight)+"px"});
			$(".previous, .next").css({top: (photoHeight/2-50)+"px"});
			
			
			
			$("#comments-form .submit").html("Submit Comment");
			$("#comments-form .submit").unbind("click");
			$("#comments-form .submit").click(function(event) {
				$("#comments-form .submit").html("Submitting...");
				event.preventDefault();
				$(this).parent().submit();
				
				$.post($(this).parent().parent().attr("action"), $(this).parent().parent().serialize(), function(data) {
					$("#comments-form .submit").html("Thank you for your comment");
					$("#comments-form .submit").unbind("click");
				});
			});
			
			$(document).mousemove(function(e) {
			
				if (innerNav3 == "") {
				
					var width = $(window).width();
					var height = $(window).height();
					
					if (e.pageY < height*7/8)
					{
						if (e.pageX < (width*3/8))
						{
							$(".previous a").fadeIn("slow");
							$(".next a").fadeOut("slow");
							clickAction = "prev";
							$(".photo .main").toggleClass("activeMainPhoto", true);
							
						} else if (e.pageX > (width*5/8))
						{
							$(".next a").fadeIn("slow");
							$(".previous a").fadeOut("slow");
							clickAction = "next";
							$(".photo .main").toggleClass("activeMainPhoto", true);
						} else {
							$(".next a").fadeOut("slow");
							$(".previous a").fadeOut("slow");
							clickAction = "";
							$(".photo .main").toggleClass("activeMainPhoto", false);
						
						}
					} else {
							$(".previous a").fadeOut("slow");
							$(".next a").fadeOut("slow");
							$(".photo .main").toggleClass("activeMainPhoto", false);
							clickAction = "";
					
					}
					
				} else {
							$(".previous a").fadeOut("slow");
							$(".next a").fadeOut("slow");
							$(".photo .main").toggleClass("activeMainPhoto", false);
							clickAction = "";
				}
			});
			$(".photo .main").unbind("click");
			$(".photo .main").click(function(e) {
				e.preventDefault();
			
				switch(clickAction) {
					case "next":
						$(".slideBoxActive").next().click();
						break;
					case "prev":
						$(".slideBoxActive").prev().click();
						break;
					default:
					
						break;
				}
			});
			
			
			$(".slideBox").unbind("click");
			$(".slideBox").click(function() {
			/*
				$(".photo img.new").attr("src", $(this).find(".templarge").html());
				$(".photo img.main").fadeOut("fast", function() {
					$(".photo img.main").attr("src", $(".photo img.new").attr("src")).show();
				});
			*/
				$(".photo img.main").hide();
				clearTimeout(toPi1);
				clearTimeout(toPi2);
			
				$(".photo img.main").unbind("load");

				$(".photo img.main").load(function() {
					$(".photo img.main").delay(500).show();
					toPi1 = setTimeout("Shelby.preloadImage('"+strPreloadImage+"');", 0);
					toPi2 = setTimeout("Shelby.preloadImage2('"+strPreloadImage2+"');", 500);
				});
				
				
				$(".photo img.main").attr("src", $(this).find(".templarge").html());

				$(".slideshowDetail .photo img").attr("src", $(this).find(".templarge").html());
				$(".slideshowDetail .aboutphoto .about").html($(this).find(".meta .more").html());
				
				$(".comments a").html("Comments ("+$(this).find(".meta .count").html() + ")");
				$(".commentlist").html($(this).find(".meta .comment").html());
				
				$("#entry_id").attr("value", $(this).find(".meta .commentid").html());
				
				$("#comments-form").fadeIn("fast");
				$("#comments-form-thankyou").fadeOut("fast");			
				
				$(".slideBox").toggleClass("slideBoxActive", false);
				$(this).toggleClass("slideBoxActive", true);
				
				if (commentsActive == 0)
					$(".toolbox .full").click();
				
				Shelby.checkSliderPos();

				strPreloadImage = $(this).next().find(".templarge").html();
				strPreloadImage2 = $(this).prev().find(".templarge").html();
			
				/*
				setTimeout("Shelby.preloadImage('"+strPreloadImage+"');", 700);
				setTimeout("Shelby.preloadImage2('"+strPreloadImage2+"');", 700);
				*/
				return false;
			});
			
			/*
			$(".submit .button a").click(function() {

				$.post($(this).parent().parent().attr("action"), $(this).parent().parent().serialize(), function(data) {
					
					if (data.indexOf("Thank you for commenting") != -1)
					{
						// success
						$("#comments-form").fadeOut("fast");
						$("#comments-form-thankyou").fadeIn("fast");
						
					} else {
						alert("Please properly complete the form.");
					}
				});			

				return false;
			});
			*/
			
			if (step==2)
			{
			
				$(document).unbind('keydown');
				$(document).keydown(function(e) {
					if (e.keyCode == 37) {
						// left
						$(".slideBoxActive").prev().click();
						return false;
					}
					
					if (e.keyCode == 39) {
						$(".slideBoxActive").next().click();
						return false;
					}
				});
					
				$(".previous a").unbind("click");					
				$(".previous a").click(function() {
					$(".slideBoxActive").prev().click();
				});
				
				$(".next a").unbind("click");					
				$(".next a ").click(function() {
					$(".slideBoxActive").next().click();
				});
				
				$(".comments a").click(function() {
					commentsActive = 1;
					$(".slideshowDetail").fadeIn("fast");		
					$(".slideshowHolder .toolbox, .slideshowHolder .photo").fadeOut("fast");
					
				innerNav3 = "Comments";
				Shelby.buildInnerNav(innerNav1, innerNav2, innerNav3);
				
					return false;
				});
				
				$(".backPhoto").click(function() {
					commentsActive = 0;
					$(".slideshowDetail").fadeOut("fast");		
					$(".slideshowHolder .toolbox, .slideshowHolder .photo").fadeIn("fast");
					
					
					return false;
				});
				
				$(".toolbox .full").click(function(event) {
					event.preventDefault();
					$(".slides").toggleClass("slidesMany", false);
					$(".slides").height(50);
					$(".slideshowHolder").toggleClass("gridSlide", false);
					$(".slideshowHolder").toggleClass("fullSlide", true);
					$(".slideshowHolder .photo").fadeIn("fast");
					$(".slideshowHolder .next").fadeIn("fast");
					$(".slideshowHolder .previous").fadeIn("fast");
					
				});
				
				$(".toolbox .grid").click(function(event) {
					event.preventDefault();
					
					if ($(".slides .slideBox").size() > 36) {
						extra = 300;
						boxSize = $(window).height() - extra;
						$(".slides").height(boxSize);					
						$(".slides").toggleClass("slidesMany", true);
					}

					
					$(".slideshowHolder").toggleClass("fullSlide", false);
					$(".slideshowHolder").toggleClass("gridSlide", true);
					$(".slideshowHolder .photo").fadeOut("fast");
					$(".slideshowHolder .next").fadeOut("fast");
					$(".slideshowHolder .previous").fadeOut("fast");
				});
				
				$(".info .add").click(function(event) {
					event.preventDefault();
					Shelby.favoriteEntry($(".slideBoxActive img").attr("src"));
				});
				
	/*
				$(".info .mail").click(function(event) {
					event.preventDefault();
					document.location("mailto:?subject=Shelby Gallery: Entry "+$(".slideBoxActive .meta .entryid").html());
				});
	*/			

				/*
				extra = 300;
				boxSize = $(window).height() - extra;
				$(".slides").height(boxSize);
				
				if ($(".slides .slideBox").size() > 36) {
					$(".slides").toggleClass("slidesMany", true);
				}
	*/
				numSlides = $(".slides .slideBox").length;
				
				sliderPageWidth = $(".slides").width();
				slidesPage = 1;

				activeSlide = $(".slideBoxActive").index();
				
				maxSlidesPage = Math.ceil(numSlides / slidesNum);
				$(".slidesSlider").css("left", "0px");
				
				$(".slidesLeft a").click(function(event) {
					if (slidesPage > 1)
					{
						slidesPage--;
						Shelby.checkSlider();
						$(".slidesSlider").animate({left: "+="+sliderPageWidth+"px"}, 300);
					}
				});

				$(".slidesRight a").click(function(event) {
					if (slidesPage < maxSlidesPage)
					{
						slidesPage++;
						Shelby.checkSlider();
						$(".slidesSlider").animate({left: "-="+sliderPageWidth+"px"}, 300);
					}
				});

			
				Shelby.checkSlider();
				Shelby.checkSliderPos();
				
				if (step==2)
				$(".slideBoxActive").click();
			} else {
				if (step==2)
				$(".slideBoxActive").click();
			}
		},
		
		checkSlider: function() {
			if (slidesPage <= 1) {
				slidesPage = 1;
				$(".slidesLeft").fadeOut("fast");
			} else {
				$(".slidesLeft").fadeIn("fast");
			
			}
			
			if (slidesPage >= maxSlidesPage) {
				slidesPage = maxSlidesPage;
				$(".slidesRight").fadeOut("fast");
			} else {
				$(".slidesRight").fadeIn("fast");
			}

			
		},
		
		checkSliderPos: function() {
			activeSlide = $(".slideBoxActive").index();
		
			if (activeSlide < ((slidesPage-1)*slidesNum))
			{
				// need to go left
				$(".slidesLeft a").click();
				setTimeout("Shelby.checkSliderPos();", 500)
			}
			
			if (activeSlide >= (slidesPage*slidesNum))
			{
				$(".slidesRight a").click();
				setTimeout("Shelby.checkSliderPos();", 500)
			}			
		},

		init: function() {

		},
		
		linkLogo: function() {
			$(".primary_navigation h1").click(function() {
				location.href = "/home/index.php";
			});
		},
		
		resetVideos: function() {
			$(".category .section .videoBox").remove();
			vidIndex=0;
			Shelby.insertVideo(0, 1);
			
		},
		
		favoriteEntry: function(entryid) {
			days = 5;
			
			var name="favorites";
			
			var date = new Date();
			
			date.setTime(date.getTime() + (days*24*60*60*1000));
			var expire = ";expires="+date.toGMTString();
			
			var curFavorites = Shelby.getFavorites();
	
			if (curFavorites != "")
			{
				if (curFavorites.indexOf(entryid) > -1)
				{
					// already there
					return;
				} else {
					if (curFavorites == "" || curFavorites == "")
					{
							document.cookie = name+"="+entryid+expire;
					} else {
							document.cookie = name+"="+curFavorites+","+entryid+expire;
					}
					
				}
			} else {
				// nothing there
				document.cookie = name+"="+entryid+expire;
			}
			
		
			//Shelby.addFavoriteDiv(entryid, $(".slideBoxActive .meta .name").html(), $(".slideBoxActive img").attr("src"));
			Shelby.addFavoriteDiv($(".slideBoxActive img").attr("src"), "", $(".slideBoxActive img").attr("src"));
			
			Shelby.buildLightboxClose();
			Shelby.updateFavoriteCount();
		},
		
		resetFavorites: function() {
			$(".lightboxPhoto").each(function() {
				$(this).find(".close a").click();
			});
		},
		
		updateFavoriteCount: function() {
			var cur = Shelby.getFavorites();
			
			var arCur = cur.split(",");
			
			var len = arCur.length;
			
			if (cur != "")
			{
				$(".navigation .pnav_lightbox span").html("("+len+")");
				$(".lightbox .tab div span").html("("+len+" Images)");
			} else {
				$(".navigation .pnav_lightbox span").html("");
				$(".lightbox .tab div span").html("");
			}
		},
		
		favoriteRemove: function(entryid) {
			days = 5;
			
			var name="favorites";
			
			var date = new Date();
			var eraseDate = new Date();
			
			date.setTime(date.getTime() + (days*24*60*60*1000));
			eraseDate.setTime(date.getTime() + (-1*24*60*60*1000));
			
			var expire = ";expires="+date.toGMTString();
			var eraseExpire = ";expires="+eraseDate.toGMTString();
			
			var curFavorites = Shelby.getFavorites();
			
			if (curFavorites != "")
			{
				if (curFavorites.indexOf(entryid) > -1)
				{
					// already there, lets remove
					curFavorites = curFavorites.replace(entryid, "");
					curFavorites = curFavorites.replace(",,", ",");
					if (curFavorites[curFavorites.length-1] == ",") {
						curFavorites = curFavorites.substring(0, curFavorites.length-1);
					}
					if (curFavorites[0] == ",") {
						curFavorites = curFavorites.substring(1, curFavorites.length);
					}
					
					if (curFavorites == "," || curFavorites == "") {
						document.cookie = name+"="+eraseExpire;
					} else {
						document.cookie = name+"="+curFavorites+expire;
					}
					Shelby.updateFavoriteCount();
				} else {
					return;
				}
			} else {
				// nothing there, we can't remove
				return;
			}			
			
			
		},
		
		
		
		addFavoriteDiv: function(entryid, entryname, entryphoto) {
			html = $(".lightboxBlank").html();
			if ($(".lightboxHolder .lightboxPhoto").length > 0) {
				$(".lightboxHolder .lightboxPhoto").last().after(html);
			} else {
				$(".lightboxHolder .lightboxInstructions").before(html);
			}
			
			
			ins = $(".lightboxHolder .lightboxPhoto").last();
			
			ins.find(".entryid").html(entryid);
			ins.find(".thumb").attr("src", entryphoto);
			ins.find(".caption").html(entryname);
			
							

			
		},
		
		
		
		getFavorites: function() {
			var name = "favorites";
			
			var cName = name + "=";
			
			var arCookies = document.cookie.split(";");
			
			for (var i=0; i<arCookies.length;i++)
			{
				var cur = arCookies[i];
				while (cur.charAt(0) == ' ') cur = cur.substring(1, cur.length);
				
				if (cur.indexOf(name) == 0) return cur.substring(name.length+1, cur.length);
			}
			
			return "";
		},
		
		insertVideo: function(absLocation, init) {
			var nCol = Shelby.getColumns();

			var videoWidth = 3;
			
			var found = 0;
			var foundObj;
			
			var curLocation = 0;
			var curAbsLocation = 0;
			
			var validChildren = $(".category .section").children(".box, .videoBox");
			
			validChildren.each(function() {
				//alert(curAbsLocation + " - " + absLocation + " - " + curLocation + " = " + nCol + " >> " + $(this).attr("class"));
				if (
					curAbsLocation > absLocation && 
					curAbsLocation > 0 && 
					curLocation < (nCol - 3) && 
					$(this).hasClass("boxTitle") && 
					!$(this).prev().hasClass("videoBox")
				)
				{
					found = 1;
					foundObj = $(this);
					return false;
				}
				
				if ($(this).hasClass("videoBox"))
				{
					curLocation+=3;
					curAbsLocation+=3;
				} else {
					curLocation++;
					curAbsLocation++;
				}
				if (curLocation >= nCol ) curLocation = 0;
				
			});
			
			if (found)
			{
				if (vids = $(".videoHolderSlot .videoBox:eq("+vidIndex+")"))
				{
					foundObj.parent().prev().append(vids.attr('outerHTML'));
					//vids.remove();
					vidIndex++;
			
					Shelby.insertVideo(curAbsLocation+3, init);
				} else {
					Shelby.fixLayout(init);
				}
			} else {
				Shelby.fixLayout(init);
				
			}
			
			
		
		},
		
		setCategoryLength: function() {
			$(".category .section").each(function() {
				var children = $(this).children(".box, .videoBox").not(".boxTitle");
				var nCount = children.length;
				
				
				
				if (nCount > cMinCategory) {
					// we modify the length
					
					// hide em all
					children.toggleClass("boxinactive", true);
					
					numExtra = nCount - cMinCategory;
					nRand = Math.min(nCount, cMinCategory + Math.floor(Math.random()*(cMaxCategory-cMinCategory)));
					
					for (var i=0;i<nRand;i++)
					{
						pick = Math.floor(Math.random()*nRand);
						alert(pick);
						
						obj = children.children(":eq("+pick+")");
						if (obj.hasClass("boxinactive"))
						{
							obj.toggleClass("boxinactive", false);
						} else {
							i--;
						}
					}
					
				}
			});
		},
		
		doCascade: function(numLeft, row, obj) {
			var nDelay = (numCols - numLeft + row)*timeOutIncrement+200;
			if (obj.length > 0 && obj.attr("class").indexOf("videoBox") != -1)
			{
				numLeft-= 3;
				obj.children(".box").delay(nDelay).animate({opacity: 1});
			} else {
				numLeft--;
			}
			
			obj.delay(nDelay).animate({opacity: 1}, function() {
				$(this).show();
			});
			
			if (numLeft > 0)
			{
				if (obj.next().length > 0)
				{
					Shelby.doCascade(numLeft, row, obj.next());
				} else {
					
					obj = obj.parent().next().children(":first-child");
					Shelby.doCascade(numLeft, row, obj);
				}
			}
		},
		
		buildSecondaryGrid: function(numAcross, adjust) {
			numCols = numAcross;
		
			
			var index = 0;
			var rawIndex = 1;
			var rowIndex = 0;
			
			$(".categoryBox").css("opacity", 0);
			$(".categoryBox").each(function() {
				rawIndex++;

				$(this).delay((1+index+rowIndex)*200).animate({opacity: 1});
				
				if (index >= (numCols-1))
				{
					if (rowIndex == 0)
					{
						index = 1
					} else {
						index = 0;
					}
					rowIndex++;
				} else {
					index++;
				}
			});
		},
		
		buildHome: function(numAcross) {
			numCols = numAcross;
			
			//alert(numCols);
					
			var index = 0;
			var rawIndex = 0;
			var rowIndex = 0;
			$(".category").find(".box, .videoBox").css("opacity", 0).css("display", "block");
			$(".category").find(".box, .videoBox").each(function() {
				rawIndex++;
				if (index == 0)
				{
					// we have a new row
					//alert(rawIndex + ": " + numCols + " " + rowIndex + " " + $(this).attr("class"));
					Shelby.doCascade(numCols, rowIndex, $(this));
				}
				
				if ($(this).hasClass("videoBox"))
				{
					index+=2;
				} else {
					index++;
				}
				
				if (index >= numCols)
				{
					index = 0;
					rowIndex++;
				}

			});
			
			setTimeout("Shelby.buildAll()", (numCols*2)*timeOutIncrement+1500);			
		},
				
		buildAll: function() {
			$(".box, .videoBox").css("opacity", 1);
			$(".box, .videoBox").show();
		},
		
		buildArchive: function() {
			$("#archive1").click(function() {
				$("#archiveContent1").fadeIn("fast");
				$(this).hide();

				$("#archive2").show();
				$("#archiveContent2").hide();
				
				return false;
			});
			
			$("#archive2").click(function() {
				$("#archiveContent2").fadeIn("fast");
				$(this).hide();
				
				$("#archive1").show();
				$("#archiveContent1").hide();
				
				return false;
			});
			
			$("#archiveContent1").hover(function() {
			
			}, function() {
				$("#archive1").show();
				$(this).fadeOut("fast");
			});
			$("#archiveContent2").hover(function() {
			
			}, function() {
				$("#archive2").show();
				$(this).fadeOut("fast");
			});
		},
		
		handleSort: function() {
			$(".filters .sort2 a").click(function() {
				$(".filters div a").not(this).toggleClass("active", false);
				$(this).toggleClass("active", true);
				$(".category").toggleClass("sort2", false);
				$(".section .box").toggleClass("SortHide", false);
				$(".section").each(function() {
					$(this).children(".box").toggleClass("SortHIDE", false);
				});	
				Shelby.fixLayout(0);
				
			});
			$(".filters .sort1 a").click(function() {
				
				$(".filters div a").not(this).toggleClass("active", false);
				$(this).toggleClass("active", true);
				$(".category").toggleClass("sort2", true);
				
				$(".section").each(function() {
					$(this).children(".box:gt("+(numCols-1)+")").toggleClass("SortHIDE", true);
				});
				
				Shelby.fixLayout(0);
				
			});
		},
		
		buildLightboxClose: function() {
			$(".lightbox .detail .lightboxPhoto .close a").unbind("click");
			$(".lightbox .detail .lightboxPhoto .close a").click(function(event) {
				event.preventDefault();
				Shelby.favoriteRemove($(this).parent().parent().find(".meta .entryid").html());
				$(this).parent().parent().fadeOut("fast");
				
				return false;
			});
		
		},
		
		buildLightbox: function() {
			$(".lightbox .tab").click(function() {
				if ($(this).parent().hasClass("activeLightbox"))
				{
					$(this).parent().toggleClass("activeLightbox", false);
					
					$(".lightbox .detail").slideUp("fast", function () {
						$(".lightbox .detail .lightboxInstructions").show();					
					});
					
					$(".lightbox .submit").slideUp("fast");
				} else {
					$(this).parent().toggleClass("activeLightbox", true);
					$(".instructioncontent").html("Send your lightbox image(s) and inquiries to Shelby Gallery");
					$(".submitInstructions .button").show();
					$(".lightbox .detail").slideDown("fast");
				}
				return false;
			});
			
			$(".primary_navigation .pnav_lightbox").click(function() {
					$(".lightbox .tab").click();
				return false;
			});
			
			strSend = "/img/button.lightbox.send.gif";
			strSendOver = "/img/button.lightbox.send.active.gif";
			$(".sendlightbox").hover(function() {
					$(this).children("img").attr("src", strSendOver);
			}, function() {
					$(this).children("img").attr("src", strSend);
			});

			strSubmit = "/img/button.lightbox.gif";
			strSubmitOver = "/img/button.lightbox.active.gif";
			$(".submitlightbox").hover(function() {
					$(this).children("img").attr("src", strSendOver);
			}, function() {
					$(this).children("img").attr("src", strSend);
			});
			
			Shelby.buildLightboxClose();
			
			$(".lightbox .lightboxInstructions .button a").click(function() {
				$(this).parent().parent().fadeOut("fast");
				$(".lightbox .submit").slideDown("fast");
			});
			
			/*
			$(".lightbox .submitInstructions .button a").click(function() {
				$(".lightbox .tab").click();
			
			});
			*/
			
			$(".submit .button").click(function(event) {
				event.preventDefault();
				
				base = "http://www.shelbygallery.com";
				
				strName = $("#name").val();
				strEmail = $("#email").val();
				strMessage = $("#message").val();
				
				strBody = "Name: " + strName + "\r\n";
				strBody+= "Email: " + strEmail + "\r\n";
				
				var strImages = "";
				
				strBody+= "Message: " + strMessage + "\r\n\r\n";
				
				$(".lightboxHolder .lightboxPhoto").each(function() {
					strImages += base + $(this).find(".thumb").attr("src") + "\r\n";
				});				
				
				strBody+= "Lightbox Photos:\r\n";
				strBody+= strImages;
				
			
				$.post("/formHandler.php", {to: "seangw@seangw.com", subject: "Lightbox Submission: "+strEmail, message: strBody});
				
				$(".instructioncontent").html("Thank you, your lightbox and contact info have been sent.");
				$(".submitInstructions .button").fadeOut("slow");
				
				Shelby.resetFavorites();
				
				$(".lightbox .tab").click();
				
			});
		
		},
		
		buildHovers: function() {
			$(".box").hover(function() {
				$(this).toggleClass("boxactive", true);
			}, function() {
				$(this).toggleClass("boxactive", false);
			});
			
			$(".boxTitle").hover(function() {
				$(this).parent().toggleClass("boxactive", true);
			}, function() {
				$(this).parent().toggleClass("boxactive", false);
			});
			
			$(".videoBox").hover(function() {
				$(this).toggleClass("videoBoxInactive", false);
				$(this).toggleClass("boxactive", true);
			}, function() {
				$(this).toggleClass("videoBoxInactive", true);
				$(this).toggleClass("boxactive", false);
			});
			
			$(".categoryBox").hover(function() {
				$(this).toggleClass("boxactive", true);
			}, function() {
				$(this).toggleClass("boxactive", false);
			});
			
			$(".archive").hover(function() {
				$(this).children("img").attr("src", "/img/btn.archive.over.gif");
			}, function() {
				$(this).children("img").attr("src", "/img/btn.archive.gif");
			});
			
		},
		
		initialLayout: function() {
			
			var size = curSize*2+cGutterSize;
			
			$("#categoryMore a").click(function(e) {
				e.preventDefault();
				if ($(".categoryTitle").hasClass("showAllCategory")) {
					$(".categoryTitle").toggleClass("showAllCategory", false);
					$("#categoryMore a").html("View All");
					$(".categoryTitle").css("height", "569px");
				} else {
					$(".categoryTitle").toggleClass("showAllCategory", true);
					$("#categoryMore a").html("View Less");
					var hei = $(window).height();
					hei += -124;
					$(".categoryTitle").css("height", hei + "px");

				}
			});
			
			//$(".identity").css("width", size+"px");
			//$(".primary_navigation").css("width", size+"px").css("left", size+7+cGutterSize);
		
			
		},
		
		getFixedColumns: function(width) {
			var winWidth = $(window).width();
			var docWidth = $(document).width();
			
			var usable = docWidth - cGutterSize*2+2;
						
			return Math.floor(usable / (width+cGutterSize));

		},
		
		fixLayout: function(init) {
		
			var winWidth = $(window).width();
			var docWidth = $(document).width();
			
			var usable = winWidth - cGutterSize*2 - 8;
			//var usable = docWidth - cGutterSize*2 - cMaxCols;

			$(".lightbox").width(usable - cGutterSize*2+5);
			
			
			var newSize = (usable / cMaxCols) - cGutterSize;

			curCols = cMaxCols;
			while(newSize < cMinSize && curCols > cMinCols)
			{
				curCols--;
				newSize = (usable / curCols) - cGutterSize;
			}
			
			var numItems = $(".category>div").length;
			if (numItems < curCols)
			{
				curCols = numItems;
				newSize = (usable / curCols) - cGutterSize;
				
				//newSize = Math.min(newSize, cMaxSize);
			}
			
			while(newSize > cMaxSize) {
				curCols++;
				newSize = (usable / curCols) - cGutterSize;
			}
						
			curSize = newSize;
			
			$(".category").width(winWidth-10);
			
			rightGutter = winWidth - (7 + (curSize + cGutterSize) * curCols)+5;
			$(".footer .right").css("right", rightGutter+"px");
		
			$(".lightbox .tab").width(newSize);
			numCols = curCols;
			//Shelby.checkLines(init);
			Shelby.setBoxSize(Math.round(newSize));
			Shelby.buildHovers();
			
						
			$(".videoBox").click(function() {
				

				
				/*$(".category .box, .category .videoBox").not($(this)).each(function() {
					$(this).css("opacity", .2);
				});	*/
				
				$(".category .box, .category .videoBox").each(function() {
					$(this).css("opacity", .2);
				});	
				
				//$(this).css("opacity", 1);
				
				off = $(this).offset();

				strVid = $(this).find(".videoFile").html();
				
				if (isMobile) {
				
					video = $("#theVideo").get(0);
					video.pause();
					video.src = $(this).find(".videoFile").html();
					video.load();
					video.addEventListener("canplaythrough", Shelby.autoPlay, false);
					
					video.addEventListener("ended", Shelby.handleVideoEnd, false);
				} else {
					$("#flowPlayer").show();
					
					$f("flowPlayer", "/js/flowplayer.commercial-3.2.7.swf", {
						clip: {
							url: strVid,
							autoPlay: true,
							autoBuffering: true,
							scaling: "orig"
						},
						
						
						canvas: {
							backgroundGradient: 'none',
							bckgroundColor: '#000000'
						},
						plugins: {
							controls: {
								url: "/js/flowplayer.controls-3.2.5.swf",
								time: false,
								volume: false,
								backgroundGradient: 'none'
							}
						},
						key: '$2ad92a22191ce0c9326'
					});
					$f("flowPlayer").play();
				}
					
				/*$("#theVideo").src = $(this).find(".videoFile").html();
				$("#theVideo").load();
				$("#theVideo").get(0).play();
				
				*/
				$("#videoPlayer h3").html($(this).find("h3").html());
				$("#videoPlayer .vcontent").html($(this).find(".text_more").html());
				//$("#videoPlayer").css({left: off.left+"px", top: (off.top-192)+"px", width: $(this).width()*1.3333+"px", height: ($(this).height()*3+cGutterSize*2)+"px"});
				//$("#videoPlayer").css({left: off.left+"px", top: (off.top-192)+"px", width: "700px", height: "500px"});
				$("#videoPlayer").css({position: "fixed", left: 200+"px", top: 77+"px", width: "700px", height: "640px"});
				$("#videoPlayer").fadeIn("slow");
				return false;
				
			});

			$("#videoPlayer .close").click();

			
			//clearTimeout(timeoutLazyLoad);
			//timeoutLazyLoad = setTimeout('$("img").lazyload({threshhold: 200});', 500);
		},
		
		autoPlay: function() {
			var video=$("#theVideo").get(0);
			video.play();
		},
		
		handleVideoEnd: function() {
			$("#videoPlayer .close").click();
		},

		getColumns: function() {
			var winWidth = $(window).width();
			var docWidth = $(document).width();
			
			var usable = winWidth - cGutterSize*2 - cMaxCols - 0;
			//var usable = docWidth - cGutterSize*2 - cMaxCols;
		
			var newSize = (usable / cMaxCols) - cGutterSize;

			curCols = cMaxCols;
			while(newSize < cMinSize && curCols > cMinCols)
			{
				curCols--;
				newSize = (usable / curCols) - cGutterSize;
			}
			
			var numItems = $(".category>div").length;
			if (numItems < curCols)
			{
				curCols = numItems;
				newSize = (usable / curCols) - cGutterSize;
				
				//newSize = Math.min(newSize, cMaxSize);
			}
			
			while(newSize > cMaxSize) {
				curCols++;
				newSize = (usable / curCols) - cGutterSize;
			}
			
			curSize = newSize;
			
			return curCols;
		},
		
		checkLines: function(init) {
			// look for line breaks forced from videos
			
			var temp;
			var cIndex = 0;
			var content = $(".category").find(".box, .videoBox");
			var swapped = 0;
						
			content.each(function() {
				if ($(".category").hasClass("sort2") && $(this).hasClass("boxTitle"))
				{
					cIndex = 0;
				}
				if ($(this).hasClass("videoBox"))
				{
					// check index;
					
					if (cIndex > (numCols - 3) && $(this).next().length > 0)
					{
						//alert(cIndex + " / " + numCols + " " + $(this).next().length);
						//alert(swap);
					
						swapped = 1;
						
						tempHtml = $(this).next().html();
						tempClass = $(this).next().attr("class");
						
						$(this).next().html($(this).html());
						$(this).next().attr("class", $(this).attr("class"));
						
						$(this).html(tempHtml);
						$(this).attr("class", tempClass);
						
						return false;
					} else {
						cIndex+=3;
					}
				} else {
					cIndex++;
				}
				if (cIndex > numCols) cIndex = 0;
			});
			
			
			if (swapped == 1) {
				Shelby.checkLines(init)
				
			} else if (init == 1){
				alert("BUILDING");
				Shelby.buildHome(numCols);
			}
			
		},
		
		setBoxSize: function(nWidth) {
			
				
			// Set standard box sizes
			$(".box").css("width", nWidth+"px").css("height", nWidth+"px");
			$(".box img").not(".overlay img").css("width", nWidth+"px").css("height", nWidth+"px");
			
			// Set Video Box Sizes
			var videoBoxWidth = nWidth * 3 + cGutterSize * 2;
			var videoBoxTitleWidth = nWidth * 2 + cGutterSize;
			
			$(".videoBox").css("width", videoBoxWidth+"px").css("height", nWidth+"px");
			$(".videoBoxTitle").css("width", videoBoxTitleWidth+"px").css("height", nWidth+"px");

			// set the navigation sizes
			
		}
		

	}

	window.Shelby = Shelby;
	$(document).ready(function(){Shelby.ondomready();});
})(jQuery);

