//****************************************************************
//****************************************************************
//	COPYRIGHT 2009, Vertex Software
//****************************************************************
//****************************************************************

var kRandomDisplayTime = 10000;
// 06MAY3009 RFM - DEFECT 2390
var kHideFlashPlayerHere = "hideFlashPlayerHere";

//===========================================================
// InitializeGrid
//===========================================================
function InitializeGrid( ) {
	try {
		CenterElementsOnPage();
		$(".gridImage,.gridImageVideo").mouseover( HandleOverItem ) 
		$("#popOutImage").click( function() { 
			StartStopRandomViewing(true);
			DisplayItemInMap(this.gridImage) 
			} );
		$("#next").click( function() { ViewPreviousNextItem(1) } );
		$("#previous").click( function() { ViewPreviousNextItem(-1) } );
		$(window).resize( function() { CenterMapOnGrid(true) } );
		}
	catch (error) {
		alert( "InitializeGrid: " + error.description  );
		}
	}


//===========================================================
// CenterElementsOnPage
//===========================================================
function CenterElementsOnPage( forResize ) {
	try {
		$(".content").show();
		$(".content").css({ "position":"absolute", "left":"50%", "margin-left": -($("#grid").innerWidth() / 2) + "px" });
		CenterMapOnGrid();
		}
	catch (error) {
		alert( "CenterElementsOnPage: " + error.description  );
		}
	}


//===========================================================
// CenterMapOnGrid
//===========================================================
function CenterMapOnGrid( forResize ) {
	try {
		$("#mapViewer").each( function() {
			var kFudgeFactor = 2;
			$(this).hide();
			$(this).css({
				// center the viewer on the grid
				"position" : "absolute",
				"left" : ($("#grid").width() / 2) - ($(this).width() / 2),
				"top" : ($("#grid").height() / 2) - ($(this).height() / 2),
				"z-index" : "1000"
				}).show();
			})
		$("#popOutImage,#popOutItem").mouseout( HandleOutItem  );
		//DisplayItemInMap( $(".gridImage")[0] );
		if (forResize) return; 
		ViewRandomItem();
		StartStopRandomViewing();
		}
	catch (error) {
		alert( "CenterMapOnGrid: " + error.description  );
		}
	}




//===========================================================
// HandleOutItem
//===========================================================
function HandleOutItem( event ) {
	try {
		$("#popOutItem").each( function() {
			this.style.display = "none";
			HandleOverItem.selected = false;
			if (SelectItem.current) {
				HandleOutItem.timer = window.setTimeout( function() { 
					if (!HandleOverItem.selected) {
						HandleOverItem( { srcElement: SelectItem.current[0] } );
						} 
					}, 1000 );
				}
			} );
		}
	catch (error) {
		alert( "HandleOutItem: " + error.description  );
		}
	}


//===========================================================
// HandleOverItem
//===========================================================
function HandleOverItem( event, animate ) {
	try {
		var imageElement = event.target;
		if (!imageElement) return; 
		if (HandleOutItem.timer) {
			window.clearTimeout( HandleOutItem.timer );
			HandleOutItem.timer = "";
			}
		$("#popOutItem").each( function() {
			var imageCellLocation = $(imageElement).parent().offset();
			var tableLocation =  $(imageElement).parent().parent().parent().offset();
			// 29APR2009 RFM - Change Request #1
			//var height = $(imageElement).height()*2;
			//var width = $(imageElement).width()*2;
			var magnification = kRolloverItemHeight/kGridItemHeight;
			var height = $(imageElement).height()*magnification;
			var width = $(imageElement).width()*magnification;
			$(this).width( width );
			$(this).height( height );
			// 29APR2009 RFM - Change Request #1
			//this.style.top = (imageCellLocation.top - height/4) - tableLocation.top +  "px";
			//this.style.left = (imageCellLocation.left - width/4) - tableLocation.left + "px";
			this.style.top = (imageCellLocation.top - (kRolloverItemHeight-kGridItemHeight)/2) - tableLocation.top +  "px";
			this.style.left = (imageCellLocation.left - (kRolloverItemWidth-kGridItemWidth)/2) - tableLocation.left + "px";
			MoveIfOverMap(this);
			$("#popOutImage").each( function() { 
				// 29APR2009 RFM - Change Request #1
				//this.src = imageElement.src.split( "_" )[0] + "_" +  kGridItemHeight*2 + "x" +  kGridItemWidth*2 + ".jpg";
				this.src = imageElement.src.split( "_" )[0] + "_" +  kRolloverItemHeight + "x" +  kRolloverItemWidth + ".jpg";
				this.width = width;
				this.height = height;
				this.gridImage = imageElement;
				} );
			if (animate) {
				$(this).fadeIn("normal" );
				}
			else {
				this.style.display = "block";
				}
			HandleOverItem.selected = true;
			} );
		}
	catch (error) {
		alert( "HandleOverItem: " + error.description  );
		}
	}


//===========================================================
// GetElementLocation
// return { Top:, Left:, Bottom:, Right: } for element
//===========================================================
function GetElementLocation( element ) {
	try {
		// Offset doesnt' work when style was just changed
		//return { Top:element.offset().top, Left:element.offset().left, Bottom:element.height() + element.offset().top, Right:element.width() + element.offset().left };
		return { Top:ToNumber(element[0].style.top), Left:ToNumber(element[0].style.left), Bottom:element.height() + ToNumber(element[0].style.top), Right:element.width() + ToNumber(element[0].style.left) };
		}
	catch (error) {
		alert( "GetElementLocation: " + error.description  );
		}
	return { Top:0, Left:0, Bottom:0, Right:0 };
	}



//===========================================================
// ToNumber
// Converts a style with px to a number
//===========================================================
function ToNumber( styleText ) {
	try {
		if (typeof styleText == "number") return styleText;
		return Number( styleText.replace( "px", "" ) );
		}
	catch (error) {
		alert( "ToNumber: " + error.description  );
		}
	return styleText;
	}


//===========================================================
// MoveIfOverMap
// Moves image so not over mapViewer
//===========================================================
function MoveIfOverMap( image ) {
	try {
		image = $(image);
		var mapViewerLocation = GetElementLocation( $("#mapViewer") );
		var imageLocation = GetElementLocation( image );
		var isImageOver = (imageLocation.Right - mapViewerLocation.Left > image.width()/2 && mapViewerLocation.Right - imageLocation.Left > image.width()/2);
		var isImageOverLeftSide = (imageLocation.Right > mapViewerLocation.Left && imageLocation.Right < mapViewerLocation.Right); 
		var isImageOverRightSide = (imageLocation.Left < mapViewerLocation.Right && imageLocation.Right > mapViewerLocation.Right);
		var isImageOverTop = (imageLocation.Bottom > mapViewerLocation.Top && imageLocation.Top < mapViewerLocation.Top );
		var isImageOverBottom = (imageLocation.Top < mapViewerLocation.Bottom && imageLocation.Bottom > mapViewerLocation.Bottom );
		if (isImageOverBottom && isImageOver) {
			image[0].style.top = mapViewerLocation.Bottom + "px";
			}
		//if (isImageOverTop && (isImageOverLeftSide || isImageOverRightSide)) {
		//	image[0].style.top = (mapViewerLocation.Top - image.height()) + "px";
		//	}
		//if (isImageOverLeftSide && (isImageOverTop || isImageOverBottom)) {
		//	image[0].style.left = (mapViewerLocation.Left - image.width()) + "px";
		//	}
		//if (isImageOverRightSide && (isImageOverTop || isImageOverBottom)) {
		//	image[0].style.left = mapViewerLocation.Right  + "px";
		//	}
		}
	catch (error) {
		alert( "MoveIfOverMap: " + error.description  );
		}
	}


//===========================================================
// StartStopRandomViewing
//===========================================================
function StartStopRandomViewing( stop  ) {
	try {
		if (stop) {
			if (StartStopRandomViewing.timer) {
				window.clearInterval(StartStopRandomViewing.timer);
				StartStopRandomViewing.timer = "";
				}
			}
		else {
			StartStopRandomViewing.timer = window.setInterval( ViewRandomItem, kRandomDisplayTime );
			}
		}
	catch (error) {
		alert( "StartStopRandomViewing: " + error.description  );
		}
	}


//===========================================================
// SelectItem
//===========================================================
function SelectItem( imageElement, animate ) {
	try {
		if (SelectItem.current) HandleOutItem( SelectItem.current[0].firstChild );
		SelectItem.current = $(imageElement);
		HandleOverItem( { target: imageElement }, animate );
		}
	catch (error) {
		alert( "SelectItem: " + error.description  );
		}
	}



//===========================================================
// ViewRandomItem
//===========================================================
function ViewRandomItem( ) {
	try {
		var totalLocations = $(".gridImage,.gridImageVideo" ).length;
		ViewPreviousNextItem( );
		}
	catch (error) {
		alert( "ViewRandomItem: " + error.description  );
		}
	}


//===========================================================
// ViewPreviousNextItem
//===========================================================
function ViewPreviousNextItem( direction ) {
	try {
		if (direction) StartStopRandomViewing(true);
		var totalLocations = $(".gridImage,.gridImageVideo" ).length;
		var locationID = 0;
		if (!direction || !SelectItem.current || SelectItem.current.length == 0) {
			locationID = Math.max( 1, parseInt( Math.random()*totalLocations ) );
			}
		else {
			locationID = Number( SelectItem.current[0].id.replace( "Location", "" )) + direction;
			}
		if (locationID < 0) locationID = totalLocations;
		if (locationID > totalLocations) locationID = 1;
		DisplayItemInMap( $("#Location" + locationID)[0], true );
		}
	catch (error) {
		alert( "ViewPreviousNextItem: " + error.description  );
		}
	}



//===========================================================
// DisplayItemInMap
//===========================================================
function DisplayItemInMap( imageElement, animate ) {
	try {
		// 06MAY2009 RFM - Edge case where imageElement is null;
		if (!imageElement || imageElement==null) return; 
		var imageParent =  $(imageElement).parent();
		var cellWidth = kGridItemWidth*3;
		var cellHeight = kGridItemHeight*3;
		var imageURL = imageElement.src.split("_")[0] + "_" + cellHeight + "x" + cellWidth + ".jpg";
		// 08MAY2009 RFM - Need mroe than 10
		//var zipCode = imageURL.match( /([0-9]{5})-[0-1]{2}/g ) ? RegExp.$1 : "78749";
		var zipCode = imageURL.match( /([0-9]{5})-[0-9]{2}/g ) ? RegExp.$1 : "78749";
		StopVideo();
		ClearOverlays();
		gLocationPlotInfo[1] =  { ID:1, Longitude:0, Latitude:0, Zip:zipCode, State:"Texas", City:"", Address:"", Country:"USA", LookupName:true, ImageWidth:cellWidth, ImageHeight:cellHeight, ImageURL:imageURL  };
		gLocationIDList[0] = 1;
		SetNoScrollIntoView(true);
		SetLocationMarkerInfoWindowTemplate( "<div class='popupTitle' style='width:||ImageWidth||'>||City||, ||State||</div><div id='popupImage'><img height='||ImageHeight||' width='||ImageWidth||' src='||ImageURL||'></div>" );
		$("#loading")[0].style.display = "block";
		LookupLocationCoordinates( function() { 
			//$("#loading")[0].style.display = "none";
			$("#loading").fadeOut("slow");
			PlotLocations();
			if (imageElement.className.match(/Video/) && $("#popupImage").length > 0) { 
				CreateVideoViewer( imageElement.src, cellWidth, cellHeight  );
				}
			} );
		SelectItem( imageElement, animate );
		}
	catch (error) {
		alert( "DisplayItemInMap: " + error.description  );
		}
	}



//===========================================================
// StopVideo
//===========================================================
function StopVideo( ) {
	try {
		if (!document.getElementById("FlashViewer")) return;
		// Cant' get sendEvent to stop video. Deleting node while video is playing results in
		// errors from player script so move node to body and delete in CreateVideoViewer
		var player = document.getElementById("FlashViewer");
		player.style.display = "none";
		player.parentNode.removeChild(player);
		// 06MAY3009 RFM - DEFECT 2390
		//document.body.appendChild(player);
		document.getElementById(kHideFlashPlayerHere).appendChild(player);
		}
	catch (error) {
		alert( "StopVideo: " + error.description  );
		}
	}



//===========================================================
// CreateVideoViewer
//===========================================================
function CreateVideoViewer( videoImage, cellWidth, cellHeight ) {
	try {
		var video = (videoImage.match( /([0-9]{5}-[0-9]{2})/gi ) ? RegExp.$1  : "");
		var oldPlayer = document.getElementById("FlashViewer");
		var isDev = document.location.href.match( /vertex/i );
		with( new SWFObject("/global/scripts/swf/mediaplayer.swf", "FlashViewer" , cellWidth, cellHeight, "8", "#FFFFFF")) {
			addParam("allowfullscreen", "true");
			addParam("allowscriptaccess", "always");
			addVariable("id", video);
			addVariable("width", cellWidth);
			addVariable("height", cellHeight);
			addVariable("file", "rtmp://flashmedia.vertex.com/ClickItOrTicket" + (isDev ? "Dev" : "") + "/" );
			addVariable("enablejs", "true");
			addVariable("image", videoImage);
			write( "popupImage"); 
			} 
		if (oldPlayer) {
			// 06MAY3009 RFM - DEFECT 2390
			//document.body.removeChild( oldPlayer ); 
			document.getElementById(kHideFlashPlayerHere).removeChild( oldPlayer ); 
			}
		}
	catch (error) {
		alert( "CreateVideoViewer: " + error.description  );
		}
	}