var golf_digest = function() {
	
	var self = {
		//Private Members
		sortBy: "",
		sortDirection : "",
		sortDirections : {
			asc : "ascending",
			desc: "descending",
			// changes the sort from asc->desc or vice versa
			flip : function() {
				(self.sortDirection == self.sortDirections.asc) ? 
					self.sortDirection = self.sortDirections.desc : self.sortDirection = self.sortDirections.asc;
				// window.alert(self.sortDirection);
			},
			change : function (field, direction) {
				self.sortBy = field;
				self.sortDirections[direction]
				self.refreshProductListing();
			}
		},
		filterSettings : {
			filterValue: "",
			change: function (newFilterValue) {
				self.filterSettings.filterValue = newFilterValue;
				self.filterSettings.updateStorage();
				self.refreshProductListing();
			},
			clear: function () {
				self.filterSettings.filterValue = "";
				self.refreshProductListing();
			},
			favorites: function () {
				self.filterSettings.filterValue = "Product_Class=Favorites";
				self.refreshProductListing("fav");
			},
			updateStorage : function () {
				// $.cookie("gdbg09-f", self.filterSettings.filterValue);
			},
			updateStore : function () {
				// self.filterSettings.filterValue = $.cookie("gdbg09-f");
				// 				self.refreshProductListing();
			}
		},
		pages : {
			currentPage : 1,
			autoRotateDuration: 3850,
			autoRotateEnabled: false,
			totalPages : function () { return ($("div.page").length); },
			gotoPage : function (pageNumber) {
				if ((pageNumber <= self.pages.totalPages()) && (pageNumber > 0)) {
					self.pages.currentPage = pageNumber;
					self.selectPage();
					return true;
				} else { return false; }
			},
			nextPage : function () {
				self.pages.gotoPage(self.pages.currentPage + 1);
			},
			prevPage : function () {
				self.pages.gotoPage(self.pages.currentPage - 1);
			},
			autoRotate : function () {
				setTimeout(function() {
						if (self.pages.autoRotateNext()) {self.pages.autoRotate()}
					},
					self.pages.autoRotateDuration
					);
			},
			autoRotateNext : function () {
				if (self.pages.autoRotateEnabled) {
					if (self.pages.currentPage == self.pages.totalPages()) { self.pages.gotoPage(1)} else {self.pages.nextPage()};
				}
				return self.pages.autoRotateEnabled;
			}	
		},
		favorites : {
			favoriteStore : "0",
			addFavorite : function (key) {
				// window.alert("adding " + key);
				self.favorites.updateStore();
				if ((self.favorites.favoriteStore.indexOf("," + key) == -1) ? self.favorites.favoriteStore += ("," + key) : false) {self.favorites.updateStorage() };
			},
			updateStorage : function () {
				$.cookie('gdbg09', self.favorites.favoriteStore);
			},
			updateStore : function () {
				self.favorites.favoriteStore = (($.cookie('gdbg09')) ? $.cookie('gdbg09') : "0") ;
			},
			show : function () {
				self.favorites.updateStore();
				window.alert(self.favorites.favoriteStore.toString());
			}
		},
		
		// General Events
		
		refreshProductListing : function (operation) {
			self.sortProducts(operation);
			return true;
		},
		// Functions
		
		sortProducts : function (operation) {
			// Default sorts
			var ajaxOperation = ((operation ? operation : "items"));
			$("#product_container").fadeOut("fast",
				function() {
				// Replace the items with a sorted set
				$("#product_container").load("smf.xml.products.asp",
					{ sortBy: self.sortBy
						, sortDirection: self.sortDirection
						, op: ajaxOperation
						, filter: self.filterSettings.filterValue
					},
					function() {
						$("#product_container").fadeIn("fast");
						self.buildPaginationElements();
						self.buildLearnMoreLinks();
						self.updateBreadcrumb();
						self.pages.gotoPage(1);
					}
				);}
			);
		},
		
		slideProducts : function () {
			var moveTo = (($("#page1").width() + parseInt($("#page1").css("padding-left"))) * (self.pages.currentPage - 1));
			$("#product_container").animate(
				{ left: (moveTo * -1) }, "normal", "swing"
			);
		},

		selectPage : function() {
			// $(".pageNumber").removeClass("currentPage");
			// 			$("#pageNumber" + pageNumber).addClass("currentPage");
			// Enable the next navigation if we're not on the last page
			if (self.pages.currentPage == self.pages.totalPages()) { 
				$("#pageNavigationNext").addClass("disabled");
			} else {
				$("#pageNavigationNext").removeClass("disabled");
			  };
			if (self.pages.currentPage == 1) {
				$("#pageNavigationPrev").addClass("disabled");
			} else {
				$("#pageNavigationPrev").removeClass("disabled");
			};
			self.slideProducts();
		},
		
		showProduct : function (itemDiv) {
			// Grab this element's content and place into our thickbox element
			// $(this).html("");
			// Get the current key and page
			var itemHash = $(itemDiv).find("div.key").text() + "|" + self.pages.currentPage;
			
			// $("#detail").html($(this).parent().clone().html());
			$("#detail").html(itemDiv.clone().html());
			
			
			var imageLocation = $("#detail div.Image_Product_Image img").attr("src")
			imageLocation = imageLocation.replace(parseUri(window.location.href).host,"").replace("http://","");
			var videoXML = "videoID.asp?videoID=" + $("#detail div.Video_ID").text() + "&image=" + URLEncode(imageLocation);
			// var videoXML = "./videoId.xml";
			
						// 
						// window.alert("video: " + $("#detail div.Video_ID").text());
						// window.alert("image: " + imageLocation);
						// window.alert("videoXML: " + videoXML);
			var flashVars = { xmlin : URLEncode(videoXML) };
			var paramSet = { flashvars : "xmlin=" + URLEncode(videoXML)};
			
			$("#detail").append($("div#sendToAFriendForm.dynamic").clone());
			$("#detail").append($("div#detailLinksTemplate").clone());
			
			// Invoke ThickBox
			var t = itemDiv.title || itemDiv.name || null;
			var a = "#TB_inline?inlineId=detail&width=900&height=360&modal=false";
			var g = itemDiv.rel || false;
			tb_show(t,a,g, function () {
				// Change the address bar
				window.location.hash = itemHash;
				// Callback once the div is loaded and fading in
				
				$("div#TB_window div#TB_ajaxContent").append("<div id='TBVideo'><div id='flashPlayer'></div></div>");
				// Show the associated video
				if ($("#detail div.Video_ID").text() > "") {
					$("#TBVideo").show();
					swfobject.embedSWF("golf_digest_videoplayer.swf", "flashPlayer", "400", "300", "9.0.0", false, flashVars, paramSet);
				} else { $("#TBVideo").hide();}
				
				// Set the keys for e-mailing a single item
				$("div#TB_window div#TB_ajaxContent #sendToAFriendForm form#sendToAFriendEmail input[name='emailKey']").val($("div#TB_window div#TB_ajaxContent div.key").text());
				$("div#TB_window div#TB_ajaxContent #sendToAFriendForm form#sendToAFriendEmail input[name='emailType']").val("item");
				$("div#TB_window div#TB_ajaxContent #sendEmailButton").click( function () {
					
					$.post("emailsend.asp?", $("div#TB_window div#TB_ajaxContent #sendToAFriendForm form#sendToAFriendEmail").serialize(), function () {
						$("div#TB_window div#TB_ajaxContent #sendToAFriendForm").fadeOut();
						$("div#TB_window div#TB_ajaxContent a#sendToAFriendLink").text("Thank you. Your email was sent!");
						});
				
					return false;
				});
				
			});
			self.pages.autoRotateEnabled = false;
			$(itemDiv).blur();
			return true;
		},
		
		buildNavigationHover : function() {
			$.each($(".nav"),
			function (b,a){
				var relHover = $(".navItemHover." + $(a).attr('class').split(' ').slice(-1));
				$(a).hover(
					function () {
						$(this).addClass("navHover");
						$(relHover).fadeIn("fast");
					},
					function () {
						$(this).removeClass("navHover");
						$(relHover).fadeOut("fast");
					}
				)
				return true;
			});
			
			$(".navItemHover").hide();
		},
		
		buildProductNavigation : function() {
			// if ((window.location.toString().indexOf('items.asp') > 0) && (window.location.toString().indexOf('search=') < 0)) {
				// $(".navItemHoverListItem a").click (
				// 				function () {
				// 					golf_digest.filter.filterBy($(this).attr("href").split("filter=").slice(-1));
				// 					$(this).parent().parent().parent().fadeOut("fast");
				// 					return false;
				// 				}
				// 			);
				// 			$("div.nav").click (
				// 				function () {
				// 					golf_digest.filter.filterBy("Product_Class='" + $(this).attr("class").split(" ")[1] + "'");
				// 					$(this).children(".navItemHover").fadeOut("fast");
				// 				}
				// 			);
				// 		} else {
				$("div.nav").click (
				function () {
					window.location = "./items.asp?filter=Product_Class='" + $(this).attr("class").split(" ")[1] + "'";
				}
				);
			// };
		},
		
		buildLearnMoreLinks : function () {
			$("div.Learn_More_Buy_More a").attr("target","_blank");
			var thisDiv = $(this);
			$("div.item").click(function () {
				self.showProduct($(this));
			}
			);
			
			// $("div.item div.learnMore, div.item div.Title").click (
			// 				function () {
			// 					// Grab this element's content and place into our thickbox element
			// 					// $(this).html("");
			// 					
			// 					$("#detail").html($(this).parent().clone().html());
			// 					
			// 					var imageLocation = $("#detail div.Image_Product_Image img").attr("src");
			// 					var videoXML = "videoID.asp?videoID=" + $("#detail div.Video_ID").text() + "&image=" + URLEncode(imageLocation.replace(parseUri(window.location).host,"").replace("http://",""));
			// 					
			// 					var flashVars = { test : true};
			// 					var paramSet = { flashvars : "xmlin=" + URLEncode(videoXML)};
			// 					
			// 					$("#detail").append($("div#sendToAFriendForm.dynamic").clone());
			// 					$("#detail").append($("div#detailLinksTemplate").clone());
			// 					
			// 					// Invoke ThickBox
			// 					var t = this.title || this.name || null;
			// 					var a = "#TB_inline?inlineId=detail&width=900&height=360&modal=false";
			// 					var g = this.rel || false;
			// 					tb_show(t,a,g, function () {
			// 						// Callback once the div is loaded and fading in
			// 						
			// 						$("div#TB_window div#TB_ajaxContent").append("<div id='TBVideo'><div id='flashPlayer'></div></div>");
			// 						// Show the associated video
			// 						if ($("#detail div.Video_ID").text() > "") {
			// 							$("#TBVideo").show();
			// 							swfobject.embedSWF("golf_digest_videoplayer.swf", "flashPlayer", "400", "300", "9.0.0", false, flashVars, paramSet);
			// 						} else { $("#TBVideo").hide();}
			// 						
			// 						// Set the keys for e-mailing a single item
			// 						$("div#TB_window div#TB_ajaxContent #sendToAFriendForm form#sendToAFriendEmail input[name='emailKey']").val($("div#TB_window div#TB_ajaxContent div.key").text());
			// 						$("div#TB_window div#TB_ajaxContent #sendToAFriendForm form#sendToAFriendEmail input[name='emailType']").val("item");
			// 						$("div#TB_window div#TB_ajaxContent #sendEmailButton").click( function () {
			// 							$.post("emailsend.asp?", $("div#TB_window div#TB_ajaxContent #sendToAFriendForm form#sendToAFriendEmail").serialize(), function () {
			// 								$("div#TB_window div#TB_ajaxContent #sendToAFriendForm").fadeOut();
			// 								$("div#TB_window div#TB_ajaxContent a#sendToAFriendLink").text("Thank you. Your email was sent!");
			// 								});
			// 							return false;
			// 						});
			// 						
			// 					});
			// 					self.pages.autoRotateEnabled = false;
			// 					this.blur();
			// 					return true;
			// 				}
			// 			);
			// 			$("div.item div img").click (
			// 				function () {
			// 					// Grab this element's content and place into our thickbox element
			// 					// $(this).html("");
			// 					
			// 					$("#detail").html($(this).parent().parent().clone().html());
			// 					
			// 					var imageLocation = $("#detail div.Image_Product_Image img").attr("src");
			// 					var videoXML = "videoID.asp?videoID=" + $("#detail div.Video_ID").text() + "&image=" + URLEncode(imageLocation.replace(parseUri(window.location).host,"").replace("http://",""));
			// 					
			// 					var flashVars = { test : true};
			// 					var paramSet = { flashvars : "xmlin=" + URLEncode(videoXML)};
			// 					
			// 					$("#detail").append($("div#sendToAFriendForm.dynamic").clone());
			// 					$("#detail").append($("div#detailLinksTemplate").clone());
			// 					
			// 					// Invoke ThickBox
			// 					var t = this.title || this.name || null;
			// 					var a = "#TB_inline?inlineId=detail&width=900&height=360&modal=false";
			// 					var g = this.rel || false;
			// 					tb_show(t,a,g, function () {
			// 						// Callback once the div is loaded and fading in
			// 						
			// 						$("div#TB_window div#TB_ajaxContent").append("<div id='TBVideo'><div id='flashPlayer'></div></div>");
			// 						// Show the associated video
			// 						if ($("#detail div.Video_ID").text() > "") {
			// 							$("#TBVideo").show();
			// 							swfobject.embedSWF("golf_digest_videoplayer.swf", "flashPlayer", "400", "300", "9.0.0", false, flashVars, paramSet);
			// 						} else { $("#TBVideo").hide();}
			// 						
			// 						// Set the keys for e-mailing a single item
			// 						$("div#TB_window div#TB_ajaxContent #sendToAFriendForm form#sendToAFriendEmail input[name='emailKey']").val($("div#TB_window div#TB_ajaxContent div.key").text());
			// 						$("div#TB_window div#TB_ajaxContent #sendToAFriendForm form#sendToAFriendEmail input[name='emailType']").val("item");
			// 						
			// 						$("div#TB_window div#TB_ajaxContent #sendEmailButton").click( function () {
			// 							$.post("emailsend.asp?", $("div#TB_window div#TB_ajaxContent #sendToAFriendForm form#sendToAFriendEmail").serialize(), function () {
			// 								$("div#TB_window div#TB_ajaxContent #sendToAFriendForm").fadeOut();
			// 								$("div#TB_window div#TB_ajaxContent a#sendToAFriendLink").text("Thank you. Your email was sent!");
			// 								});
			// 							return false;
			// 						});
			// 						
			// 					});
			// 					self.pages.autoRotateEnabled = false;
			// 					this.blur();
			// 					return true;
			// 				}
			// 			);
			self.buildItemHover();
		},
		
		buildPaginationElements : function() {
			$("#product_container").width((self.pages.totalPages() + 1) * $("#page1").width());
			if (self.pages.totalPages() < 2)
			{
				$("#pageNavigationNext").hide();
				$("#pageNavigationPrev").hide();
			} else
			{
				$("#pageNavigationNext").show();
				$("#pageNavigationPrev").show();
			};
			// $("#pageNavigation").html("");
			// 			$.each($("#product_container > div.page"),
			// 			function (b,a){
			// 				$("#pageNavigation").append("<div class='pageNumber' id='pageNumber" + (b + 1) + "'><a href='#' onclick='golf_digest.showPage(" + (b + 1) + ")'>" + (b + 1) + "</a></div>");
			// 				return true
			// 			});
		},
	
		updateBreadcrumb : function () {
			var parseFilter = ("?" + self.filterSettings.filterValue).replace(/ and /g,"&").replace(/\"/g,"").replace(/\'/g,"");
			var parseKey = parseUri(parseFilter).queryKey;
			var parseFilterValue = "";
			var parseURL = parseUri(window.location).queryKey;
			var numOfItems = $("#product_container div.item").length + 0;
			
			// Product Class Breadcrumb
			$("#productBreadcrumb #filterInfo").html((parseKey.Product_Class ? parseKey.Product_Class : "All"));
			((parseUri(window.location).file == "favorites.asp") ? $("#productBreadcrumb #filterInfo").html("Favorites") : false);
			$("#productBreadcrumb #filterInfo").html((parseURL.search ? "Search" : "All"));
			
			// Sub-Type Breadcrumb
			parseFilterValue = (parseKey.Brand ? parseKey.Brand : (
				parseKey.Product_Sub_Type ? parseKey.Product_Sub_Type : (
					parseKey.Price ? parseKey.Price : (
						(parseURL.search) ? parseURL.search : "All")
					)
				)
			);
			parseFilterValue = (numOfItems == 0) ? "Sorry, your search returned no product matches." : parseFilterValue;
			$("#productBreadcrumb #filterValue").html(parseFilterValue);
			
			// Brand Logo
			if (parseKey.Brand) {
				$("#brandLogo").html("<img src='images/brands/" + parseKey.Brand.toLowerCase() + ".jpg' />");
			} else {
				$("#brandLogo").html("");
			}
				
			// Item Count
			
			(numOfItems > 0) ? $("#productBreadcrumb #itemCount").html(numOfItems + " items") : $("#productBreadcrumb #itemCount").html("no items found");
			(parseFilterValue == "") ? parseFilterValue = "All" : true;
		},
		
		buildSearch : function () {
			$("#searchField").keypress(function (e) {  
		        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {  
		            window.location = "items.asp?search=" + $(this).val();
		            return false;  
		        } else {
		        	$("#searchFieldButton").attr("href","items.asp?search=" + $(this).val());
		            return true;  
		        }
	        });
	        $("#searchField").blur(function (e) {  
		        	$("#searchFieldButton").attr("href","items.asp?search=" + $(this).val());
		            return true;  
	        }); 
		},
		
		buildItemHover : function () {
			$("body").find("div.item:not(.featured) div.Title").hide();
			$("div.item:not(.featured)").bind("mousemove", function () {
				// $("div.item:not(.featured) div.Title").hide();
				// $(this).find("div.Title").fadeIn("normal");
				$(this).find("div.Title").show();
			});
			$("div.item:not(.featured)").bind("mouseout",function () {
				$(this).find("div.Title").hide();
			});
			$("div.item:not(.featured) div.Title").bind("mouseout", function () {
				$(this).hide();
			});
		}
	};
	
	
	//Public Member
	var pub = {
		sort : {
			flip : function () {
				self.sortDirections.flip();
				return true;
			},
			current : function () {
				return self.sortDirection;
			},
			change : function (field, direction) {
				self.sortDirections.change (field, direction);
				return true;
			}
		},
		filter : {
			filterBy : function (newFilter) {
				self.filterSettings.change(newFilter);
			},
			clear : function () {
				self.filterSettings.clear();
			}
		},
		showPage : function (pageNumber) {
			self.pages.gotoPage(pageNumber);
		},
		autoRotate : function () {
			if ($("#product_container.featured").length > 0) { self.pages.autoRotateEnabled = true; self.pages.autoRotate(); }
		},
		addToFavorites : function (object) {
			self.favorites.addFavorite($(object).parent().parent().find("div.key").text());
			$(object).fadeOut("slow").text("Thank you! This item is in your favorites").fadeIn("normal");
			return false;
		},
		showFavorites :  function () {
			self.favorites.show();
		},

		sendFavoritesEmail: function (obj) {
			// $("#favoritesEmailForm").append($("#sentToAFriendForm"));
			var t = "Email your favorites";
			var a = "#TB_inline?inlineId=favoritesEmailForm&width=340&height=190&modal=false";
			$("#sendToAFriendFormFavorites").show();
			var g = this.rel || false;
			tb_show(t,a,g, function () {
				// $("#TB_ajaxContent #sendToAFriendForm").addClass("favorites").show();
				$("#TB_ajaxContent #sendToAFriendFormFavorites input#sendEmailButton").click( function () {
					$(this).unbind("click");
					$(this).attr("href","#");
					$.post("emailsend.asp?", $("#TB_ajaxContent #sendToAFriendFormFavorites form#sendToAFriendEmail").serialize(), function () {
						// $("#TB_window").append("Thank you! Your email was sent!");
						$("#TB_ajaxContent #sendToAFriendFormFavorites").fadeOut(3000, function () {
							// Wait 3 seconds
							tb_remove();
						});
						
						
						
						// $("#favoritesEmailForm #sentToAFriendForm").remove();
						});
					return false;
				});
			});
			$("#sendToAFriendFormFavorites").hide();
		}
	};	
	
	pub.init = function () {
		$("#pageNavigationPrev").hover( function () { $(this).toggleClass("grey"); }, function () { $(this).toggleClass("grey"); });
		$("#pageNavigationNext").hover( function () { $(this).toggleClass("grey"); }, function () { $(this).toggleClass("grey"); });
		$("#pageNavigationPrev").click( function () {
			self.pages.autoRotateEnabled = false;
			self.pages.prevPage();
		});
		$("#pageNavigationNext").click( function () {
			self.pages.autoRotateEnabled = false;
			self.pages.nextPage();
		});
		
		if ((parseUri(window.location).queryKey.filter) || (parseUri(window.location).file == "default.asp") || (parseUri(window.location).file == "")) {
			self.filterSettings.filterValue = URLDecode(parseUri(window.location).queryKey.filter);
			self.filterSettings.updateStorage();
		} else
		{
			// self.filterSettings.updateStore();
		};
		// Pull the current item and page from the URL (if available)
		var itemHash = window.location.hash.split("|");
		var itemPage = (itemHash ? itemHash[1] : 1);
		var itemNumber = (itemHash ? itemHash[0].replace("#","") : "");
		
		// Initialize navigation and products
		self.sortDirection = self.sortDirections.asc;
		self.buildNavigationHover();
		self.buildProductNavigation();
		self.buildPaginationElements();
		self.buildLearnMoreLinks();
		self.buildSearch();
		self.buildItemHover();
		// self.buildFavoritesLink();
		self.updateBreadcrumb();
		self.pages.gotoPage(itemPage);
		// If we find an item key, find the DIV and invoke the method
		var itemDiv = null; 
		if (itemNumber.length > 1) {
			$("div.page div.item").each( function () {
				var itemTest = $(this).find("div.key").text();
				if (itemTest == itemNumber) {
					itemDiv = $(this);
					return false;
				}
			});
			$(itemDiv).click();
		}
		
		self.favorites.updateStore();
		return true;
	}
	
	return  pub;
} ();
// ONLOAD EVENT

$(window).load(function () {
 	$(document).pngFix();
 	
 	// Initialize base object 	
 	golf_digest.init();
 	
 	// Start auto-rotator on a .featured
 	golf_digest.autoRotate();
 	
 	// Thickbox init
 	tb_init('a.thickbox');
});