

/*======================================================================
	timelapseFull.js
------------------------------------------------------------------------
	JavaScript
	
	PURPOSE
		Handle custom Web 2.0 functionality for the timelapse
	images on the north america map on WindowsAroundTheWorld.

	NOTES 
		This uses Script.aculo.us on Prototype for advanced
	UI animation and AJAX communication.


	HISTORY
	
	2006-11-25, Created, Jim Rich
	2008-05-10, Modified, Jim Rich
		- Added San Dimas school (sdm)
	2008-07-27, Modified, Jim Rich
	    - Totally rebuilt for Full Timelapse page
	
	for www.WindowsAroundTheWorld.org
=======================================================================*/


/*======================================================================
	Global Variables and Settings
=======================================================================*/
	// Set timeLapse 
	var timelapseSpeed = 3.41; // natural log of the Frames per Second to be converted to miliseconds
	var restartTime = 3000;
	var imageSize = 's';

	var currentSchool;
	var currentSchoolDisplay;
	var timelapseMoveDistance = 111;
	var allowOpen = true;
	var killDownloads = false;

	// Toggle managment
	var mtjImageParameterList;
	var mtjDayPulled = false;
	var toggleMtJuliet = -1;	
	var mtjLeaveOpen = false;

	// Timelapse Frame Tracking variables
	var mtjTrackTimeout;
	var mtjTrackFrames = 0;
	var mtjRunState = 0;

	// Image Arrays 
	var mtjImages = new Array();
	var mtjImageLabel = new Array();
	var mtjImagePreload = new Array();
	var mtjLargeImages = new Array();

    // Schools array
    var schoolName = new Array('franklin','paulatuk','mtjuliet','hilo','phoenix','dorchester','charlotteville','sandimas','nantucket');
    var schoolID = new Array(3,5,7,8,9,11,12,14,15);
    var schoolDisplay = new Array('Franklin, Massachusetts','Paulatuk, Northwest Territories, Canada','Mt. Juliet, Tennessee','Hilo, Hawaii','Phoenix, Arizona','Dorchester, Massachusetts','Charlotville, Tobago','San Dimas, California','Nantucket, Massachusetts');
    


/*======================================================================
	On Load Function
=======================================================================*/
	function initialize() {
		// Set the current time on the timeofday slider
		
		document.getElementById('mtj_time_value').innerHTML=possibleTimeOfDay[mtjTimeOfDay];
		document.getElementById('mtj_speed_value').innerHTML=possibleSpeed[Math.round((timelapseSpeed*1.7)+2.316)];

        // Need to create a new function that accepts institutionID and uses the arrays.
		switch(institutionID){
		   case '3':
			 toggleSchoolButton('franklin');	
			break;
		   case '5':
			toggleSchoolButton('paulatuk');
			break;
		   case '7':
			toggleSchoolButton('mtjuliet');
			break;
		   case '8':
			toggleSchoolButton('hilo');
			break;
		   case '9':
			toggleSchoolButton('phoenix');	
			break;
		   case '11':
			toggleSchoolButton('dorchester');	
			break;
		   case '12':
			toggleSchoolButton('charlotteville');
			break;
		   case '14':
			toggleSchoolButton('sandimas');	
			break;	
		   case '15':
			toggleSchoolButton('nantucket');	
			break;			
		   default : 
			toggleSchoolButton('franklin');	
			break;
		}	
		
		
		// From nav.js
		startList();
	}

/*======================================================================
	Slider functions and lookup arrays
=======================================================================*/
	// Slider and onChange functions
	var possibleTimeOfDay = new Array('12:00 midnight','1:00 am','2:00 am','3:00 am','4:00 am','5:00 am','6:00 am','7:00 am','8:00 am','9:00 am','10:00 am','11:00 am','12:00 noon','1:00 pm','2:00 pm','3:00 pm','4:00 pm','5:00 pm','6:00 pm','7:00 pm','8:00 pm','9:00 pm','10:00 pm','11:00 pm','12:00 midnight');
	var possibleSpeed = new Array('5 Seconds / Frame','2 Seconds / Frame','1.25 Seconds / Frame','2 Frames / Second (FPS)','3 Frames / Second (FPS)','5 Frames / Second (FPS)','9 Frames / Second (FPS)','17 Frames / Second (FPS)','30 Frames / Second (FPS)','55 Frames / Second (FPS)','100 Frames / Second (FPS)');
  

    //Full
    //var schoolName = new Array('franklin','paulatuk','mtjuliet','hilo','phoenix','roxbury','dorchester','charlotteville','scarborough','sandimas','nantucket');
    //var schoolID = new Array(3,5,7,8,9,10,11,12,13,14,15);
    
	// Process the TimeFrame slider selection
	function chooseTimeFrame(selection,school){

		var timeFrame;
		var coverDisplay;

		switch(selection){
		   case 1:
			timeFrame = 'month';
			coverDisplay = 'none'
			break;
		   case 2:
			timeFrame = 'year';
			coverDisplay = 'none'
			break;
		   default : 
			timeFrame = 'day';
			coverDisplay = 'block'
			break;
		}	


		mtjTimeFrame = timeFrame;
		//document.getElementById('mtj_time_of_day_cover').style.display = coverDisplay;
		mtjTrackFrames=0;
		killdownloads = true;
		endDate = persistedEndDate;
	}


	// Toggle the button selectors
	function toggleSchoolButton(school){
	
	    // Stop the player
	    mtjToggleTimeLapsePlay('stop');
		mtjTrackFrames=0;
		killdownloads = true;
	
		//clear all the buttons
		for (i = 0; i < schoolName.length; i++){
		    
		  //turn all buttons off  
		  document.getElementById('btn_'+schoolName[i]).style.backgroundPosition='0 0';
		  
		  // add the school selected if it matches 
		  if (schoolName[i] == school)
		  {
		    institutionID = schoolID[i];
		    currentSchoolDisplay = schoolDisplay[i];
		  }
		}
				
		//select the one passed in
		document.getElementById('btn_school_name').innerHTML = currentSchoolDisplay;
        document.getElementById('btn_'+school).style.backgroundPosition='0 -51px';		
	}

    //Mouse Over of School Selector button
    function mouseoverSchoolButton(school){
		for (i = 0; i < schoolName.length; i++){
	
		  // add the school selected if it matches 
		  if (schoolName[i] == school)
		  {
		    document.getElementById('btn_school_name').innerHTML = schoolDisplay[i];
		  }
		}
    }

    //Mouse Out of School Selector button
    function mouseoutSchoolButton(school){
            document.getElementById('btn_school_name').innerHTML = currentSchoolDisplay;
    }



	// Process the TimeOfDay slider selection
	function chooseTimeOfDay(selection,school){
	
		mtjTimeOfDay = selection;
		document.getElementById('mtj_time_value').innerHTML=possibleTimeOfDay[selection];
		mtjTrackFrames=0;
		killdownloads = true;

		endDate = persistedEndDate;
	}


	// Process the Speed slider selection
	function chooseSpeed(selection){
	
		timelapseSpeed = selection;
		//mtjTrackFrames=0;
		//killdownloads = true;

		//endDate = persistedEndDate;
	}


/*======================================================================
	AJAX call and error handling
=======================================================================*/


	// Handle the call made to the server
	function requestImages(parameterList, school) {
	
		currentSchool = school;
		
		new Ajax.Request('timelapsedata.aspx', {parameters:parameterList, onSuccess:processImageRequest, onFailure:errFunc, method:'GET',asynchronous: true });

	}



	// Handle the call made to the server
	function processImageRequest(req) {
	
		var responseData = eval('('+req.responseText+')');

		mtjImages.length = 0;
		mtjImageLabel.length = 0;
		mtjLargeImages.length = 0;
		mtjImagePreload.length = 0;
		//Load the data into arrays
		for (var i=0;i<responseData.timelapse.length;i++)
		{
			mtjImages[i] = responseData.timelapse[i].image.path;
			mtjImageLabel[i] = responseData.timelapse[i].image.label;
			mtjLargeImages[i] = responseData.timelapse[i].image.largeImage;
		}

		//Cache the images
		for (i = 0; i < mtjImages.length; i++){
		   mtjImagePreload[i] = new Image()
		   mtjImagePreload[i].src = mtjImages[i]
		   if(killDownloads)
		   	break;
		}
	}


	// Need better Error presentation, but this will catch the errors
	var errFunc = function(t) {
	    alert('Error ' + t.status + ' -- ' + t.statusText);
	}







/*======================================================================
	Functions to play the timelapse movies
	TODO: Simplify with single functions with params, not time for that now.
=======================================================================*/
	function mtjToggleTimeLapsePlay(action){
		if (mtjRunState == 0 && action != 'stop'){
			mtjRunState = 1;
			killdownloads = false;
			//document.getElementById('mtj_all_slider_cover').style.display = 'block';
			document.getElementById('mtj_timelapse_button').src = 'images/timelapse-pause.gif';

			// don't pull images if you already have them
			if(mtjImageParameterList != 'i='+ institutionID +'&tf='+mtjTimeFrame+'&td='+mtjTimeOfDay+'&ed='+endDate+'&sz='+imageSize) {

				// get the images
				mtjImageParameterList = 'i='+ institutionID +'&tf='+mtjTimeFrame+'&td='+mtjTimeOfDay+'&ed='+endDate+'&sz='+imageSize
				new Ajax.Request('timelapsedata.aspx', {parameters:mtjImageParameterList, onSuccess:processImageRequest, onFailure:errFunc, method:'GET',asynchronous: true });
			}	

			//Delay play to allow some images to load
			document.getElementById('mtjLoading').style.display = 'block';
			setTimeout('mtjPlayTimeLapseFrames();',3000);
			}
		else {
		document.getElementById('mtj_timelapse_button').src = 'images/timelapse-play.gif'
		//document.getElementById('mtj_all_slider_cover').style.display = 'none';
		mtjRunState = 0;
		}
	}

	function mtjPlayTimeLapseFrames(){

		   // turn off loading animation here
		   document.getElementById('mtjLoading').style.display = 'none';
		   
		   // check to see if any images came back
		   if(mtjImages.length > 0) {
		   
		    if(imageSize == 's')
		    {
			   // change the image	
			   document.getElementById('smallPlayerImage').src = mtjImagePreload[mtjTrackFrames].src;

			   //need to change popup size based on type of image
			   if (mtjLargeImages[mtjTrackFrames] == 'none') {
				document.getElementById('mp_mtjulietLarge').childNodes[0].href = '#';
				document.getElementById('mp_mtjulietLarge').childNodes[0].style.cursor='default';
				}
			   else {
				document.getElementById('mp_mtjulietLarge').childNodes[0].href = 'javascript:openPopup(\'../view_image.aspx?t='+ mtjLargeImages[mtjTrackFrames] +'&s='+ mtjLargeImages[mtjTrackFrames] +'&w=480&h=640\',480,640);';
				document.getElementById('mp_mtjulietLarge').childNodes[0].style.cursor='pointer';
				}

            }
            else
            {
			   // change the image	
			   document.getElementById('largePlayerImage').src = mtjImagePreload[mtjTrackFrames].src;

			   //need to change popup size based on type of image
			   if (mtjLargeImages[mtjTrackFrames] == 'none') {
				document.getElementById('player_window').childNodes[0].href = '#';
				document.getElementById('player_window').childNodes[0].style.cursor='default';
				}
			   else {
				document.getElementById('player_window').childNodes[0].href = 'javascript:openPopup(\'../view_image.aspx?t='+ mtjLargeImages[mtjTrackFrames] +'&s='+ mtjLargeImages[mtjTrackFrames] +'&w=480&h=640\',480,640);';
				document.getElementById('player_window').childNodes[0].style.cursor='pointer';
				}
            
            }


			   // Change the date time label for each image
			   //document.getElementById('mtjImageLabel').innerHTML = mtjImageLabel[mtjTrackFrames];

			   mtjTrackFrames = mtjTrackFrames + 1;
			   if (mtjTrackFrames > (mtjImagePreload.length-1)) mtjTrackFrames=0;

			   if (mtjRunState == 1) {

			   if (mtjTrackFrames!=0) mtjTrackTimeout = setTimeout('mtjPlayTimeLapseFrames()', (1000/(Math.exp(timelapseSpeed))));
			   else mtjTrackTimeout = setTimeout('mtjPlayTimeLapseFrames()', restartTime);
			   }
		   }
	}
	
		
	
/*======================================================================
	Duplicate code from nav.js so we can combine the onload methods
=======================================================================*/

	startList = function() {
		if (document.all&&document.getElementById) {
			navRoot = document.getElementById("nav");
			for (i=0; i<navRoot.childNodes.length; i++) {
				node = navRoot.childNodes[i];
				if (node.nodeName=="LI") {
					node.onmouseover=function() {
						this.className+=" over";
					}
					node.onmouseout=function() {
						this.className=this.className.replace(" over", "");
					}
				}
			}
		}
	}

	function openPopup( popUp,wt,ht ) {
		var str="toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,screenx=30,screeny=20,width="+wt+",height="+ht+",top=0,left=0";
		popupWin=window.open(popUp,"large_image",str);
		popupWin.focus();
	}
	


	
	
