$(document).ready(function() {	   						   
	/* MAIN NAV */
		$('#menu > li ul').hide().css({'visibility':'visible'});	
		$('#menu > li').bind("mouseover", function() {
			$(this).children("a").addClass("hover");
			$(this).find("ul").show();
		});
		$('#menu > li').bind("mouseout", function() {
			$(this).children("a").removeClass("hover");
			$(this).find("ul").hide();
		});
	
	/* CAROUSEL */
		if($("#main-photo-slider").length) {
			var theInt = null;
			var $crosslink, $navthumb;
			var curclicked = 0;
			
			theInterval = function(cur){
				clearInterval(theInt);			
				if( typeof cur != 'undefined' )
					curclicked = cur;
					
				$crosslink.removeClass("active-thumb");
				$navthumb.eq(curclicked).parent().addClass("active-thumb");
				$(".stripNav ul li a").eq(curclicked).trigger('click');			
				theInt = setInterval(function(){
					$crosslink.removeClass("active-thumb");
					$navthumb.eq(curclicked).parent().addClass("active-thumb");
					$(".stripNav ul li a").eq(curclicked).trigger('click');
					curclicked++;
					if( 5 == curclicked )
						curclicked = 0;				
				}, 7000);
			};
			
			$(function(){			
				$("#main-photo-slider").codaSlider();			
				$navthumb = $(".nav-thumb");
				$crosslink = $(".cross-link");			
				$navthumb.click(function() {
					var $this = $(this);
					theInterval($this.parent().attr('href').slice(1) - 1);
					return false;
				});			
				theInterval();
			});		
			$(".loading-page").removeClass("loading-page");
		}

	/* MISC */
		if($("#newcontent").length && $("#newtrailers").length && $("#newcontent").height() != $("#newtrailers").height()) {
			if($("#newcontent").height() > $("#newtrailers").height()){$("#newtrailers").css({'height':$("#newcontent").height()+'px'});}
			if($("#newtrailers").height() > $("#newcontent").height()){$("#newcontent").css({'height':$("#newtrailers").height()+'px'});}
		}				

	/* CHANGE LINKS */
		$("a[href='/profile/login/']").attr('href', '/profile/login/popup/?iframe');
		$("a[href='/profile/settings/login-information/email/']").attr('href', '/profile/settings/login-information/popup/email/?iframe');
		$("a[href='/profile/settings/login-information/password/']").attr('href', '/profile/settings/login-information/popup/password/?iframe');
		$("a[href='/profile/settings/login-information/reminder/']").attr('href', '/profile/settings/login-information/popup/reminder/?iframe');
		$("a[href='/help/glossary/#profiletypes']").attr('href', '/help/glossary/popup/profile-types/?iframe');

	/* FANCY */
		$("#download, #freedownload").fancybox({'overlayShow': true, 'overlayOpacity': 0.9, 'overlayColor': '#000', 'zoomSpeedIn': 0, 'zoomSpeedOut': 0, 'frameWidth': 360, 'frameHeight': 355, 'padding': 0});
		$("a[href='/profile/login/popup/?iframe']").fancybox({'overlayShow': true, 'overlayOpacity': 0.9, 'overlayColor': '#000', 'zoomSpeedIn': 0, 'zoomSpeedOut': 0, 'frameWidth': 360, 'frameHeight': 245, 'padding': 0});
		$("a[id^='readme']").fancybox({'overlayShow': true, 'overlayOpacity': 0.9, 'overlayColor': '#000', 'zoomSpeedIn': 0, 'zoomSpeedOut': 0, 'frameWidth': 400, 'frameHeight': 300, 'padding': 0});
		$("a[href^='/help/glossary/popup/']").fancybox({'overlayShow': true, 'overlayOpacity': 0.9, 'overlayColor': '#000', 'zoomSpeedIn': 0, 'zoomSpeedOut': 0, 'frameWidth': 360, 'frameHeight': 340, 'padding': 0});
		$("a[href^='/profile/settings/login-information/']").fancybox({'overlayShow': true, 'overlayOpacity': 0.9, 'overlayColor': '#000', 'zoomSpeedIn': 0, 'zoomSpeedOut': 0, 'frameWidth': 360, 'frameHeight': 225, 'padding': 0});
		$("div#upgrade a").fancybox({'overlayShow': true, 'overlayOpacity': 0.9, 'overlayColor': '#000', 'zoomSpeedIn': 0, 'zoomSpeedOut': 0, 'frameWidth': 585, 'frameHeight': 455, 'padding': 0});
		$("span#advancedChange a").fancybox({'overlayShow': true, 'overlayOpacity': 0.9, 'overlayColor': '#000', 'zoomSpeedIn': 0, 'zoomSpeedOut': 0, 'frameWidth': 360, 'frameHeight': 335, 'padding': 0});
	
	/* AUTOCOMPLETE */
		$("#q").autocomplete("/system/ajax/ac_game-name.php", {
			width: 269,
			max: 25,
			highlight: false,
			scroll: true,
			scrollHeight: 300,
			formatItem: function(data, i, n, value) {
				var imgpath = value.split("*~*")[0].split("*,*")[1];
				var newimgpath = imgpath.substring(0, imgpath.lastIndexOf("/"))+"/gen"+imgpath.substring(imgpath.lastIndexOf("/"), imgpath.lastIndexOf("."))+"_thumb_49x70"+imgpath.substring(imgpath.lastIndexOf("."));
				return "<a href='"+value.split("*~*")[0].split("*,*")[2]+"' title='"+value.split("*~*")[0].split("*,*")[0]+"'><img src='"+newimgpath+"' height='70' width='49'/><span class='title'>"+value.split("*~*")[0].split("*,*")[0]+"</span><span class='date'>Release Date: <strong>"+value.split("*~*")[0].split("*,*")[3]+"</strong></span></a>";
			},
			formatResult: function(data, value) {
				return value.split("*~*")[0];
			}
		});
		
		$("#q").bind("keydown", function(e) {
			if (e.keyCode == 13) {
				return false;
			}
		});
		
	/* SEARCH DEFAULT VALUE */
		$("#q").click(function() {
			if($(this).val() == "Search") {
				$(this).removeClass("hint");
				$(this).val("");
			}
		});
	
		$("#q").blur(function() {
			if($(this).val() == "" || $(this).val() == "Search") {
				$(this).val("Search");
				$(this).addClass("hint");
			}
		});
		
	/* HIDE ASIDE WHILE MENU OR AUTOCOMPLETE OPEN */
		var int = setInterval(function() {
			if($(".ac_results").is(":visible") || $("#menu > li ul").is(":visible")) {
				toggleAside("hide");
			} else {
				toggleAside("show");
			}
		}, 100);
		
	/* GET GAMESHADOW PAGE */
	if($("#getform").length) {
		$("#displayname-label, #email-label, #password-label, #legal-label").tipsy({trigger: "manual", gravity: "e"});
		$("#newsletter-label").tipsy({trigger: "manual", gravity: "e", opacity: 1});
		
		var illegalUsername = /^[a-zA-Z0-9_]{0,20}$/;
		var illegalEmail = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
		var illegalPassword = /^.{3,99}$/;
		
		$("#submit").bind("click", function() {
											
			var app = false;
			if($("#app").is(":checked")) {
				app = true;
			}

			var username = testField($("#displayname"),illegalUsername);
			var email = testField($("#email"),illegalEmail);
			var password = testField($("#password"),illegalPassword);
			var legal = testCheck($("#legal"));
			
			if(username && email && password && legal) {				//alert("ALL REQUIRED FIELDS ARE FILLED IN");
								
				$("#form-submit").click();
				
			} else if($("#newsletter").is(":checked")) {				//alert("NEWSLETTER CHECKED: ARE ALL REQUIRED FIELDS ARE FILLED IN?");
			
				//THE CODE BELOW NEEDS TO BE INSIDE A IF TO CHECK FOR ALL FIELDS ARE BLANK
				
				if(!username && !email && !password && !legal) {
			
					$("#dialog").html("<p class='msg info'>If you would like the <a href='#'>Awesome GameShadow Newsletter</a> you will need to complete all fields.</p>");
					$("#dialog").dialog({
						modal: true,
						width: "334px",
						buttons: {
							ok: function() {
								$(this).dialog('close');
							},
							"I don't want the newsletter": function() {
								$("#newsletter").attr("checked", false);
								$(this).dialog("destroy");
								$("#form-submit").click();
							}
						}
					});
					$("#dialog").bind("dialogclose",function(event, ui){
						this.dialog("destroy");
						
						highlightField($("#displayname"),username);
						highlightField($("#email"),email);
						highlightField($("#password"),password);
						highlightCheck($("#legal"),legal);
						
						if(username && email && password && legal) {				
							$("#newsletter-label").tipsy("hide");
							$("#form-submit").click();
						} else {
							$("#newsletter-label").tipsy("show");
						}
					});
			
				} else {
					
					highlightField($("#displayname"),username);
					highlightField($("#email"),email);
					highlightField($("#password"),password);
					highlightCheck($("#legal"),legal);
					
					if(username && email && password && legal) {				
						$("#newsletter-label").tipsy("hide");
						$("#form-submit").click();
					} else {
						$("#newsletter-label").tipsy("show");
					}
					
				}
				
			} else if(username || email || password || legal) {			//alert("NEWSLETTER NOT CHECKED: ARE ANY REQUIRED FIELDS ARE FILLED IN?");

					highlightField($("#displayname"),username);
					highlightField($("#email"),email);
					highlightField($("#password"),password);
					highlightCheck($("#legal"),legal);	

			} else if(!app) {											//alert("NO REQUIRED FIELDS ARE FILLED IN OR DOWNLOADS CHECKED!");
				
				$("#dialog").html("<p class='msg info'>You didn't make a selection. If you would like to download the GameShadow App' please click the link below:<br/><a href='#'>Download GameShadow App'</a></p>");
				$("#dialog").dialog({
					modal: true,
					width: "334px",
					buttons: {
						ok: function() {
							$(this).dialog("close");
						}
					}
				});
				$("#dialog").bind("dialogclose",function(event, ui){
					this.dialog("destroy");
				});				
				
			} else {													//alert("NO REQUIRED FIELDS ARE FILLED IN BUT A DOWNLOAD IS CHECKED");
				
				$("#form-submit").click();
				
			}
		});
		
		function testField(field,illegal) {
			if(field.val() != "" && field.val().search(illegal) == 0) {
				return true;
			} else {
				return false;
			}
		}
		function testCheck(field) {
			if(field.is(":checked")) {
				return true;
			} else {
				return false;
			}
		}
		function highlightField(field,istrue) {
			if(istrue) {
				field.parents("label").removeClass("highlight").tipsy("hide");
			} else {
				field.parents("label").addClass("highlight").tipsy("show");
			}
		}
		function highlightCheck(field,istrue) {
			if(istrue) {
				field.parents("label").removeClass("highlight").tipsy("hide");
			} else {
				field.parents("label").addClass("highlight").tipsy("show");
			}
		}
	}
	
	if($(".get-gameshadow #get-gameshadow-actions").length) {
		$("#get-gameshadow-actions").dialog({
			modal: true,
			width: "334px",
			buttons: {
				ok: function() {
					$(this).dialog('close');
				}
			}
		});
		$("#get-gameshadow-actions").bind("dialogclose",function(event, ui){
			this.dialog("destroy");
		});
		if($("#download-app").length) {
			setTimeout("window.location='"+$("#download-app").attr("href")+"'",100);
		}
	}
	
	/* COMPETITION PAGE */
		if($(".comp-page").length) {
			$(".comp-page .answer").click(function(event) {
				event.preventDefault();
				$(".comp-page .answer").removeClass("selected");
				$(this).addClass("selected");
				$(".comp-page #answer").val($(this).attr("href"));
			});
		}
	
	/* DEALS PAGE */
		if($("#deals").length) {
			$("#deals").anythingSlider({
				easing: "easeInOutExpo",
				autoPlay: true,
				delay: 3000,
				startStopped: true,
				animationTime: 600,
				hashTags: false,
				buildNavigation: false
			});
		}
	
	/* QUIZ PAGE */
		if($("#quiz").length) {
			$("#quiz fieldset").fadeTo(0, 0.01).hide().addClass("stack");
			$("#quiz fieldset:first").fadeTo(0, 1).show();	
			$("#quiz fieldset:last label").click(function(event) { $("#quiz").submit(); });	
			$("#quiz label").click(function(event) {
				$(this).addClass("selected");
				$(this).parent().fadeTo(600, 0.01, function() {
					$(this).hide();
				});
				$(this).parent().next().show().fadeTo(600, 1);
			});	
		}
	
	/* VIDEO PLAYER */
		if($(".movieplayer").length) {
			
			/* CHROME DETECTION */
			$.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());
			
			/* SETUP PREROLLS */
			var preroll = "";
			//TO TURN ON PREROLLS COMMENT THE LINE ABOVE OUT, AND UNCOMMENT TO BELOW
			//var prerolls = [];
			//prerolls[0] = "http://gameshadow.vo.llnwd.net/o1/ltd/website/adverts/doublefusion/machete/machete.mp4";
			//prerolls[1] = "http://gameshadow.vo.llnwd.net/o1/ltd/website/adverts/doublefusion/machete/machete.mp4";
			//prerolls[2] = "http://gameshadow.vo.llnwd.net/o1/ltd/website/adverts/doublefusion/machete/sartana.mp4";
			//prerolls[3] = "http://gameshadow.vo.llnwd.net/o1/ltd/website/adverts/doublefusion/machete/senator.mp4";
			//prerolls[4] = "http://gameshadow.vo.llnwd.net/o1/ltd/website/adverts/doublefusion/machete/she.mp4";
			//var preroll = prerolls[Math.ceil(Math.random()*prerolls.length-1)];
			
			/* SETUP VARIABLES */
			var playerVersion = swfobject.getFlashPlayerVersion();
			var flashversion = playerVersion.major.toString();
			var title = $(".videometa .title").html();
			var movie = $(".videometa .path").html();
			var image = $(".videometa img.photo").attr("src");
			var image_alt = $(".videometa img.photo").attr("alt");
			var player = $(".videometa .player").html();
			var rating = $(".videometa .rating").html(); 
			var user_age = $(".videometa .rating").attr("rel");	
			var link_id = $(".videometa .link-id").html();
			var poster = "<a href='#' title='Play "+image_alt+"' class='play' onclick='javascript: _gaq.push([\"_trackEvent\", \"Trailer\", \"Play\", \""+title+"\"]);'><span class='overlay'>Play!</span><img src='"+image+"' alt='"+image_alt+"' width='640' height='360'/></a>";
			var age_gate = "<div class='age-gate'><h3>This Video has an Age Requirement!</h3><p>You need to be "+rating+" or over to view this video!</p><p class='agegate'><a href='#'>I Am Over "+rating+"</a></p></div>";
			var need_flash = "<div class='need-flash'><h3>Flash Player Required!</h3><p>This content requires the Flash Player. <a target='_blank' href='http://www.adobe.com/go/getflashplayer' onclick='javascript: _gaq.push([\"_trackEvent\", \"Exit\", \"Get Flash\", \""+title+"\"]);'>Download Flash Player</a></p></div>";
			
			$(".movieplayer.mp4 .videometa").remove();
			
			/* HTML 5 or MP4 */
			if($(".movieplayer.mp4").length) {
				if($.browser.webkit && !$.browser.chrome) {
					
					/* HTML 5 */
					
					$(".movieplayer.mp4 video").hide().before(poster);
					$(".movieplayer.mp4 a.play").click(function(event) {
						event.preventDefault();
						
						if(user_age < rating) {
							$(".movieplayer.mp4 a.play").after(age_gate).remove();
							$(".movieplayer.mp4 p.agegate a").click(function(event) {
								event.preventDefault();
								$(".movieplayer.mp4 div.age-gate").remove();
								$(".movieplayer.mp4 video").show();
								$.ajax({ url: "/system/ajax/set_session.php?session=user_age&value="+rating });
								$.ajax({ url: "/system/ajax/track_trailer.php?link_id="+link_id });
								return false;
							});
						} else {
							$(".movieplayer.mp4 a.play").remove();
							$(".movieplayer.mp4 video").show();
							$.ajax({ url: "/system/ajax/track_trailer.php?link_id="+link_id });
						}
						return false;
					});
				} else if(flashversion == 0) {
					$(".movieplayer.mp4").html(need_flash);
				} else {
					
					/* MP4 */
					
					$(".movieplayer.mp4").html(poster);
					$(".movieplayer.mp4 a.play").click(function(event) {
						event.preventDefault();
						if(user_age < rating) {			
							$(".movieplayer.mp4").html(age_gate);
							$(".movieplayer.mp4 p.agegate a").click(function(event) {
								event.preventDefault();
								addvideo();
								$.ajax({ url: "/system/ajax/set_session.php?session=user_age&value="+rating });												
								return false;
							});
						} else { addvideo(); }
						function addvideo() {
							$.ajax({ url: "/system/ajax/track_trailer.php?link_id="+link_id });				
							$(".movieplayer.mp4").html("").flash({
									src: player,
									width: 640,
									height: 400,
									allowFullScreen: true,
									flashvars: { MOVIELOC: movie, PRELOC: preroll }
								},{ version: 10 }
							);
						}
						return false;
					});
				}
			} else if($(".movieplayer.flv").length) {
				
				/* FLV */
				
				if(flashversion > 0) {
					$(".movieplayer.flv").html(poster);
					$(".movieplayer.flv a.play").click(function(event) {
						event.preventDefault();
						if(user_age < rating) {			
							$(".movieplayer.flv").html(age_gate);
							$(".movieplayer.flv p.agegate a").click(function(event) {
								event.preventDefault();
								addvideo();
								$.ajax({ url: "/system/ajax/set_session.php?session=user_age&value="+rating });					
								return false;
							});	
						} else { addvideo(); }
						function addvideo() {
							$.ajax({ url: "/system/ajax/track_trailer.php?link_id="+link_id });				
							$(".movieplayer.flv").html("").flash({
									src: player,
									width: 640,
									height: 400,
									allowFullScreen: true,
									flashvars: { MOVIELOC: movie, PRELOC: preroll }
								},{ version: 10 }
							);
						}
						return false;
					});
				} else if(flashversion == 0) {
					$(".movieplayer.flv").html(need_flash);
				}
			}
		}
		
	/* COMMENTS */
		if($("#comment").length) {
			
			/* COMMENT SCROLLER */
				if($("#comment:not(.static)").length) {
					$(window).scroll(function () {		
						var scrolled = $(window).scrollTop();			
						var form = $("#comment");
						var div = $("#comments .comments");
						var wrap = $("#commentWrap");	
						wrap.height(350);	
						var divoffset = div.offset();
						if((divoffset.top-scrolled) > 0) {
							form.css({'position':'relative','top':'0'});
						}
						if((divoffset.top-scrolled) < 0) {
							form.css({'position':'fixed','top':'10px'});
						}
					});
				}
				
			/* COMMENT VALIDATION */
				window.setTimeout("nobot()",15000);
			
				$("#sendscrawl").click(function(event) {
					event.preventDefault();
					if(!$("#terms").is(":checked")) {
						if($("#scrawlname").val() == "") {
							$("#formname").addClass("highlight");
							if($("#scrawlname").val() == "" || $("#scrawlname").val() == "Enter your comment here...") {
								$("#formcomment").addClass("highlight");
							}
							return false;
						} else if($("#scrawlname").val() == "" || $("#scrawlname").val() == "Enter your comment here...") {
							$("#formcomment").addClass("highlight");
							return false;
						} else {
							if(!isbot()) {
								$("form#comment").submit();
							} else {
								$("#comment > fieldset").before("<p class='msg'>Wow, that's fast typing for a human!<br/><a href='#' id='iamhuman' onclick='javascript: _gaq.push([\'_trackEvent\', \'BotTest\', \'Comments\', \'I Am Human\']);'>I Am Indeed Human!</a></p>");
								
								$("#iamhuman").click(function(event) {
									event.preventDefault();
									$("form#comment").submit();
								 });
							}
							return true;	
						}
					}
				});			
		}
	
});

/* DELAYED FUNCTIONS */
$(window).load(function() {
	// Do this after the HTML has loaded...
		
		/* ADD IFRAMES */
		$("#mpu").before("<iframe id='mpu' src='/static/iframes/site_mpu.htm' height='250' frameborder='0' scrolling='no' ><![CDATA[ ]]></iframe>").remove();
		$("#ad728").before("<iframe id='ad728' src='/static/iframes/site_728.php' width='728' height='90' frameborder='0' scrolling='no' ><![CDATA[ ]]></iframe>").remove();
		$("#facebookfans").before("<iframe class='facebookfans' src='/static/iframes/facebook_fans.htm' height='250' frameborder='0' scrolling='no' ><![CDATA[ ]]></iframe>").remove();
		
		/* FACEBOOK LIKE */
		if($(".fb_like").length) {
			$(".fb_like").each(function(index) {
				$(this).after("<iframe class='fb-like' src='http://www.facebook.com/plugins/like.php?href="+escape($(this).attr("rel"))+"&amp;show_faces=false&amp;width="+$(this).attr("width")+"&amp;layout="+$(this).attr("layout")+"&amp;action=like&amp;colorscheme=light&amp;height="+$(this).attr("height")+"' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:"+$(this).attr("width")+"px; height:"+$(this).attr("height")+"px;' allowTransparency='true'></iframe>").remove();
			});
		}
});

/* JS FUNCTIONS */

	/* TOGGLE ASIDE */
	function toggleAside(hideShow) {
		if($("body > aside").length || $("body > div.aside").length) {
			if(hideShow == "hide") {
				if(!$("body > div.aside.temp").length) {
					$("body > aside").hide().after("<div class='aside temp' style='background-color: #000;'><![CDATA[ ]]></div>");	
				}					
			} else {
				$("body > div.aside.temp").remove();
				$("body > aside").show();
			}
		}
	}
	
	/* BOT TEST */
	var bot = "yes";
	function nobot() {
		bot = "no";
	}
	function isbot() {
		if(bot == "no") {
			return false;
		} else {
			return true;	
		}
	}