jQuery.fn.exists = function(){return jQuery(this).length>0;}
var isiPad = (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i)) != null;
var homeSection = "videos";

/*
 *    JSON FEED PARSING, INSERTION AND PAGINATION
 */
 
 $(document).ready(function(){
	 /* SHOULD BE: http://www.telltalegames.com/getnews?tagid=66&limit=30&length=200 <<---------- CHANGE 'SAMPLE-JSON.JSON' TO THIS URL FOR PRODUCTION!!! ***/
	 
	$.getJSON('http://www.telltalegames.com/getnews?callback=?&tagid=66&limit=30&length=200', function(data) { 
	  var html = "";
	  var css_class;
	  $.each(data, function(key, val) {
		 if ( ((key+1) % 3) == 0 ){
		   css_class = "puzzle-news-item last";
		 }else{
		   css_class = "puzzle-news-item";
		 }
		 html += '<div class="'+ css_class +'">';
    	 html += '<p class="puzzle-news-date">'+ val.date +'</p>'
         html += '<h2><a href="'+ val.url +'" class=\"external\">'+ val.title +'</a>"</h2>';
         html += '<p>'+val.content+'</p>';
         html += '</div>'
	  });
	  
	  //insert the content 
		 $(html).prependTo($('#puzzle-news-list'));
		 
		 //and, paginate
			$('#puzzle-news-list').jPaginate({
				items: 3
			});
	}); 
	 
 })

/*
 *    HOVER EFFECTS FOR THE NAV HANDLED HERE FOR TOUCH INTERFACES CONSIDERATION
 */
 
function initNavHoverEffects(){
 if (isiPad){
	 $('#puzzle-nav-home a:not(.selected)').live('touchend', function(){
		$(this).removeClass('hover');
	 }) 	
	 $('#puzzle-nav-about a:not(.selected)').live('touchend', function(){
		$(this).removeClass('hover');
	 })
	 
	 $('#puzzle-nav-episodes a:not(.selected)').click(function(){
		 showTooltip('#hector-tooltip-episodes')
	 })
 }else{
	$('li#puzzle-nav-home a:not(.selected)').hover(function(){
		 $(this).css('background-position', '0 -38px')
		 showNavGnome();
 	  },
	  function(){
		 $(this).css('background-position', '0 -76px')
		 hideNavGnome();
 	});
	$('#puzzle-nav-about a:not(.selected)').hover(function(){
		 $(this).css('background-position', '0 -38px')
		 showNavGnome();
 	  },
	  function(){
		 $(this).css('background-position', '0 -76px')
		 hideNavGnome();
 	});
	$('#puzzle-nav-community a:not(.selected)').hover(function(){
		 $(this).css('background-position', '0 -38px')
		 showNavGnome();
 	  },
	  function(){
		 $(this).css('background-position', '0 -76px')
		 hideNavGnome();
 	});
 }
}


/*
 *    SCREENSHOTS WIDGET
 */

//initialize fancybox needed for widget
function initFB(){
	$("a.advance-link").fancybox({
		'titleShow' : false,
		'showNavArrows' : false
	});
}

//init screenshots
function initScreenshots(){
	//thumbnails for screenshot player
	// Initially set opacity on thumbs and add
	// additional styling for hover effect on thumbs
	var onMouseOutOpacity = 0.67;
	$('#thumbs ul.thumbs li').opacityrollover({
		mouseOutOpacity:   onMouseOutOpacity,
		mouseOverOpacity:  1.0,
		fadeSpeed:         'fast',
		exemptionSelector: '.selected'
	});
	
	// Initialize Advanced Galleriffic Gallery
	var gallery = $('#thumbs').galleriffic({
		delay:                     2500,
		numThumbs:                 5,
		preloadAhead:              10,
		enableTopPager:            true,
		enableBottomPager:         false,
		maxPagesToShow:            7,
		imageContainerSel:         '#slideshow',
		controlsContainerSel:      '#controls',
		captionContainerSel:       '',
		loadingContainerSel:       '#loading',
		renderSSControls:          false,
		renderNavControls:         true,
		playLinkText:              '',
		pauseLinkText:             'Pause Slideshow',
		prevLinkText:              '<img src="/images/puzzleagent2/puzzle-left-arrow.png">',
		nextLinkText:              '<img src="/images/puzzleagent2/puzzle-right-arrow.png">',
		nextPageLinkText:          '<img src="/images/puzzleagent2/puzzle-right-arrow-small.png">',
		prevPageLinkText:          '<img src="/images/puzzleagent2/puzzle-left-arrow-small.png">',
		enableHistory:             false,
		autoStart:                 false,
		syncTransitions:           true,
		defaultTransitionDuration: 900,
		onSlideChange:             function(prevIndex, nextIndex) {
			// 'this' refers to the gallery, which is an extension of $('#thumbs')
			this.find('ul.thumbs').children()
				.eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
				.eq(nextIndex).fadeTo('fast', 1.0);
		},
		onPageTransitionOut:function(callback) {
			this.fadeTo('fast', 0.0, callback);
		},
		onPageTransitionIn:function() {
			this.fadeTo('fast', 1.0);
		}
	});
	
	//initialize fancybox
    initFB();
}


/*
 *   AJAX CONTENT SWAPPING
 */

function loadpage(rel){
	$.ajax({
		type: "GET",
		url: "/include/js/puzzleagent2/ajax/"+ rel + ".html",
		data: ({
			page: rel
		}),
		success: function(msg){
			$('#puzzle-player-container').html(msg);
			if (rel=="screenshots"){
				$('#puzzle-player-container').removeClass("overflow");
				initScreenshots();
				if(!isiPad){ initSounds(); }
			}
			if (rel=="video"){
				$('#puzzle-player-container').addClass("overflow");
				if(!isiPad){ initSounds(); }
				if(isiPad){
					$('#normal-video').hide();
					$('#mobile-video').show();	
				}
			}
		}
	});
}



var swapSection="home";
function transitionPage(section){	
    if(!isiPad){
    	playTransitionSounds()
    }
	swapSection = section;
	if(!isiPad){
		initPositionsForGnome();
		bringOutTheGnome();
	}else{
		swapContent(); //for the IOS people
	}
}


/*
 *    SOUND SETUP PLAYS ON NON-IPAD SYSTEMS
 */
var flash;
function getMovie(movieName){
  if(document.embeds[movieName])
	return document.embeds[movieName];
  if(window.document[movieName])
	return window.document[movieName];
  if(window[movieName])
	return window[movieName];
  if(document[movieName])
	return document[movieName];
  return null;
}

var waitInterval;
var hotelMusicPlaying = false;
function initSounds(){
	if(!(getMovie("musicSwf") == null) && !isiPad){
		clearInterval(waitInterval);
		flash = getMovie('musicSwf');
		if (swapSection == "about"){
			clearInterval(whisperInterval);
			flash.PlayHotelExteriorNight();
			hotelMusicPlaying =true;
		}else{
			if(hotelMusicPlaying) flash.StopHotelExteriorNight();
			if (homeSection == "screenshots"){
				//console.log("starting whispers cuz we're on screenshots");	
				initWhispers();
			}else{
				clearInterval(whisperInterval);
				//console.log("we're not starting whispers cuz video may be playing");	
			}
		}
	}else{
		waitInterval=setInterval(initSounds, 1000);	
	}
};
var whisperInterval;
function initWhispers(){
	var random = (Math.ceil(Math.random()*40) *1000) + 8000; //min 8 seconds here
	whisperInterval = setInterval(playWhisper, random);
	//console.log("whisper scheduled for "+random);
	function playWhisper(){
	  clearInterval(whisperInterval);
	  flash.PlayGnomeWhisper();
	  initWhispers();
	}
}
function playTransitionSounds(){
	if(!isiPad){ flash.PlayWhisper(); }
};
function muteSounds(){
	flash.DoMute();
    clearInterval(whisperInterval);
}

function unMuteSounds(){
	 flash.DoUnmute();
	 initSounds();
}


/*
 *    GNOME ANIMATIONS
 */
$(window).resize(function() {
  if(!isiPad){
  	initPositionsForGnome()
  }
})

var initialOffset;
var terminalOffset;
var dtt;//gnome distance to travel
var mdtt; //media player distance to travel
var playerInitialOffset;
var stepSegment;
var currentFrame;
var gnomeDelay;
var playerWidth;
var isTransitionGnomeAnimating = false;
function initPositionsForGnome(){
	// first, let's find the distance to travel (dtt) and media player distance to travel (mdtt)
	  initialOffset = $('#puzzle-transition-gnome').offset();
	  terminalOffset =  $('#puzzle-container').offset();
	  dtt = terminalOffset.left - initialOffset.left + 5; //adjust 5px per whitni
	  playerInitialOffset =  $('#puzzle-media-player').offset();
	  playerWidth =  $('#puzzle-media-player').width();
	  mdtt = playerInitialOffset.left + playerWidth; //media player distance to travel
	  gnomeDirection = "forward";
	  
	// now, let's break that distance into 6 segments, 
	// as there are 6 frames in the animation prior to the gnome grabbing the div
	  stepSegment = "+=" + Math.ceil(dtt/6) + "px";
	// we also count the return step segment, which is 3 steps and a further distance
	  stepSegmentBack = "-=" + Math.ceil(mdtt/12) + "px";
	  
	//we'll start at the first frame of the animation and reset css
$('#puzzle-transition-gnome div').removeClass('f'+currentFrame);
currentFrame = 1;
$('#puzzle-transition-gnome div').addClass('f1')
}



function bringOutTheGnome(){ 
      isTransitionGnomeAnimating = true;
	  var currentGnomePosition = $('#puzzle-transition-gnome').offset();
	  if(currentGnomePosition.left <= terminalOffset.left){
		 takeAGnomeStep(); 
	  }else{
		//now reverse direction
		gnomeDirection = "backward";
		gnomeDelay = setInterval(backOutTheGnome, 500);
	  }
}

function backOutTheGnome(){
	clearInterval(gnomeDelay);
	var currentGnomePosition = $('#puzzle-transition-gnome').offset();
	var currentPlayerPosition = $('#puzzle-media-player').offset();
	  if(currentPlayerPosition.left >= (-mdtt) ){
		 takeAGnomeStepBack(); 
	  }else{
		//now we can swap the content after we wait 1/2 second...
		swapContent(); 
	  }
}

function takeAGnomeStep(){
	$('#puzzle-transition-gnome').animate({ //move it!
	  left: stepSegment
	}, {
	  duration: 110,
	  complete: function() {
		 incrementGnomeStyle();
	  }
	})
}

function takeAGnomeStepBack(){
	$('#puzzle-media-player').animate({ //move it!
	  left: stepSegmentBack
	}, {
		duration:80
	});
	$('#puzzle-transition-gnome').animate({ //move it!
	  left: stepSegmentBack
	}, {
	  duration: 80,
	  complete: function() {
		 incrementGnomeStyle();
	  }
	})
}


function incrementGnomeStyle(){
	 var currentStyle = "f"+currentFrame;
	 var nextStyle = "f"+(currentFrame+1);
	 $('#puzzle-transition-gnome div').removeClass(currentStyle);
	 $('#puzzle-transition-gnome div').addClass(nextStyle);
	 currentFrame++;
	 if(gnomeDirection == "forward"){
		 bringOutTheGnome();
	 }else{
		 backOutTheGnome();
	 }
}

function swapContent(){
	showNewSection();
	function showNewSection(){
		if (swapSection == "about"){
			$('#puzzle-about-container').show();
			$('#puzzle-media-player ul').hide(); //hide nav
			$('#puzzle-player-container').html(''); //unload html
			$('#puzzle-player-container').hide(); //hide div
			if(!isiPad){
				initSounds();
			}
		}else{//going back home
			$('#puzzle-about-container').hide(); //hide div
			$('#puzzle-media-player ul').show(); //show nav
			$('#puzzle-player-container').show(); //show div
			loadpage("video");
			homeSection = "video";
			$("#puzzle-media-nav-videos").addClass("selected");
			$("#puzzle-media-nav-screenshots").removeClass("selected");
			if(!isiPad){
				initSounds();
			}
		}
		if(!isiPad){
			var currentPlayerPosition = $('#puzzle-media-player').offset();
			$('#puzzle-media-player').animate({ left: "+="+ (playerInitialOffset.left + (- currentPlayerPosition.left)) +"px" }, { duration:30 });
		}
		resetNavGnome();
		isTransitionGnomeAnimating = false;
	}
}


 var navGnomeInterval;
 var isNavGnomeAnimating = false;
 function showNavGnome(){
	 if (!isNavGnomeAnimating){
		$('#puzzle-nav-gnome').show();
	 	isNavGnomeAnimating = true;
	 	$('#puzzle-nav-gnome').animate( { left: "35px", top:"39px" }, { duration:500 } );
	 }
 }
 function hideNavGnome(){
	 if (isNavGnomeAnimating){
		 $('#puzzle-nav-gnome').animate( { left: "120px", top:"120px" }, { duration:300, complete:function(){ resetNavGnome() } } );
	 }
	
 }
function resetNavGnome(){
	 $('#puzzle-nav-gnome').hide();
	isNavGnomeAnimating = false;
	gnomeDirection = "forward";
}


$(document).ready(function(){
 //default to home for nav
 $('#puzzle-nav-home a').addClass("selected");
 
 initNavHoverEffects();
 
 //main nav and transitions
 $("#puzzle-nav-about a").click(function(){
	 if(! $(this).hasClass("selected") && !isTransitionGnomeAnimating){
		 hideNavGnome()
		 $(this).addClass("selected");
		 $("#puzzle-nav-home a").removeClass("selected");
		 transitionPage("about");
		 initNavHoverEffects();
	 }
 });
 $("#puzzle-nav-home a").click(function(){
	 if (! $(this).hasClass("selected") && !isTransitionGnomeAnimating){
		 hideNavGnome()
		 $(this).addClass("selected");
		 $("#puzzle-nav-about a").removeClass("selected");
		 transitionPage("home");
		 initNavHoverEffects();
	 }
 });
 	
 loadpage("video");
 
 // class for off-site links
  $('a.external').attr('target', '_blank'); 

 //embed sounds swf
 var attributes = {
   id:"musicSwf",
   name:"musicSwf"
 };
 var params = {
   wmode: "transparent",
   menu: "false", 
   allowScriptAccess: "always"
 };
 if(!isiPad){
	 swfobject.embedSWF("/images/puzzleagent2/puzzle-agent.swf", "paMusicSwf", "1", "1", "9.0.0",null, null, params, attributes);
 }else{
	$("#puzzle-music-controller").hide(); 
 }

 if(!isiPad){
    $('#puzzle-music-checkbox').click(function(){
		if($(this).hasClass('on')){
			 muteSounds();
			 $(this).removeClass('on');
			 $(this).addClass('off');
		}else{
			unMuteSounds();
			$(this).removeClass('off');
		    $(this).addClass('on');
		}
	 })
 }
	 
 if(!isiPad){ initSounds(); }
 
	//tabs
	$(function() {
		$("#puzzle-media-nav-videos").click(function(event){	
		    homeSection = "video";
			loadpage("video");
			$(this).addClass("selected");
			$("#puzzle-media-nav-screenshots").removeClass("selected");
			event.preventDefault();
		});
		$("#puzzle-media-nav-screenshots").click(function(event){
			homeSection = "screenshots";
			loadpage("screenshots");
			$(this).addClass("selected");
			$("#puzzle-media-nav-videos").removeClass("selected");
			event.preventDefault();
		});
	});
	
	$('#slideshow-prev').addClass('inactive');
	
	$('#slideshow-container').cycle({
		next: '#slideshow-next',
		prev: '#slideshow-prev',
		nowrap: 1,
		timeout: 0,
		onPrevNextEvent: function(isNext, zeroBasedSlideIndex, slideElement){
			if(zeroBasedSlideIndex > 0){
				$('#slideshow-prev').removeClass('inactive');
			} else {
				$('#slideshow-prev').addClass('inactive');
			}
			
			if(zeroBasedSlideIndex < 2){
				$('#slideshow-next').removeClass('inactive');
			} else {
				$('#slideshow-next').addClass('inactive');
			}
		}
	});
	$('#slideshow-container a.puzzle_fb').fancybox({
		'titleShow' : true,
		'titlePosition' : 'inside',
		'showNavArrows' : true
	});    
		
		
    //agent eyeball intervals
	var agentArrayCounter = 0;
	var agentArray = [1000, 10000, 4000]; 
	var agentEyesOnInterval = "";
	var agentEyesOffInterval = "";
	agentEyesOnInterval = setTimeout(showAgentEyes, agentArray[agentArrayCounter]) ;
	
	function showAgentEyes(){
		$('#puzzle-agent-eyes').show();
		agentEyesOffInterval = setTimeout(hideAgentEyes, 500) ;
		clearInterval(agentEyesOnInterval);
		agentArrayCounter = (agentArrayCounter < agentArray.length-1 ) ? agentArrayCounter+1 : 0;
		agentEyesInterval = setTimeout(showAgentEyes, agentArray[agentArrayCounter]) ;
		return false;
	}
	function hideAgentEyes(){
		$('#puzzle-agent-eyes').hide();
		clearInterval(agentEyesOffInterval);
		return false;
	}
	

});

