$(document).ready(function(){
	exploreObj.init();
});

var exploreObj = {
	init:function(){
		this.hoverBoxes.init();
		this.pagination.init();
		this.callouts.init();
		this.filter.init();
		this.videos.init();
	},
	videos:{
		playQueue: [],
		itemOrders: [
				[1, 3, 11, 15, 9, 2, 12, 7, 18, 8, 6, 16, 4, 5],
				[13, 20, 28, 33, 25, 35, 19, 32, 30, 27, 23]
		],
		init: function(){
			this.playAll(1);
		},
		playAll: function(page){
			this.pauseAll();
			
			// clear the play queue
			this.playQueue.length = 0;
			
			// build the play queue based on the page
			for (var i = 0; i < this.itemOrders[page-1].length; i++) {
				this.playQueue.push("flash" + this.itemOrders[page-1][i]);
			}
			
			// start the first x many
			for (var i = 0; i < 6; i++) {
				this.playNextInQueue();
			}
		},
		playAllActive: function(){
			
			this.pauseAll();
			
			this.playQueue.length = 0;
			
			$("#gridfullwidth > ul > li.activeGridItem object").each(function(){
				exploreObj.videos.playQueue.push($(this).attr("id"));
			});
			
			// start the first x many
			for (var i = 0; i < 6; i++) {
				this.playNextInQueue();
			}
		},
		onVideoComplete: function(elementId){
			this.playQueue.push(elementId);
			this.playNextInQueue();
		},
		pauseAll: function(){
			
			// clear the play queue
			this.playQueue.length = 0;
			
			that = this;
			$("#gridfullwidth > ul > li object").each(function(){
				that.pause($(this).attr("id"));
			});
		},
		pause: function(elementId, tries){
			
			if (tries == undefined)
				tries = 0;
			
			try {
				document.getElementById(elementId).pauseFLV();
			}
			catch(e){
				// Flash not loaded yet, or doesn't exist
				if (tries < 10) {
					that = this;
					var interval = setTimeout(function(){
						that.pause(elementId, tries+1);
					}, 200);
				}
			}
		},
		playNextInQueue: function(){
			if (this.playQueue.length > 0) {
				this.play(this.playQueue.shift());
			}
		},
		play: function(elementId, tries){
			
			if (tries == undefined)
				tries = 0;

			try {
				document.getElementById(elementId).playFLV();
			} 
			catch (e) {
				// Flash not loaded yet, or doesn't exist
				//console.log(e)
				if (tries < 10) {
					that = this;
					var interval = setTimeout(function(){
						that.play(elementId, tries+1);
					}, 200);
				}
			}
			
		}
	},
	hoverBoxes:{
		init:function(){
			
			// make sure all items start with class that denotes active grid item:
			$("#gridfullwidth > ul > li").addClass("activeGridItem");
			
			// supress <a> element behaivior for grid items:
			$("#gridfullwidth > ul > li > a.grid-item").bind("click", function(e){
				return false;
			});
			
			
			// mouseover event-handler for grid items:
			$("#gridfullwidth > ul > li").mouseover(function(){
				// stop here if callout window is open, or if this isn't an active item (filtered out)
				if(exploreObj.callouts.calloutWindowOpen || !$(this).hasClass("activeGridItem")){
					return;
				}
				// make sure all other hover boxes are hidden:
				exploreObj.hoverBoxes.hideAll();
				
				var bump = { top:-18, left:-36 }; // shortcut to center hover box over grid item: much quicker than caclulating each time
				var thisOffset = $(this).offset();

				// try clone method:
				var originalItem = $("div.hoverBox",this);
				
				var clonedItem = originalItem.clone(true).prependTo("#container").css({
					"display":"block",
					"position":"absolute",
					"z-index":12,
					"left":thisOffset.left + bump.left,
					"top":thisOffset.top + bump.top

				}).addClass("clonedItem");
				
				// the play button on the clone should 'click' the original
				// item's play button:
				$("a.playButton",clonedItem).click(function(){
					$("a.playButton",originalItem).click();
				});
			
				
			});
		
			// mouseleave event-handler to close hover boxes:
			$("#gridfullwidth > ul > li > div.hoverBox").mouseleave(function(){

				$(this).remove();
				
			});
		},
		hideAll:function(){
			
			$("#container > div.hoverBox.clonedItem").remove();
			
		}
	},
	pagination:{ // NOTE: it is assumed that the grid will take up 2 pages
		currentPage:1,
		userPaginationDisabled:false,
		enableUserPagination:function(){
			exploreObj.pagination.userPaginationDisabled = false;
			$("#paginationContainer").removeClass("disabled");
		},
		disableUserPagination:function(){
			exploreObj.pagination.userPaginationDisabled = true;
			$("#paginationContainer").addClass("disabled");
		},
		init:function(){
			
			// add event handlers for pagination buttons:
			$("#paginationContainer a").bind("click", function(e){
				if(exploreObj.pagination.userPaginationDisabled){ return false; }
				var pageToShow = parseInt($(this).attr('href').substring(3));
				exploreObj.pagination.showPage(pageToShow);
				exploreObj.videos.playAll(pageToShow);
				return false;
			});
			
			// activate first page button:
			$("#paginationContainer > ol a:eq(0), #paginationContainer > a:eq(0)").addClass("selectedPage");
			
			// unhide pagination UI
			$("#paginationContainer").css("display","block");
		},
		showPage:function(pageNumber){
			exploreObj.pagination.currentPage = pageNumber;
			if(pageNumber==1){ // page 1
				// hide everything, show indexes 1-17:
				$("#gridfullwidth").animate({marginLeft:"0px"},750);
				$("#paginationContainer > ol a:eq(0), #paginationContainer > a:eq(0)").addClass("selectedPage");
				$("#paginationContainer > ol a:eq(1), #paginationContainer > a:eq(1)").removeClass("selectedPage");
				$("#paginationContainer > ol a:eq(2), #paginationContainer > a:eq(2)").removeClass("selectedPage");
				document.getElementById("paginationPrevious").setAttribute('href','#')
				document.getElementById("paginationNext").setAttribute('href','#pg2')
			} else if(pageNumber==2){ // page 2
				/*$("#grid > ul > li:gt(0)").css("display","none");
				$("#grid > ul > li:gt(17)").css("display","block");*/
				$("#gridfullwidth").animate({marginLeft:"-924px"},750);
				$("#paginationContainer > ol a:eq(0), #paginationContainer > a:eq(0)").removeClass("selectedPage");  //-- Remove the PREVIOUS paging blue button class
				$("#paginationContainer > ol a:eq(1)").addClass("selectedPage");
				$("#paginationContainer > a:eq(1)").removeClass("selectedPage");  																	 //-- Add the BLUE NEXT arrow class
				$("#paginationContainer > ol a:eq(2), #paginationContainer > a:eq(2)").removeClass("selectedPage");  //-- Remove the NEXT paging blue button class
				document.getElementById("paginationPrevious").setAttribute('href','#pg1')  													 //-- Dynamically Change the PREVIOUS arrow link to '#pg1'
				document.getElementById("paginationNext").setAttribute('href','#pg3')  															 //-- Dynamically Change the NEXT arrow link to '#pg3'
			}else{ // page 3
				/*$("#grid > ul > li:gt(0)").css("display","none");
				$("#grid > ul > li:gt(17)").css("display","block");*/
				$("#gridfullwidth").animate({marginLeft:"-1848px"},750);
				$("#paginationContainer > ol a:eq(0), #paginationContainer > a:eq(0)").removeClass("selectedPage");
				$("#paginationContainer > ol a:eq(1)").removeClass("selectedPage");
				$("#paginationContainer > a:eq(1)").addClass("selectedPage");
				//get the ID tag from the arrow and add htm link to the tag
				$("#paginationContainer > ol a:eq(2), #paginationContainer > a:eq(2)").addClass("selectedPage");
				document.getElementById("paginationPrevious").setAttribute('href','#pg2')  													 //-- Dynamically Change the PREVIOUS arrow link to '#pg2'
				document.getElementById("paginationNext").setAttribute('href','#')  															   //-- Dynamically Change the NEXT arrow link to '#'
			}
		}
	},
	callouts:{
		calloutWindowOpen:false,
		calloutIds:[
			{calloutId:"focus-devices",toutId:"devices"},
			{calloutId:"focus-tradeshow",toutId:"tradeshow"},
			{calloutId:"focus-hermes",toutId:"hermes"}
		],
		init:function(){
			// set up click event handlers for callouts:
			$("#touts > div.touts-body > div.callout > p > a").bind("click", function(e){
				// which one is this?
				var thisCalloutId = this.parentNode.parentNode.id;
				var toutId = "";
				for(var i=0; i < exploreObj.callouts.calloutIds.length; i++){
					// give all but active callout and respective content a class called 'inactive':
					if(exploreObj.callouts.calloutIds[i].calloutId != thisCalloutId){
						$("#"+exploreObj.callouts.calloutIds[i].calloutId).addClass("inactive");
						$("#"+exploreObj.callouts.calloutIds[i].toutId).addClass("inactive");
					}else{
						$("#"+exploreObj.callouts.calloutIds[i].calloutId).removeClass("inactive");
						$("#"+exploreObj.callouts.calloutIds[i].toutId).removeClass("inactive");
						// this is the active one: make a note of it :)
						toutId = exploreObj.callouts.calloutIds[i].toutId;
					}
				}
				
				// fade out inactive:
				$("#touts > div.touts-body > div.inactive").fadeTo("slow",0.3);
				// fade in new active:
				$(this.parentNode.parentNode).fadeTo("slow",1);
				// unhide tout content:
				$("#"+toutId).fadeIn("slow");
				
				// fade out other tout content
				$("#container > div.section.inactive").fadeOut("slow");

				// hide grid
				$("#grid").fadeTo("slow",0);
				exploreObj.callouts.calloutWindowOpen = true;
				// make sure all other hover boxes are hidden:
				exploreObj.hoverBoxes.hideAll();
				
				return false;
			});
			
			// make whole callout invoke window too:
			$("#touts > div.touts-body > div.callout").css("cursor","pointer");
			$("#touts > div.touts-body > div.callout").bind("click", function(e){
				$("p > a.learn-more",this).click();
			});
			
			// set up event handler for close button:
			$("#container > div.section > p.close-this > a").bind("click", function(e){
				exploreObj.callouts.restoreGrid();
				exploreObj.callouts.calloutWindowOpen = false;
				return false;
			});
		},
		restoreGrid:function(){
			// set all callouts to normal state:
			for(var i=0; i < exploreObj.callouts.calloutIds.length; i++){
				// remove class called 'inactive' from all callouts:
				$("#"+exploreObj.callouts.calloutIds[i].calloutId).removeClass("inactive");
			}
			
			// fade in:
			$("#touts > div.touts-body > div").fadeTo("slow",1);
			
			// hide tout content, unhide grid:
			$("#container > div.section").fadeOut("slow");
			$("#grid").fadeTo("slow",1);
		}
	},
	filter:{
		gridItemsTotal:0, // to store number of items
		init:function(){
			// need to retain original indices so that we can revert to original order:
			var allGridItems = $("#gridfullwidth > ul > li");
			this.gridItemsTotal = allGridItems.length;
			allGridItems.each(function(i){
				// set a css flag to identify original index (makes it easier to target them later)
				$(this).addClass("originalIndex"+i);
			});

			// closed filter button click handler: opens panel
			$("#filter > div.filter-button").bind("click", function(e){
				exploreObj.filter.openMenu();
			});
			
			// click handler for actual filter links:
			$("#filter > div.filter-button-open > div.filter-list ul li a").bind("click", function(e){
				// update filter ui to reflect selection:
				var characterLimit = 20;
				var uiText = $(this).html();
				if(uiText.length > characterLimit){
					uiText = uiText.substr(0,(characterLimit-3)) + "...";
				}
				$("#filter > div.filter-button > h3").html(uiText);
				
				
				// what is the selected filter? Info lives on href of the a element that was clicked...
				var filterStr =  $(this).attr("href").substring(1);
				exploreObj.filter.applyFilter(filterStr);
				// close panel: hide open filter panel, show closed state:
				exploreObj.filter.closeMenu();
				return false;
			});
			
			// hide panel if user rolls out without making selection:
			$("#filter > div.filter-button-open > div.filter-list").mouseleave(function(){
				exploreObj.filter.closeMenu();
			});
		},
		applyFilter:function(filterStr){
			if(exploreObj.callouts.calloutWindowOpen){
				exploreObj.callouts.restoreGrid();
			}
			// view all?
			if(filterStr == "view-all"){
				exploreObj.filter.resetFilter();
				return;
			}
			
			// get the active set:
			var activeCollection = $("#gridfullwidth > ul > li:gt(0)."+filterStr);
			
			// just in case there isn't a match, stop here:
			if(!activeCollection.length){ return; }
			
			// disable pagination until transition effects finish:
			exploreObj.pagination.disableUserPagination();
			
			// make sure previously faded items are reset:
			$("#gridfullwidth > ul > li:not(.activeGridItem)").fadeTo("slow",1);
			
			$("#gridfullwidth > ul > li:gt(0)").removeClass("activeGridItem"); // clear out 'active' flags
			activeCollection.addClass("activeGridItem"); // flag new active


			// renumber active items, starting with 1 and finishing with activeCollection.length
			// then renumber inactive items with remainder (grid items)

			$(activeCollection).each(function(g){
				var itemToGrab = $(this);
				// remove grid_ class, then add back with correct number:
				
				var classString = itemToGrab.attr("class");
				var classArray = classString.split(" ");
				
				for(var j=0; j < classArray.length; j++){
					var thisClassName = classArray[j];
					// is it the 'grid_n' class?
					if(thisClassName.indexOf("grid_") == 0){
						// update:
						classArray[j] = "grid_" + (g+1);
					}
				}
				
				itemToGrab.attr("class",classArray.join(" "));
				
			});


			// get the inactive set:
			var inactiveCollection = $("#gridfullwidth > ul > li:gt(0):not(li.activeGridItem)");
			var startGridNumber = activeCollection.length;


			$(inactiveCollection).each(function(g){
				var itemToGrab = $(this);
				// remove grid_ class, then add back with correct number:
				
				var classString = itemToGrab.attr("class");
				var classArray = classString.split(" ");
				
				for(var j=0; j < classArray.length; j++){
					var thisClassName = classArray[j];
					// is it the 'grid_n' class?
					if(thisClassName.indexOf("grid_") == 0){
						// update:
						classArray[j] = "grid_" + (g+startGridNumber);
					}
				}
				
				itemToGrab.attr("class",classArray.join(" "));
				
			});


			// 3- refresh pagination:
			exploreObj.pagination.showPage(1);
			
			// 4 - fade out inactive items
			$("#gridfullwidth > ul > li:not(.activeGridItem)").fadeTo("slow",0.15);
			
			// play all the active items, but delay so transitions can finish:
			var playActiveDelay = setTimeout(function(){
				exploreObj.videos.playAllActive();
			}, 500);

		},
		resetFilter:function(){

			// disable pagination until transition effects finish:
			exploreObj.pagination.disableUserPagination();

			// make sure previously faded items are reset:
			$("#gridfullwidth > ul > li:not(.activeGridItem)").fadeTo("slow",1,exploreObj.pagination.enableUserPagination);

			// set all active:
			$("#gridfullwidth > ul > li:gt(0)").addClass("activeGridItem");
			
			// revert to original order
			// originalIndex25
			



			for(var g=1; g < this.gridItemsTotal; g++){ // start at one because we're skipping first item (learn more)
				// get item with original index 'g' and add it in the correct spot:
				var itemToGrab = $("#gridfullwidth > ul > li.originalIndex" + g);
				// remove grid_ class, then add back with correct number:
				
				
				var classString = itemToGrab.attr("class");
				var classArray = classString.split(" ");
				
				for(var j=0; j < classArray.length; j++){
					var thisClassName = classArray[j];
					// is it the 'grid_n' class?
					if(thisClassName.indexOf("grid_") == 0){
						// update:
						classArray[j] = "grid_" + g;
					}
				}
				
				itemToGrab.attr("class",classArray.join(" "));
				

			}

			// pagination, reset?
			exploreObj.pagination.showPage(1);
			// play all the items, but delay so transitions can finish:
			var playAllDelay = setTimeout(function(){
				exploreObj.videos.playAll(1);
			}, 500);
		},
		openMenu:function(){
			$("#filter > div.filter-button-open").css("display","block");
			$("#filter > div.filter-button").css("display","none");
		},
		closeMenu:function(){
			$("#filter > div.filter-button-open").css("display","none");
			$("#filter > div.filter-button").css("display","block");
		}
	}
}


$(document).ready(function(){
	
	//intial modal call - grid modal instances need similar intialization
	$("#vid-grid").jqm({trigger:'#grid li:gt(0) div.hoverBox a.playButton', overlay:90, onHide:stopFVideo, onShow:showVideoAndDescription, toTop:true, modal:true});
	
	// init first grid item modal (learn more)
	
	$("#learnMoreModal").jqm({
		trigger:'#grid li:eq(0) div.hoverBox a.playButton',
		overlay:90,
		onHide:stopFVideo,
		onShow:showLearnMoreVideo,
		toTop:true,
		modal:true
	});
	
	
	// the new overlay needs to resize if window resizes:
	$(window).resize(function(){
		resizeAlternateOverlay();
	});
	
});



function resizeAlternateOverlay(){
	// how big is the screen?
	
	var sH = Math.max($(window).height(),$(document).height()); // $(window).height();
	var sW = $(window).width();

	$("#alternateOverlay").css({
		'width':sW+'px',
		'height':sH+'px',
		'left':'0px'
	})
}

function showAlternateOverlay(){
	$("#alternateOverlay").css('display','block');
}


var showVideoAndDescription=function(hash){

	exploreObj.videos.pauseAll();
	
	// hide all descriptions:
	$("#vid-grid > div.video-caption").css("display","none");
	
	// figure out what was clicked, and what the corresponding video and description are:
	
	var triggerId = $(hash.t.parentNode.parentNode.parentNode).attr("id");
	var triggerIndex = 0;
	var flvUrlStr = "";
	
	for(var i =0; i < videoDataArray.length; i++){
		if(triggerId == videoDataArray[i].triggerId){
			// got a match:
			triggerIndex = i;
			flvUrlStr = videoDataArray[i].flvUrl;
		}
	}
	
	// unhide correct description:
	$("#"+triggerId+"_description").css("display","block");
	
	// generate embed markup and insert into document:
	var embedMarkupStr = makeSwfObjMarkupForVideo(flvUrlStr);
	$("#flash-replace").html(embedMarkupStr);
	
	// unhide modal window:
	$("#vid-grid").css("display","block");
	
	$(".jqmOverlay").css({
		'display' : 'none'
	});
	
	resizeAlternateOverlay();
	showAlternateOverlay();
};


function makeSwfObjMarkupForVideo(flvUrl){
	var fo = new SWFObject("/embedded/explore/swf/VideoPlayer_embedded.swf", "flashVideoId", "640", "480", "8", "ffffff");
	fo.addVariable("flvPath", flvUrl);
	fo.addVariable("id", "videoid");
	fo.addParam("Wmode", "transparent");
	fo.addParam("allowscriptaccess", "always");
	return fo.getSWFHTML();
}

function getThumbVideoMarkup(index){
	var flashvars = {
		imgPath: "images/" + index + ".jpg",
		flvPath: "../flv/" + index + ".flv",
		swfPath: "swf/",
		isLocal: "false",
		elementId: "flash" + index
	};

	var params = {
		allowScriptAccess:"always",
		allowFullScreen:"true",
		wmode:"opaque",
		bgcolor:"#ffffff",
		flashvars: flashvars
	};

	var attributes = {
		id:"flash" + index
	};
	
	swfobject.createSWF(attributes, params, "flash" + index);

}

function embedThumbVideo(index){

	var flashvars = {
		imgPath: "images/" + index + ".jpg",
		flvPath: "../flv/" + index + ".flv",
		swfPath: "swf/",
		isLocal: "false",
		elementId: "flash" + index
	};

	var params = {
		allowScriptAccess:"always",
		allowFullScreen:"true",
		wmode:"opaque",
		bgcolor:"#ffffff"
	};

	var attributes = {
		id:'flash' + index
	};
	
	swfobject.embedSWF("swf/smallVideoPlayer_new.swf ", "flash" + index, "146", "109", "9", false, flashvars, params, attributes);
}

function stopFVideo(hash) {
	var theModal = hash.w;
	
	$("#flash-replace").html("");
	$("#learnMoreFlashContainer").html("");

	hash.w.hide();
	hash.o.remove();
	$("#alternateOverlay").css({
		'display':'none'
	})
	
	// restart videos in grid for current page:
	exploreObj.videos.playAll(exploreObj.pagination.currentPage);
}


var showLearnMoreVideo=function(hash){
	
	// generate embed markup and insert into document:
	var fo = new FlashObject("/embedded/explore/swf/embedded_learnMore.swf", "embedded_learnMore", "932", "466", "9", "bgcolour");
	fo.addParam("Wmode", "true");
	fo.addParam("allowscriptaccess", "always");
	var embedMarkupStr = fo.getSWFHTML();
	$("#learnMoreFlashContainer").html(embedMarkupStr);
	
	// unhide modal window:
	$("#learnMoreModal").css("display","block");
	
	$(".jqmOverlay").css({
		'display' : 'none'
	});

	resizeAlternateOverlay();
	showAlternateOverlay();

};


function setVideoSize(width,height) {
	$("#flashVideoId").css({'width' : width+'px', 'height' : height+'px'});
	resizeAlternateOverlay();
}




