/*********************UnClassified******************************
 *                                                             *
 *  Project:  Wavcam(tm) On Demand viewer javascript interface *
 *  Author:   J.Dean                                           *
 *  Modified: 21 Feb 2008                                      *
 *  Copyright: 2007-2008 Innovative Signal Analysis Inc.       *
 *  License: This code may not be copied, distributed, or used *
 *  to create derivative works without the written             *
 *  consent of Innovative Signal Analysis Inc.                 *
 ***************************************************************/

/*  This file handles all of the user interface and timing for the
	  On Demand viewer.  It makes use of AJAX to prevent the need for
		constantly refreshing the entire .html file, this also reduces
		the overhead on the server.  The project makes extensive use of
		meta tags to store variables about how the imagery is being viewed.
		The other option is to implement sessions, but using the meta tags
		allows for a simpler interface that (with the imbedded php) allows
		for exact bookmarking to a specific frame and view mode. */

/* AJAX comments:  If multiple functions make calls to either create,
   modify, or read an AJAX object (xmlHttp) then bad things can happen.
   In a project like this with synchronous and asynchronous image updates
   the only safe way to handle this is to (for the most part) have 
   each function create an object with a different name. This unfortunately
   means that functions that could normally be used for "play" and "update"
   need to be copied.  It would be possible to reuse them with lots of if / then
   work, but this would really eat cpu on the client side and we're trying to 
   avoid that.*/

/* These functions allow images to be loaded in background first
	 providing flicker free viewing */
var wimage = new Image();
var wimage2 = new Image();
var playangle_g = "";
var playtime_g = "";
var nimage_g = 1;
var nframe_g = 1;
var oframe_g = 1;
var playing_g = 0;
var panset_g = 1;
var workdir_g = "";
var anglespeed_g = 0;
var timespeed_g = 0;
var twoup_g = 0;

function updateimg(){ //This will refresh the image
	document.getElementById("wavcamimg").src = wimage.src;
}
function updateimg2(){ //This will refresh the image
	document.getElementById("wavcamimg2").src = wimage2.src;
}

function imageChanged1(action,twoup,workdir){  //update center image while playing
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ //only state we're interested in 4="done"
		var nimage =  xmlHttp.responseXML.getElementsByTagName("newimg")[0].childNodes[0].nodeValue;
		var nframe =  xmlHttp.responseXML.getElementsByTagName("newframe")[0].childNodes[0].nodeValue;
	  var iserror = xmlHttp.responseXML.getElementsByTagName("error")[0].childNodes[0].nodeValue;
		var outdir = workdir + "webimages/";
		if (iserror=="0"){   //If there's no errors then load images
			if (twoup==1){
				var nframe2 =  xmlHttp.responseXML.getElementsByTagName("newframe2")[0].childNodes[0].nodeValue;
				wimage2.src = outdir + "image_"+nimage+"_f"+nframe2+".jpg";		//Preload Image
				setTimeout(updateimg2,90); //Give browser 100ms to load image
			}
			wimage.src = outdir + "image_"+nimage+"_f"+nframe+".jpg";		//Preload Image
			setTimeout(updateimg,90); //Give browser 100ms to load image
			document.getElementById("imgcur").value=nimage;
			document.getElementById("framecur").value=nframe;
			nimage_g = nimage;
			if ((action!="pimage")&&(action!="nimage")){ //this should fix race condition with frame changes
				nframe_g = nframe;
			}
			if (nframe_g != oframe_g){
				highlightCurrent2(twoup,nframe_g,oframe_g);		//Highlight image in panoramic (only call if needed)
				oframe_g = nframe_g;
			}
			loadPartial(workdir,nimage);
			play_wav();					//Callback to play timer function	
		} else {
			playing_g = 0;
			playangle_g = "";
			playtime_g = "";
		}
	}
}

function imageChanged2(action,twoup,workdir){  //copy of above with diff AJAX object
	if (xmlHttpsing.readyState==4 || xmlHttpsing.readyState=="complete"){ //This is the only state we're interested in 4="done"
		var nimage =  xmlHttpsing.responseXML.getElementsByTagName("newimg")[0].childNodes[0].nodeValue;
		var nframe =  xmlHttpsing.responseXML.getElementsByTagName("newframe")[0].childNodes[0].nodeValue;
	  var iserror = xmlHttpsing.responseXML.getElementsByTagName("error")[0].childNodes[0].nodeValue;
		var outdir = workdir + "webimages/";
		if (iserror=="0"){   //If there's no errors then load images
			document.getElementById("imgcur").value=nimage;
			document.getElementById("framecur").value=nframe;
			nimage_g = nimage;
			if ((action!="pimage")&&(action!="nimage")){ //this should fix race condition with frame changes
				nframe_g = nframe;  //don't override changed image number
			}
			if (twoup==1){
				var nframe2 =  xmlHttpsing.responseXML.getElementsByTagName("newframe2")[0].childNodes[0].nodeValue;
				wimage2.src = outdir + "image_"+nimage+"_f"+nframe2+".jpg";		//Preload Image
				setTimeout(updateimg2,90); //Give browser 100ms to load image
			}
			wimage.src = outdir + "image_"+nimage+"_f"+nframe+".jpg";		//Preload Image
			setTimeout(updateimg,90); //Give browser 90ms to load image
			if (action !="first"){
				if (nframe_g != oframe_g){
					highlightCurrent2(twoup,nframe_g,oframe_g);		//Highlight image in panoramic
					oframe_g = nframe_g;
				}
			}
		} 
	}
}

/*This function is the interface to the php processing files,
  all important information is sent via http GET command line*/
function proc1stButton(waction){
	xmlHttp=GetXmlHttpObject();	//Get AJAX interface
	var url = "inc_wavplayback.php" + "?imgnum="+nimage_g+"&framenum="+nframe_g+"&waction="+waction+"&workdir="+workdir_g+"&twoup="+twoup_g;
	xmlHttp.onreadystatechange=function(){
					imageChanged1(waction,twoup_g,workdir_g);
					};
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}
/*This is a copy of the above with a diff AJAX object name.
	This is required because multiple calls to the same AJAX 
	object can cause the playing to die and be unrecoverable
  (have only seen this on Gecko based browsers).*/
function procSingleButton(waction){
	if ((playing_g ==0)||((playing_g==1)&&(playtime_g==""))){//either not playing or playing angles
		xmlHttpsing=GetXmlHttpObject();	//Get AJAX interface
		if (xmlHttpsing==null){
			alert ("This browser does not support AJAX");
			return;
		}
		var url = "inc_wavplayback.php" + "?imgnum="+nimage_g+"&framenum="+nframe_g+"&waction="+waction+"&workdir="+workdir_g+"&twoup="+twoup_g;
		xmlHttpsing.onreadystatechange=function(){
						imageChanged2(waction,twoup_g,workdir_g);
						};
		xmlHttpsing.open("GET",url,true);
		xmlHttpsing.send(null);
	} else {
		if(waction =="pframe"){
			var nframe_gint = parseInt(nframe_g);
			if( nframe_gint == 2 ){
				nframe_g = 80;
			} else{
				nframe_g = nframe_gint - 1;
			}
		} else if (waction =="nframe"){
			var nframe_gint = parseInt(nframe_g);
			if( nframe_gint == 80 ){
			nframe_g = 2;
			} else{
				nframe_g = nframe_gint + 1;
			}
		}
	}
}

function delay_metachange0(element0) {
		element0.onkeyup = function(){metachange_0(element0);};
		}
function metachange_0(element0){
	var	func = function() {
									nimage_g = element0.value;
						};
	if(element0.alertTimerId){
		clearTimeout(element0.alertTimerId);
	}
	element0.alertTimerId = setTimeout(func,200); //delay
}
		
function delay_metachange1(element1) {
	element1.onkeyup = function(){metachange_1(element1);};
	}

function metachange_1(element1){
	var	func1 = function() {
								nframe_g = element1.value;
						};
	if(element1.alertTimerId){
		clearTimeout(element1.alertTimerId);
	}
	element1.alertTimerId = setTimeout(func1,200); //delay for 200 ms
}

function setup_play_angle(pl_func,speed){
	playangle_g = pl_func;
	anglespeed_g = speed;	
	if (playing_g == 0){ //We're not currently playing
		playing_g = 1;
		play_wav();
	}
}
	
function stop_play_angle(){
	playangle_g = "";
}

function setup_play_time(pl_func,speed){
	playtime_g = pl_func;
	timespeed_g = speed;
	if (playing_g == 0 ){ //Not currently playing
		playing_g = 1;
		play_wav();
	}
}

function stop_play_time(){
	playtime_g = "";
}

function play_wav(){
	var plspeed;
	//Speed arbitration
	if (playangle_g ==""){ //Timescan only
		plspeed = timespeed_g;
	} else {
		if (playtime_g ==""){ //Angle scan only
			plspeed = anglespeed_g;
		}else{
			plspeed = anglespeed_g; //FIXME need proper arbitration
		}
	}
	var pl_func = playangle_g + playtime_g;	
	if (pl_func ==""){
		playing_g = 0;
	}
	else {
		playing_g = 1;
	}
	var func = function(){	proc1stButton(pl_func);
										}
	if (playing_g == 1){
		setTimeout(func,plspeed);
	}
}

/******************************************************************
                      Panoramic functions
******************************************************************/
function panChanged(){
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ //This is the only state we're interested in 4="done"
		var pimage =  xmlHttp.responseXML.getElementsByTagName("pimg")[0].childNodes[0].nodeValue;
//		var frames =  xmlHttp.responseXML.getElementsByTagName("numframes")[0].childNodes[0].nodeValue;
		var rprefix = xmlHttp.responseXML.getElementsByTagName("resultprefix")[0].childNodes[0].nodeValue;
		var twidth = document.body.offsetWidth - 40; //This will adjust "per browser"
		var fwidth = (twidth / 79)|0;  //can only have integers
		var fheight = 48;  //do we want this to be a proper proportion ?
		var rwidth = 320; //real width
		var rheight = 240; //real height
		var turl = "";
		var	imgaction0 = 'onclick=\"panChangeFrame(this.id)\"';
		var imglnk;
		for (var k = 2; k<=80; k++){					//make panoramic
			imglnk = "<a class=\"smpan\" href=\"#\"> <img id=\""+k+"\"  "+imgaction0+" width=\""+fwidth+"\" height=\""+fheight+"\"src=\""+rprefix+k+".jpg\"\/><span><img id=panreal"+k+" width=\""+rwidth+"\" height=\""+rheight+"\"src=\""+rprefix+k+".jpg\"\/></span></a>";
			turl = turl + imglnk;
		}
		document.getElementById("panimage").innerHTML = "";
		document.getElementById("panimage").innerHTML = turl;
		highlightCurrent2(twoup_g,nframe_g,oframe_g);

		//Create Panoramic Key
		document.getElementById("pankey").innerHTML = "<div style=\"width:3px;\" class=\"pankeychunk\">&nbsp</div>"; //Clear old
		var kurl = "";
		var kdiv;
		for (var l = 2; l<=80; l++){
			if ((l==1) || ((l%10)==0) ||(l==80)){
				kdiv = "<div style=\"width:"+fwidth+"px;\" class=\"pankeychunk\">"+ l +"</div>";
			}
			else{
				kdiv = "<div style=\"width:"+fwidth+"px;\" class=\"pankeychunk\">&nbsp</div>";
			}
			kurl = kurl + kdiv;
		}
		document.getElementById("pankey").innerHTML = kurl;
		document.getElementsByTagName('meta')[5].content = 1;  //Update Meta that we have a panorama
	}
}

function panPartial(){
	if (xmlHttppan.readyState==4 || xmlHttppan.readyState=="complete"){ //This is the only state we're interested in 4="done"
		var rprefix = xmlHttppan.responseXML.getElementsByTagName("resultprefix")[0].childNodes[0].nodeValue;
		var startimg = xmlHttppan.responseXML.getElementsByTagName("startimg")[0].childNodes[0].nodeValue;
		var stopimg = xmlHttppan.responseXML.getElementsByTagName("stopimg")[0].childNodes[0].nodeValue;
		var spanid;
		for (var k = startimg; k<=stopimg; k++){
			spanid = 'panreal'+k;
			document.getElementById(k).src = rprefix+k+".jpg";
			document.getElementById(spanid).src = rprefix+k+".jpg";	
		}
	}
} 

function loadPartial(workdir,curimg){
	xmlHttppan=GetXmlHttpObject(); //Get AJAX interface
	if (panset_g == 8){
		panset_g = 1;
	} else {
		panset_g = panset_g + 1;
	}
	var url = "inc_wavpanpartial.php" + "?imgnum="+curimg+"&panset="+panset_g+"&workdir="+workdir;
	xmlHttppan.onreadystatechange=function(){
					panPartial();
					};
	xmlHttppan.open("GET",url,true);
	xmlHttppan.send(null);
}	

function panChangeFrame(frame){
	nframe_g = frame;
	procSingleButton("panframe");
	}

function leftChangeFrame(){
	var nframe_gint = parseInt(nframe_g);
	if( nframe_gint == 2 ){
		nframe_g = 80;
	} else{
		nframe_g = nframe_gint - 1;
	}
	procSingleButton("panframe");
}

function rightChangeFrame(){
	var nframe_gint = parseInt(nframe_g);
	if( nframe_gint == 80 ){
		nframe_g = 2;
	} else{
		nframe_g = nframe_gint + 1;
	}
	procSingleButton("panframe");
}

	

function loadPan(curimg){
	xmlHttp=GetXmlHttpObject();	//Get AJAX interface
	if (xmlHttp==null){
		alert ("This browser does not support AJAX");
		return;
	}
	var url = "inc_wavpanorama.php" + "?imgnum="+curimg+"&workdir="+workdir_g;
	xmlHttp.onreadystatechange=function(){
					panChanged();
					};
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

function highlightCurrent2(twoup,imid_new,imid_old){
		if(twoup==0){
			document.getElementById(imid_old).style.border='none';
			document.getElementById(imid_new).style.border='3px red solid';
		}else{
			document.getElementById(imid_old).style.border='none'; //unhighlight old
			var imid_int = parseInt(imid_new);
			var imid_rt;
			if (imid_old == 80){
				document.getElementById(2).style.border='none'; //unhighlight old
			} else {
				var imid_ort = parseInt(imid_old) + 1;
				document.getElementById(imid_ort).style.border='none'; //unhighlight old
			}	
			if (imid_int == 80){ //Wrap around case
				imid_rt = 2;
			} else {
				imid_rt = imid_int + 1 ;
			}
			document.getElementById(imid_new).style.borderWidth='3px 0px 3px 3px';
			document.getElementById(imid_new).style.borderColor='red';
			document.getElementById(imid_new).style.borderStyle='solid';
			document.getElementById(imid_rt).style.borderWidth='3px 3px 3px 0px';
			document.getElementById(imid_rt).style.borderColor='red';
			document.getElementById(imid_rt).style.borderStyle='solid';
		}	
}

function loadFirstImage() {
	//fix nasty race condition that leaves image window blank while pan is processed
	var dopan = document.getElementsByTagName('meta')[5].content;
	document.getElementsByTagName('meta')[5].content = 0;  //Avoid javascript error on first load race condition
	//Grab initial settings, assign to globals, don't grab again.
	nimage_g = document.getElementsByTagName('meta')[1].content;
	nframe_g = document.getElementsByTagName('meta')[2].content;
	oframe_g = nframe_g;
	workdir_g = document.getElementsByTagName('meta')[6].content;
	anglespeed_g=document.getElementsByTagName('meta')[9].content;
	timespeed_g=document.getElementsByTagName('meta')[10].content;
	twoup_g = document.getElementsByTagName('meta')[12].content;
	procSingleButton("first");
	if (dopan==1){
		showLoading();
		setTimeout("loadPan(nimage_g)",500); //Give browser 400ms to load first image
	}
}

function showLoading() {
	var loadhtml = 'Loading Full View <img src="./wimages/loading.gif" alt="Loading Full View">';
	document.getElementById("panimage").innerHTML = loadhtml;
}
	
/*****************************************************************
                      AJAX stuff
******************************************************************/

function GetXmlHttpObject(){
	var xmlHttp=null;
	try{
	  // Firefox, Opera 8.0+, Safari
	  xmlHttp=new XMLHttpRequest();
 	 }
	catch (e){
  	// Internet Explorer
 	 try{
    		xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    	}
  	catch (e){
    		xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    	}
  	}
	return xmlHttp;
}

