$(document).ready(function() {

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

	// 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("/a/images/download/shadowBox/shtl.png","/a/images/download/shadowBox/shtm.png","/a/images/download/shadowBox/shtr.png","/a/images/download/shadowBox/shbl.png","/a/images/download/shadowBox/shbm.png","/a/images/download/shadowBox/shbr.png","/a/images/download/shadowBox/shml.png","/a/images/download/shadowBox/shmr.png");
	
	var messageTransfer = "";
	var messageTransferID;
	 
	showMessage = function(id,customWidth,destURL){

					
		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>";
		
		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();
		
		btnClose =  '<a class="dimmerBtnClose clearLink" href="#" onclick="hideMessage(); 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(){
		if ($.browser.msie) { // if IE
			$("#dimmer, #dimmerMessage").remove();
			$("#iframeLayer").remove();
		} else {
			$("#dimmer, #dimmerMessage").fadeOut("fast",function(){
				$("#dimmer, #dimmerMessage").remove();
			}); 
		}
		$(messageTransferID).html(messageTransfer);
	}





	//used to place voki in dimmerMessage
	vokiFrameAddress = function(vokiAddress){
		$("#vokiIframe").attr("src",vokiAddress);
	}


	// 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;
	 })


		// sets initial element shown as 0
		elShown = 0;

		// called if text of prev/next button need to customized
		getCustomBtnText = function(elShown,elSize,trigger){
		
			// set targets relative to the trigger
			target = $(trigger).parents(".pod:first").find(".contentSwapWrap:first").find(".contentSwap h3");
			prevBtn = $(trigger).parents(".pod:first").find(".prevBtn");
			nextBtn = $(trigger).parents(".pod:first").find(".nextBtn");
	
			if ( elShown < elSize && elShown > 0) {
				nextBtnHtml = $(target).eq(elShown+1).html();
				prevBtnHtml = $(target).eq(elShown-1).html();
			} else if ( elShown == elSize) {
				nextBtnHtml = $(target).eq(0).html();
				prevBtnHtml = $(target).eq(elSize-1).html();
			// when elShown == 0
			} else {
				nextBtnHtml = $(target).eq(1).html();
				prevBtnHtml = $(target).eq(elSize).html();
			}
			// assign final HTML value to button text				
			$(nextBtn).html(nextBtnHtml);
			$(prevBtn).html(prevBtnHtml);
			return false;

		}
	
	
		$(".nextBtn, .prevBtn").click(function(){
			trigger = $(this);
			showNext = false;
			if ( $(trigger).hasClass("nextBtn") ) { showNext = true; }
			target = $(trigger).parents(".pod:first").find(".contentSwapWrap:first").find(".contentSwap");
			// subtract one to correspond with the array starting at 0
			elSize = $(target).size() - 1;
			$(target).hide();

			if ( (showNext == true) && ( elShown < elSize) ) {
				elShown = elShown + 1;
				$(target).eq(elShown).fadeIn();
			} else if (showNext == true) { 
				$(target).eq(0).fadeIn();
				elShown = 0;
			} else if ( (showNext == false) && ( elShown > 0) ) {
				elShown = elShown - 1;
				$(target).eq(elShown).fadeIn();
			} else { 
				$(target).eq(elSize).fadeIn();
				elShown = elSize;
			}
			
			// tests to see if customNavBtns is present
			if($(trigger).parents(".pod:first").hasClass("customNavBtns")) {
				getCustomBtnText(elShown,elSize,trigger);
			}
			return false;
			
		});
	
	var tabClick = false;

	// used for web searches from the header
	searchTabSwitch = function(id) {
		// adds an active class to the active tab
		$("#searchTabs a").removeClass("active");
		$(id).addClass("active"); 
		$('#search_text').focus();
		tabClick = true;
	}
	
	
    $("#search_text").keypress(function (e) {
      if (e.which == 13 ) {
          	doSearch();    
         }
    });	
	
	// determine which tab is active and pass the search function required
	doSearch = function(){
		var queryString = $("#search_text").attr("value");
		if ( $("#liveSearch").attr("class") == "active" ) {
			document.location.href = "http://search.live.com/results.aspx?q="+queryString+"&mkt=en-us&FORM=VCM019";
		} else {
			document.location.href = "/search.jsp?search_text="+queryString;
		}
	}
	
	
	// tag picker on game landing pages
	// uses hidden checkmarks
	$(".tagPick3 label").click(function(){
		var target = $(this);

		var n = $(".tagPick3 label.active").length; // get number of active tags
		
 		if ( $(target).hasClass("active") ) {
 			$(target).removeClass("active");
 			$(".tagPick3 span").css("color","#878787");
 		} else if (n < 3) {
 			$(target).addClass("active");
 		} else {
 			$(".tagPick3 span").css("color","red");
 			return false; // to prevent checkmark
 		}
		
	});



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

	$('a[href=#top-page]').click(function(){
        $('html, body').animate({scrollTop:0}, 'slow');
        return false;
    });

});
