var $lastOpen = null;	// last open category bar
var UKEY = 85;
var DKEY = 68;
var CKEY = 67;
var OKEY = 79;
var useKeys = true;
var view = "list";
var folderOpen = false;

$(function() {
	
	// clicking on kit images
	$(".kit .productImage").live("click",function() {
		var $me = $(this);
		// only if one is not open
		if(!folderOpen) {
			folderOpen = true;
			
			// close on window movement
			$(window).resize(function() {
				if(folderOpen) {
					$me.click();
				}
			});
			
			// escape closes as well
			$(document).keyup(function(e) {
				if(e.keyCode == 27 && folderOpen) {
					$me.click();
				}
			});
			
			// reference to this productBox
			var $pbox = $(this).parents(".productBox");
			// fade out everything but mee
			$(".productBox").not($pbox[0]).animate({
				opacity:.2
			},{queue:false});
			
			// were want to all blocks on my left
			// so count until the left pos is > than the prev
			var $onMyLeft = $();
			if($pbox.position().left != 15) {
				var left = 99999999;
				// when the left is > than the last left that means your on a new row
				$pbox.prevAll().each(function() {
					if($(this).position().left < left) {
						$onMyLeft.push(this);
						left = $(this).position().left;
					}
				});
				// just so we can quickly get them later
				$onMyLeft.add($pbox).addClass("moved");
			}	
			
			// create the folder
			var $children = $("<div class='childrenContainer'></div>");
			// it needs to start out in the right spot before going absolute
			if($pbox.position().left != 15) {
				$children.insertBefore($onMyLeft.filter(":last"));
			} else {
				$children.insertBefore($pbox);
			}	
			// modify the block to STAY in its relative position spot absolutely
			$children.css({
				width:$(window).width() - 100,
				height:0
			});
			
			// get more products
			$.post("kits/loadKitsInVideo",{kid:$pbox.find(".buyButton").attr("tid")},function(html) {
				$children.html(html);
				
				// it starts out in list view :<
				$children.find(".productBox").css({width:200,height:235,"margin-right":10,"float":"left"});
				$children.find(".productTitle").css("height",29);
				$children.find(".productDescription").css("height",70);
				$children.find(".productImage").css({width:200,height:116}).css("margin-right","");
				$children.find(".productImage img").css({width:200,height:116});
				$children.find(".buyButton").css({"margin-top":0,"float":"left"});
				$children.find(".productContent").css("float","left");
				
				// make the folder animate to the right height with the products movement
				$children.animate({
					height:235,
					"margin-bottom":15
				},{
					queue:false,
					complete: function() {
						var $pointer = $(".pointer");
						if(!$pointer.length) {
							$pointer = $("<div class='pointer'></div>");
							$pbox.parent().append($pointer);
							$pointer.css({
								left:$pbox.position().left + 84,
								top:$pbox.position().top - 20
							});
						}
					}
				});
				

			});
			
		// closing	
		} else {
			folderOpen = false;
			$(".pointer").remove();
			// slide up
			$(".childrenContainer").animate({
				height:0,
				padding:0,
				margin:0
			},{
				queue:false,
				// remove when done
				complete:function() {
					$(".childrenContainer").remove();
					$(".moved").removeClass("moved");
				}	
			});
			
			// fade it all back in
			$(".productBox").animate({
				opacity:1
			},{queue:false});
			
			// fade this out as everything is happening
			$(".childrenContainer").animate({
				opacity:0
			},{queue:false});
			
		}	
		
	});
	
	if($.fn.countdown) {
		$('.presaleClock').countdown({
			until:new Date($('.presaleClock').attr("until")*1000), 
			compact: true,
			layout:"{dnn}{sep}{hnn}{sep}{mnn}{sep}{snn}"
		});
	}	
	
	// don't play if the product isn't found
	$(".playForm").submit(function() {
		if($(this).parents(".productBox").hasClass("notFound")) return false;
	});
	
	// open the settings pane
	$("#toggleSettings").click(function() {
		if($("#settings").css("display") == "none") {
			$("#settings").fadeTo("fast",1);
		} else {
			$("#settings").fadeOut();
		}
		return false;
	});
	
	// make the settings pane draggable by the title
	$("#settings").draggable({ handle: '#settingsTitle' });
	
	$("#close_settings").click(function() {
		$("#settings").fadeOut();
	});
	
	// submit a single user subscription
	$(".buy_sub_now").click(function() {
		$me = $(this);
		$.post("login/checkLogin",function(data) {
			if(!data) {
				useKeys = false;
				
				$(".pageBlocker").clickAway(function() {
					useKeys = true;
				});
				$(".pageBlocker").fadeIn(function() {
					$("#floatingLogin").fadeIn();
					$("#floatingLogin").center();
				});
			} else {
				$me.parents("form").submit();
			}
		});
	});
	
	// if the url says myvideos click that guy
	if(location.href.search(/myvideos/) != -1) {
		$("[href=myvideos]").addClass("on");
	} else {
		$("[href=store]").addClass("on");
	}

	
	/*
	$(".category").each(function() {
		if(!$(this).find(".productBox").length) $(this).hide();
	});*/
	
	$("#numUsers").keyup(function() {
		var nUsers = $(this).val();
		$.post("subscriptions/multiSubPricing",{nUsers:nUsers},function(total) {
			// show total
			$("#multiTotal").html("Your total: $"+total);
			// item number
			$("#multi_item_number").val(nUsers);
		});
	});
	
	
	$(".categoryBar").hover(function() {
		$(this).find(".arrow").addClass("black");
		$(this).addClass("on");
	}, function() {
		if( $(this).next().css("display") == "none") {
			$(this).removeClass("on");
			if(!$(this).hasClass("on")) {
				$(this).find(".arrow").removeClass("black");
			}
		}	
	});
	
	// prevent right clicking	
	$(this).bind("contextmenu", function(e) {
		e.preventDefault();
	});
	
	// hovering the product box will make play appear
	// only when the product is found
	//
	$(".productBox:not(.notFound)").hover(function(e) {
		var $me = $(this);
		var $form = $me.find(".playForm");
		var $overlay = $me.find(".playOverlay");
		
		// always start out the same
		if($form.attr("action") != "video/watch") $form.swapAttr("action","href").attr("target","_self");
		
		
		if($form.attr("href") != "") {
			// if you were holding the alt key, show the info
			if(e.altKey) {
				$overlay.attr("src","images/InfoBlock.png").fadeTo(200,1);
				$form.swapAttr("action","href").attr("target","_blank");
			} else {
				$overlay.attr("src","images/playOverlay.png").fadeTo(200,1);
				
				// if you now press the alt key, show info
				$(document).bind("keydown.info",function(e) {
					if(e.altKey) {
						$overlay.attr("src","images/InfoBlock.png");
						$form.swapAttr("action","href").attr("target","_blank");
					}
				});
				// when you let go, go back to play
				$(document).bind("keyup.info",function(e) {
					$overlay.attr("src","images/playOverlay.png");
					$form.swapAttr("action","href").attr("target","_self");
				})
			}
		} else {
			$overlay.fadeTo(200,1);
		}
	},function() {
		$(document).unbind("keydown.info");
		$(document).unbind("keyup.info");
		$(this).find(".playOverlay").fadeTo(200,0);
	});
	
	
	
	// clicking on a play button
	$(".playOverlay").click(function() {
		
		if(_gaq) {
			_gaq.push(['_trackEvent', 'videos', 'play', $(this).parents("form").attr("href")]);
		}
		
		$(this).parents("form").submit();
		
		return false;
	}).mousedown(function() {
		return false;
	});
	
	// U for traversing upwards and D for crawling down
	$(document).keyup(function(e) {
		if(useKeys) {
			switch(e.keyCode) {
				case UKEY :
					if($lastOpen) {
						$lastOpen.fold();
						var $toOpen = $lastOpen.parent().prev().find(".categoryBar");
						if($toOpen.length > 0) {
							$lastOpen = $toOpen;
							$lastOpen.unfold();
						}
					}
					break;
				case DKEY :
					if($lastOpen) {
						$lastOpen.fold();
						var $toOpen = $lastOpen.parent().next().find(".categoryBar");
						if($toOpen.length > 0) {
							$lastOpen = $toOpen;
							$lastOpen.unfold();
						}	
					}
					break;
				case CKEY :
					$(".categoryBar").fold();
					break;
				case OKEY :
					$(".categoryBar").unfold();
					break;
				default:
					break;
			}
		}	
	});
	
	// clicking a product price will show a check mark
	$(".buyButton a").live("click",function() {
		var $me = $(this);
		var $parent = $me.parent();
		var classes = $me.parents(".productBox").attr("class");
		var type = $me.parents(".productBox").hasClass("kit") ? "k" : "t";
		// show the checkbox immediatly because we want this to seem fast
		$me.replaceWith("<div class='checkedProduct'></div>");
		addToCart($parent.attr("tid"),$parent.attr("title"),type);
		return false;
	});
	
	// add the click handler for unchecking a product
	$(".checkedProduct").live("click",function() {
		var $me = $(this);
		var $parent = $me.parent();
		removeFromCart($parent.attr("tid"),function() {
			var price = $parent.attr("price");
			$me.replaceWith("<a href='#'>Add To Cart - $"+price+"</a>");
			// if there are no products checked hide the checkout button
			if($(".checkedProduct").length == 0) $(".checkoutButton").hide();
		});
	});
	

	
	// live filter
	$("#categoryFilter > input").keyup(function() {
		var search = $(this).val();
		$(".productContent").each(function() {
			var haystack = $(this).text().toLowerCase();
			var needle = search.toLowerCase();
			var $categoryContent = $(this).parents(".categoryContent");
			if(haystack.lastIndexOf(needle) == -1) {
				$(this).parents(".productBox").fadeOut("fast",function() {
					if($categoryContent.find(".productBox:visible").length == 0) {
						$categoryContent.prev(".categoryBar").fold();
						$categoryContent.prev(".categoryBar").hide();
					}
				});
			} else {
				if($categoryContent.css("display") == "none") {
					$categoryContent.prev(".categoryBar").show();
					$categoryContent.prev(".categoryBar").unfold();
				}	
				$(this).parents(".productBox").fadeIn("fast");
			}
		});
		return false;
	}).focus(function() {
		if( $(this).val() == "Search") {
			$(this).val("");
		}
	}).blur(function() {
		if( $(this).val() == "") {
			$(this).val("Search");
		}
	}).keydown(function(e) {
		if(e.keyCode == 13) {
			return false;
		}
	});
	
	// clear filter button
	$("#clearFilter").click(function() {
		$("#categoryFilter input").val("");
		$(".productBox").show();
		$(".categoryBar").show();
		$(".categoryContent").show();
		return false;
	});
	
	// make text inside a category disabled
	$(".categoryBar").mousedown(function() {
		return false;
		
	// clicking a category folds it down	
	}).click(function() {
		var $me = $(this);
		var $next = $me.next();
		if( $next.css("display") == "none") {
			$(this).unfold();
		} else {
			$(this).fold();
		}
	});
	
	
	$("#thumbnailButton").click(function() {
		view = "thumb";
		$(".productBox").addClass("thumbViewBox");
		
		$categoryContentVisible = $(".categoryContent:visible");
		$categoryContentHidden = $(".categoryContent:hidden");
		
		// on state of the buttons
		$(this).parent().find(".on").removeClass("on").end().end().addClass("on");

		if(onMyVideosPage) {
			// if on my videos page use thse
			$categoryContentVisible = $(".categoryContent");
			$categoryContentVisible.find(".productBox").css({width:357,height:93,"margin-right":10,"float":"left"});
			$categoryContentVisible.find(".productTitle").css({height:29,width:148});
			if ($.browser.webkit) {
				$categoryContentVisible.find(".productDescription").css({height:30,width:150});
			} else {
				$categoryContentVisible.find(".productDescription").css({height:32,width:150});
			}
			$categoryContentVisible.find(".productImage").css({width:160,height:93}).css("margin-right","");
			$categoryContentVisible.find(".productImage img").css({width:160,height:93});
			$categoryContentVisible.find(".buyButton").animate({"margin-top":0},speed).css("float","left");
			$categoryContentVisible.find(".productContent").css("float","left");
			$categoryContentVisible.find(".projectWrapper").css("margin-top",19);
		} else {

			// animate the visible ones
			$categoryContentVisible.find(".productBox").animate({width:201,height:235,"margin-right":10},speed).css("float","left");
			$categoryContentVisible.find(".productTitle").animate({height:29},speed);
			$categoryContentVisible.find(".productDescription").css({height:70});
			$categoryContentVisible.find(".productImage").animate({width:200,height:116},speed);
			$categoryContentVisible.find(".productImage img").animate({width:200,height:116},speed);
			$categoryContentVisible.find(".buyButton").animate({"margin-top":0},speed).css("float","left");
			$categoryContentVisible.find(".productContent").css("float","left");
			
					
			// non animate, just change the hidden ones
			$categoryContentHidden.find(".productBox").css({width:200,height:235,"margin-right":10,"float":"left"});
			$categoryContentHidden.find(".productTitle").css("height",29);
			$categoryContentHidden.find(".productDescription").css("height",70);
			$categoryContentHidden.find(".productImage").css({width:200,height:116}).css("margin-right","");
			$categoryContentHidden.find(".productImage img").css({width:200,height:116});
			$categoryContentHidden.find(".buyButton").css({"margin-top":0,"float":"left"});
			$categoryContentHidden.find(".productContent").css("float","left");
			
		}
	});
	
	$("#listButton").click(function() {
		
		view = "list";
		
		$categoryContentVisible = $(".categoryContent:visible");
		$categoryContentHidden = $(".categoryContent:hidden");
		
		// on states of the buttons
		$(this).parent().find(".on").removeClass("on").end().end().addClass("on");
		
		// animate into a list
		if($categoryContentVisible.length < 4) {
			$categoryContentVisible.find(".productBox").animate({width:"100%",height:58,"margin-right":""},speed).css("float","");
			$categoryContentVisible.find(".productTitle").animate({height:14},speed);
			$categoryContentVisible.find(".productDescription").animate({height:29},speed);
			$categoryContentVisible.find(".productImage").animate({width:100,height:58},speed).css("margin-right",10);
			$categoryContentVisible.find(".productImage img").animate({width:100,height:58},speed);
			$categoryContentVisible.find(".buyButton").animate({"margin-top":2},speed).css("float","right");
			$categoryContentVisible.find(".productContent").css("float","");
		} else $categoryContentHidden = $(".categoryContent");
		
		// just switch the hidden ones
		$categoryContentHidden.find(".productBox").css({width:"100%",height:58,"margin-right":"","float":""});
		$categoryContentHidden.find(".productTitle").css({height:14,width:"auto"});
		$categoryContentHidden.find(".productDescription").css({height:29,width:"auto"});
		$categoryContentHidden.find(".productImage").css({width:100,height:58});
		$categoryContentHidden.find(".productImage img").css({width:100,height:58});
		$categoryContentHidden.find(".buyButton").css({"margin-top":2,"float":"right"});
		$categoryContentHidden.find(".productContent").css("float","");
		$categoryContentHidden.find(".projectWrapper").css("margin-top",9);

	});
	
	// animation variables
	var speed = 1000;
	
	// start in thumbnail mode
	$("#thumbnailButton").click();
	

	
	// open the first guy
	$(".categoryBar:first").click();
	$(".categoryBar").eq(1).click();
	
	// if there are any products in the cart show the button
	if($(".checkedProduct").length > 0) {
		refreshCart();
		
	}
	
	/*
	$(".productBox").popOut({
		height : 300,
		useElement: $("#poppedOut"),
		speed : 200,
		border : "1px solid #333",
		selectors : [
			{
				".productDescription": {
					height:150
				}
			},{
				".productLink" : {
					"display":"block",
					"margin-top":-40,
					"margin-bottom":10
				}
			}
		]
	});
	*/
	
	$("#homeBtn").click();
	
});




