$(document).ready(function() {

// opens document ready function, edit above this line
// ----------------------------------------------------

	// login for NickArcade & NickJrArcade
	$("#userBox").keydown(function(e) {
		if(e.keyCode == 13) {
			$("#userBox a#login").click();
			return false;
		}
	});
	
	$("#userBox input#email").focus(function(){
		$(this).val("").css("color","#333")
	});


	// preload images by calling this function
	jQuery.preloadImages = function()
	{
	  for(var i = 0; i<arguments.length; i++)
	  {
		 jQuery("<img>").attr("src", arguments[i]);
	  }
	}


	// fixes FF/Mac scrollbar issue
	toggleScrollBar = function(id){
		$(id).toggleClass('openState'); 
		$(id).toggleClass('closedState'); 
	}
	
	slideUpElement = function(id){
		$(id).slideUp();
		toggleScrollBar(id);
	}	
	slideDownElement = function(id){
		$(id).slideDown();
		toggleScrollBar(id);
	}	

	// Button triggers the hidden content to slide into view
	
	slideToggleElement = function(btnElement,id,startText,finalText){
		$(id).slideToggle();
		toggleScrollBar(id);
		shouldOpen = $(id).css('height') == "1px";
		txtTarget = $(btnElement).find("span");
		changeBtnText(txtTarget,shouldOpen,startText,finalText);
	}	

	// called to change the text that appears in buttons
	changeBtnText = function(txtTarget,shouldOpen,startText,finalText){
		$(txtTarget).fadeOut("fast", function(){
			if (shouldOpen) { 
				$(txtTarget).removeClass('slideClosed'); 
				$(txtTarget).addClass('slideOpen'); 
				btnText = finalText;
			} else {
				$(txtTarget).removeClass('slideOpen'); 
				$(txtTarget).addClass('slideClosed'); 
				btnText = startText;
			}
			(txtTarget).text(btnText);
			(txtTarget).fadeIn("fast");
		});
	}	
	

	// Used only for the chat window now	
 	targetSlideToggle = function(id){
 		txtTarget = $("#chatBox").next(".revealAbove").find("span");
 		origText = (txtTarget).text();
		$(id).slideToggle(function(){
			changeBtnText(txtTarget,origText);
		}); 
 	}


	//Sets a counter for the max characters on textareas with the 'addCounter' class
	
	// set the max chars
	$("textarea.addCounter[maxLength]").each(function(){
		var max  = $(this).attr('maxLength');
		var html_counter = "<div class=\"note\"><span>0<\/span>/" + max +"<\/div>";
		$(this).after(html_counter);
		this.relatedElement = $('div.note span')[0];
	});
	
	// check the max chars
	$("textarea.addCounter[maxLength]").keyup(function(){
		var maxLength = $(this).attr('maxLength');
		var currentLength = this.value.length;
		if(currentLength >= maxLength) {
			this.relatedElement.className = 'toomuch';
			this.value = this.value.substring(0, maxLength);
			} else {
			this.relatedElement.className = '';
			}
		this.relatedElement.firstChild.nodeValue = currentLength;
	});

	//used on the About Me edit page to see the second list of questions

	$("#forwardBtn").click(function() {
		if ( $("#step1").is(':visible') ) {
			$("#step1, #step1Txt").fadeOut("fast",function() {
				$("#step2, #step2Txt").fadeIn("fast");
			});
			$("#forwardBtn").addClass("disabled");
			$("#backBtn").removeClass("disabled");
		};
	});
	$("#backBtn").click(function() {
		if ( $("#step2").is(':visible') ) {
			$("#step2, #step2Txt").fadeOut("fast",function() {
				$("#step1, #step1Txt").fadeIn("fast");
			});
			$("#backBtn").addClass("disabled");
			$("#forwardBtn").removeClass("disabled");
		};
	});


	//Provides table zebra-ing, no need for alt rows
	//add 'zebra' class to table and, to show sorting, 'sort-N' where N is the sorted column

	$(".zebra").each(function(i){
	
		$(this).find('tr:even,div.row:even').addClass('zebraRowEven');
		$(this).find('tr:odd,div.row:odd').addClass('zebraRowOdd');

// Need to figure how to test if this second class contains 'sort'

		var el = $(this).get(0);
		var cssClasses = el.className.split(' '); 
		
		if ( cssClasses[1] != null && (cssClasses[1].match("sort")) ) {
			var str=cssClasses[1];
			var str=parseInt(str.replace('sort-', ""));
			$(this).find('tr:even').find('td' + ':nth-child('+str+')').addClass('activeColEven');
			$(this).find('tr:odd').find('td' + ':nth-child('+str+')').addClass('activeColOdd');
			$(this).find('th' + ':nth-child('+str+')').addClass('activeHead');
		}
	
	});


	// scroll window to an element ID
 	scrollToElement = function(target){
      var targetOffset = ($(target).offset().top) - 6;
		$('html, body').animate( {scrollTop: targetOffset}, {duration: 1000, easing: 'easeInOutExpo'} );			
	}

	// shows/hides registration wall, shows/hides element it's blocking
	// using visibility so it doesn't remove the target from the flow
 	showRegWall = function(target,regWall){
		var offset = $(target).offset();	
	  	$(target).css("visibility","hidden"); 
	   $(regWall).show();
	  	$(regWall).css({ top: offset.top, left: offset.left });
	}
 	hideRegWall = function(target,regWall){
	  	$(target).css("visibility","visible"); 
	   $(regWall).hide();
	}

	//triggers grayed out screen, adds message for user
	//accepts custom width if need be

	// preload images for the shadowBox
   $.preloadImages("/common/i/shadowBox/shtl.png","/common/i/shadowBox/shtm.png","/common/i/shadowBox/shtr.png","/common/i/shadowBox/shbl.png","/common/i/shadowBox/shbm.png","/common/i/shadowBox/shbr.png","/common/i/shadowBox/shml.png","/common/i/shadowBox/shmr.png");
	
    var messageTransfer = "";
    var messageTransferID;

    showMessage = function(id,customWidth,destURL,flashVar,keyword){

			var flashExists = false;
			
        var iframeLayer = "<iframe id=\"iframeLayer\" style=\"z-index:99;border:none;margin:0;padding:0;position:absolute;width:100%;height:100%;top:0;left:0;filter: alpha(opacity=0);\" src=\"javascript:''\"></iframe>";

			// flashVar contains path to video to load

			if (!flashVar) {
			  messageTransferID = id;
			  // get the message HTML that need to show
			  messageTransfer = $(id).html();
			  // empty that HTML so we don't end up with two IDs
			  $(id).empty();
        } else {
        		messageTransfer = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="320" height="282" id="flvplayer_f8" align="middle">';
				messageTransfer += '<param name="allowScriptAccess" value="sameDomain" />';
				messageTransfer += '<param name="allowFullScreen" value="false" />';
				messageTransfer += '<param name="movie" value="/common/flash/flvplayer_f8_v2.swf" />';
				messageTransfer += '<param name="quality" value="high" />';
				messageTransfer += '<param name="bgcolor" value="#ffffff" />';
				messageTransfer += '<param name="FlashVars" value="'+flashVar+'">';
				messageTransfer += '<embed src="/common/flash/flvplayer_f8_v2.swf" FlashVars="'+flashVar+'" quality="high" bgcolor="#ffffff" width="320" height="282" name="flvplayer_f8" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />';
				messageTransfer += '</object>';
				
				// if keyword is present, and it should be if a video is being displayed, add buttons
				if (keyword) {
					messageTransfer += '<div id="videoButtons" class="contain"><a class="clearLink moreInfo fltL" href="/nick/gameinfo.jsp?s='+keyword+'">More Info</a><a class="clearLink clickToBuy fltR" href="/nick/cart/addToCart.jsp?add='+keyword+'">Click to buy</a></div>';
				}
				
			  var flashExists = true;
        }



        btnClose =  '<a class="dimmerBtnClose clearLink" href="#" onclick="hideMessage('+flashExists+'); return false;">Close</a>';
        // insert the layers, the dimmer itself and the dimmer message with inserted text
        $('<div id="dimmer"></div>').appendTo(document.body);
        $('<div id="dimmerMessage"><table class="shadowBox"><tr><td class="shtl"></td><td class="shtm"></td><td class="shtr"></td></tr><tr><td class="shml"></td><td class="shmm">' + btnClose + messageTransfer + '</td><td class="shmr"></td></tr><tr><td class="shbl"></td><td class="shbm"></td><td class="shbr"></td></tr></table></div>').appendTo(document.body);

			var ieScrollTop = 0;

        if ( typeof document.body.style.maxHeight === "undefined" ) { // if IE 6
			ieScrollTop = document.documentElement.scrollTop;
			$(iframeLayer).appendTo(document.body); 
        }

         // Determine and set negative marginLeft to pull it back to center
        if (customWidth) {
            var messageWidth = customWidth;
            $("#dimmerMessage").width(customWidth);
        } else {
            var messageWidth = $("#dimmerMessage").width();
        }
        var messageLftMarg = ( messageWidth / 2 ) - messageWidth;
        $("#dimmerMessage").css("marginLeft",messageLftMarg);

         // Determine and set negative marginTop to pull it back to center
        var messageHeight = $("#dimmerMessage").height();
			var messageTopMarg = ( messageHeight / 2 ) - messageHeight + ieScrollTop;
        $("#dimmerMessage").css("marginTop",messageTopMarg);


        if ($.browser.opera) { // have to do this wonky show/hide for opera because the flash layer peeks through otherwise
            $("#flashItem").css("visibility","hidden");
            $("#dimmer, #dimmerMessage").show();
            $("#flashItem").css("visibility","visible");
        } else {
            // fade in, then fade in message, fixes issue with IE
            $("#dimmer").fadeIn("fast",function(){
                $("#dimmerMessage").fadeIn("fast",function(){
                    $("#dimmerMessage").find(".dimmerBtnA").attr("href",destURL);
                });
            });
        }

    }

    // hides the dimmer and the message
    hideMessage = function(flashExists){
        if ($.browser.msie) { // if IE
            $("#dimmer, #dimmerMessage").remove();
            $("#iframeLayer").remove();
        } else {
            $("#dimmer, #dimmerMessage").fadeOut("fast",function(){
                $("#dimmer, #dimmerMessage").remove();
            });
        }
        if (flashExists == false) {
        		$(messageTransferID).html(messageTransfer);
    		}
    }


	// used to with truncated text boxes
	 $(".showMore").click(function(){
		$(this).parent(".truncated").next(".untruncated").show();
		$(this).parent(".truncated").hide();
		return false;
	 })
	 $(".showLess").click(function(){
		$(this).parent(".untruncated").prev(".truncated").show();
		$(this).parent(".untruncated").hide();
		return false;
	 })

	// hover over Wish For It buttons
	$("#selectWantMessage").change(function () {
	 	targetValue = $("#selectWantMessage option:selected").attr("value");
	 	targetValue = "#"+targetValue;
	 	$(".wantMessage").hide();
	 	$(targetValue).show();
        $("#chosenSubject").attr("value", $("#selectWantMessage option:selected").html());
        $("#chosenBody").attr("value", $(targetValue).html());
     });

	//On target registration page, show state dropdown if country selected is United States
	$("#targetRedeemForm #country:input").change(function(){
		var countryValue = $(this).val();
		if (countryValue == "us") {
			$("#dropdownState").show();
		} else {
			$("#dropdownState").hide();
		}
	})

	$("#guestPassForm #country:input").change(function(){
		var countryValue = $(this).val();
		if (countryValue == "us") {
			$("#dropdownState").show();
		} else {
			$("#dropdownState").hide();
		}
	})

	


// -----------------------------------------------------
// closes document ready function, edit above this line

});
