// phCommon.js
//
// Note the notion of "standard image based editing", which
// puts a stricter standard on the use of these javascript functions
// for html files created starting with the rhapsody log files ...

var USE_MAP_WINDOW = true; // (docloc.match("localhost"))?true:false;
var HIDE_OLD_CHARTS = false; // (docloc.match("localhost"))?true:false;
var MAP_AUTO_RESIZE = true; // (docloc.match("localhost"))?true:false;

var IMG_TITLE_HEIGHT = 32;
var pageImages = new Array;
var next_index;
var prev_index;

var map_window = null;
var infocus = false;

setCookie("test_cookie",1);
var supportsCookies = (getCookie("test_cookie")=="1");
var isIE = (navigator.appName == 'Microsoft Internet Explorer');
var isIE8 = (isIE && document.documentMode && (document.documentMode==8));
var supports_map_window = (supportsCookies && (!isIE || isIE8));

// could not get it working well,
// so we just use a constant window size on IE

if (isIE) MAP_AUTO_RESIZE = false;


//------------------------------------
// slideShow support
//------------------------------------

function pageImage(filename,caption)
{
	this.index = pageImages.length + 1;
	this.filename = filename;
	caption = caption.replace(/\[.*?\]/g,"");
	this.caption = caption;
}

function addPageImage(filename,caption)
{
	var pi = new pageImage(filename,caption);
	pageImages.push(pi);
	return pi;
}

function sizeDiv(div,x,y,w,h)
{
	div.style.left = x + "px";
	div.style.top = y + "px";
	div.style.width = w + "px";
	div.style.height = h + "px";
}

function createDiv(id,width,top,height)
{
	var div = document.createElement("div");
	div.id = id;
	div.style.position = "absolute";
	sizeDiv(div,0,top,width,height);
	return div;
}

function createButton(label,class_name,type_data,onclick,title)
{
	var div = document.createElement("div");
	div.innerHTML = label;
	div.className = class_name;
	div.type_data = type_data;
	div.title = title;
	div.onclick = onclick;
	return div;
}


function slideShow(index)
{
	var body = document.body; 
	body.style.overflow = "hidden";
	var body_width = body.clientWidth;
	var body_height = body.clientHeight;

	var img_title = createDiv('img_title',body_width,0,IMG_TITLE_HEIGHT);
	img_title.innerHTML = "&nbsp;&nbsp;"+document.title + "<br><span id='img_title_text'></span>";
	img_title.appendChild(createButton(
		"X","button_img_close","",closeSlideShow,
		"Close picture and go BACK to the previous page"));

	if (pageImages.length > 1)
	{
		img_title.appendChild(createButton(
			"&lt;","button_img_prev","",prevSlide,
			"Go to the previous picture"));
		img_title.appendChild(createButton(
			">","button_img_next","",nextSlide,
			"Go to the next picture"));
	}

	body.innerHTML = "";
	body.appendChild(img_title);

	var img_div = createDiv('img_div',body_width,IMG_TITLE_HEIGHT,body_height-IMG_TITLE_HEIGHT);
	img_div.resizeSlideShow = resizeSlideShow;
	img_div.style.overflow = "auto";
	body.appendChild(img_div);

	loadImage(index);
}


function loadImage(index)
{
	var pi = pageImages[index-1];
	var display_name = pi.filename.replace(/.*\//g,"");
	
	var len = pageImages.length;
	index = parseInt(index);
	next_index = index + 1;
	prev_index = index - 1;
	if (next_index>len) next_index = 1;
	if (prev_index<1) prev_index = len;
	
	var img_div = document.getElementById("img_div");
	var img_title_text = document.getElementById("img_title_text");
	
	img_title_text.innerHTML = 
		"&nbsp; " +
		"<span class='small'>" +
		display_name +
		" &nbsp; " +
		"(" + index + "/" + len + ")" +
		 " &nbsp;&nbsp; " +
		pi.caption +
		"</span>";
	
	var img = document.createElement("img");
	img.div = img_div;
	img.scaling = 1;
	img.style.position = "absolute";
	img.onclick = clickOnSlide;
	img.title = pi.caption;
	// img.style.display = "none";
	img.style.position = "absolute";
	img.className = "te_link";
	img.onclick = clickOnSlide;
	img_div.image_loading = img;
	img.src = pi.filename;
	
	setTimeout("resizeSlideShowOnLoad();",300);
}


function resizeSlideShowOnLoad()
{
	var img_div = document.getElementById("img_div");
	var img = img_div.image_loading;
	if (img.complete && 
		img.height && 
		img.width && 
		(img.height > 60) && 
		(img.width > 60))
	{
		img.org_height = img.height;
		img.org_width = img.width;
		img_div.image_loaded = img;
		img_div.resizeSlideShow();
		img_div.innerHTML = "";	
		img_div.appendChild(img);
	}
	else
		setTimeout("resizeSlideShowOnLoad()" ,300);
}


function resizeSlideShow()
{
	var img = this.image_loaded;
	if (!img) return;
	var win_width = this.offsetWidth;
	var win_height = this.offsetTop + this.offsetHeight - IMG_TITLE_HEIGHT;
	if ((win_height >= img.org_height) &&
		(win_width >= img.org_width))
	{
		img.height = img.org_height;
		img.width = img.org_width;
	}
	else 
	{
		var aspect_high = 1;
		var aspect_wide = 1;
		if (img.scaling>0)
		{
			aspect_high = win_height / img.org_height;
			aspect_wide = win_width / img.org_width;
		}
		if (aspect_high < aspect_wide)
		{
			img.height = img.org_height*aspect_high;
			img.width = img.org_width*aspect_high;
		}
		else
		{
			img.height = img.org_height*aspect_wide;
			img.width = img.org_width*aspect_wide;
		}
	}
}


function clickOnSlide()
{
	if (this.scaling>0) this.scaling=0; else this.scaling=1;
	this.div.resizeSlideShow();
}

function prevSlide()
{
	loadImage(prev_index);
}

function nextSlide()
{
	loadImage(next_index);
}

function closeSlideShow()
{
	history.go(-1);
}


function onResizeSlideShow()
{
	var img_div = document.getElementById("img_div");
	if (img_div)
	{
		var img_title = document.getElementById("img_title");
		var body_width = document.body.clientWidth;
		var body_height = document.body.clientHeight;
		sizeDiv(img_title,0,0,body_width,IMG_TITLE_HEIGHT);
		sizeDiv(img_div,0,IMG_TITLE_HEIGHT,body_width,body_height-IMG_TITLE_HEIGHT);
		img_div.resizeSlideShow();
	}
}


//------------------------------------------------
// Misc
//------------------------------------------------

function onFocusCommon()
	// Anytime we get the focus, bring up the map window if it's open
	// The only time I've been able to determine that this does not
	// work is one attempts to minimize the map_window.  It then 
	// returns focus which restores it and causes an endless loop.
	// So, we detect if the window is minimized (height<=24), and
	// don't do the focus stuff if it is. Does not work on IE8.
{
	if (!isIE &&
		!infocus && 
		this.map_window && 
		(this.map_window.initialized==237) &&
		(this.map_window.outerHeight > 24))
	{
		// alert("focus child");
		infocus = true;
		this.map_window.focus();
		this.focus();
		infocus = false;
	}
}


function onResizeCommon()
	// to resize the map window when parent resize
{
	onResizeSlideShow();
	if (MAP_AUTO_RESIZE && this.map_window && (this.map_window.initialized==237))
	{
		var newpos = determineMapWindowPos()
		map_window.moveTo(newpos.x,newpos.y);
		map_window.resizeTo(newpos.w,newpos.h);
	}
}


function toggleRhapsodyBreak(part_num,menu_id,toggle_param)
	// intercept a press on a "part" in the outline
	// to notify map window of the context change
{
	toggleItem(menu_id,toggle_param);
	if (map_window && map_window.initialized==237)
	{
		var dataset = mi[dataset_index].split(",")[2];
		map_window.mapPane.setContext(true,dataset,"part",part_num);
	}
}



//----------------------------------
// map window 
//----------------------------------

function rect(x,y,w,h)
{
	this.x = x;
	this.y = y;
	this.w = w;
	this.h = h;
}


function determineMapWindowPos(for_open)
	// determine the desired position of the map window
	// used during the initial open, and if MAP_AUTO_RESIZE
	// when the user resizes the browser. 
	// Jury rigged for IE.
{	
	var x,y,h,w;
	var screen_w = window.screen.width;
	var screen_h = window.screen.height;
	
	// get the size of the current browser window
	// for FF this appears to truly be the browser window size
	
	if (!isIE)   // if (window.screenX)	// ff, etc
	{
		x = window.screenX; 
		y = window.screenY; 
		w = window.outerWidth;
		h = window.outerHeight;
	}		
	
	// of course, for IE, it's all f'd up
	// never mind the details ...
		
	else					
	{
		x = window.screenLeft - 15;
		y = window.screenTop - 109;
		w = document.documentElement.clientWidth + 20;
		h = document.documentElement.clientHeight + 80;
	}
	
	// Given the correct size of the browser window,
	// determine size and position of map window
	// We want it to be a minimum of 300px wide and high,
	// and to appear somewhat "attached" to the browser window:
	//
	// - it's top and height should be the same as the browser window.
	// - if possible, it's right edge should connect with the left 
	//   edge of the browser window.
	// 
	// And we want it, with the browser window, to appear
	// centered on the screen.  In other words, whatever space
	// there is to the right of the browser window should also
	// exist to the left of the map window.
	
	var right_space = screen_w - (x+w);
	if (right_space < 0) right_space = 0;
	w = x - right_space;
	if (w<300) w = 300;
	if (h<300) h = 300;
	x -= w;		
	return new rect(x,y,w,h);
}


function openMap()
	// short ending if called on a page that has no dataset.
	// in practice this happens if user opens window and changes pages out of set
{
	// open the window
		
	setCookie("map_opened","1");
	var position = determineMapWindowPos(true);
	map_window = top.open(
			'', 						// url
			"mapWindow",			    // name
			"left=" + position.x + "," +
			"top=" + position.y +"," +

			// for FF, outerXXX eliminates calcs of map_window chrome
			// still haven't got IE working
			
			(isIE ? "width=" + position.w + "," : "") + 
			(isIE ? "height=" + position.h + "," : "" ) +
			((!isIE) ? "outerWidth=" + position.w + "," : "") + 
			((!isIE) ? "outerHeight=" + position.h + "," : "") +
			
			"buttons=no," +
			"scrollbars=no," +
			"location=no," +
			"menubar=no," +
			"resizable=yes," +
			"status=no," +
			"directories=no," +
			"toolbar=no," );	

	// we don't bother to call the map window if the dataset index <> 0
	
	if (map_window.initialized == 237)
		map_window.mapPane.setContext(true,cur_dataset,"page",page_id);
	else
		map_window.document.location = "/common/map_window.html?"+cur_dataset+":page:"+page_id;
		
	displayMaps("none");
}


function closeMap()
{
	setCookie("map_opened","");
	displayMaps("block");
	if (map_window != null)
	{
		map_window.close();
		map_window = null;
	}
}


function initializeMap()
{
	// no map window for pre-8 IE or when we are on 
	// a page that is not part of a dataset
	
	if (!supports_map_window || (cur_dataset == ""))
	{
		USE_MAP_WINDOW = false;
		HIDE_OLD_CHARTS = false;
	}
	
	if (USE_MAP_WINDOW && getCookie("map_opened")) 
		openMap();
}


function displayMaps(how)
{
	if (HIDE_OLD_CHARTS)
	{
		var divs = document.getElementsByTagName("div");
		for (var i=0; i<divs.length; i++) 
		{
			var className = divs[i].className;
			if (className.match(/^ph_map/))
				divs[i].style.display = how;
		}
	}
}


function getUserGeoData(what)
{
	document.location = "../map_data/"+cur_dataset+"."+what;
}

//--------------------------------------
// phCommon 'main'
//--------------------------------------

function processPHDiv(div_className,div)
	// process a ph_image, ph_group, or ph_map div to add elements
	// to slideshow, rewrite the ph_img_link to call the slideshow,
	// and add captions to the end of the div.  For ph_maps go another
	// step and add the blurb at the end and change the link to openMap()
	// as appropriate. 
{			
	var text = div.innerHTML;
	var imgs = div.getElementsByTagName("img");
	
	var next_image = 0;
	var captions = [];
	var links = [];
	var anycaptions = false;
	
	// some variables which assume there is only one map to a map div
	// so that we can yet again override the urls if using the map_window
	
	var map_link;
	var map_slideshow_index = 0;
		
	// build the list of captions and links
	// while replacing the main linkurl for slideshows
	
	for (var i=0; i<imgs.length; i++) 
	{
		var className = imgs[i].className;
		
		// add captions and slideshow entries for maps and images
		
		if (className.match(/ph_img|ph_map/))	// includes noprocess
		{
			var linkurl = "";
			var linkimg = "";
			var parent = imgs[i].parentNode;
			if (parent.nodeName == 'A')		
			{
				var parentClass = parent.className;
				if (parentClass.match(/ph_link_img|ph_link_map/))	// includes noprocess
					linkimg = parent.href;
				else
					linkurl = parent.href;
			}
			
			var caption = imgs[i].title;
			if (caption && caption != "")
				anycaptions = true;

			var index = 0;
			var use_id = "";
			var rslt = linkimg.match(/\/files\/(.*)\//);
			if (rslt) use_id = rslt[1];
			
			// get the page id from the spec, which is full http url.
			// only valid as a slideshow if its a reference to this 
			// page's files directory. we don't validate server 
			// (assume that /files/ is the one we're talking about),
			// and we don't validate the filename part at all.
			
			if (use_id == page_id)	// page_id is a global set in phUtils.js
			{
				var pi = addPageImage(linkimg,caption);
				index = pi.index;
				linkurl = docloc + "?slideShow("+index+")";
				parent.href = linkurl;
				
				map_link = parent;
				map_slideshow_index = index;
			}
							
			captions[next_image] = caption;
			links[next_image] = linkurl;
			next_image++;
		}
	}

	var is_map = div_className.match(/ph_map/);
	
	if (anycaptions)
	{
		var is_group = div_className.match(/ph_group/);
		var container = document.createElement('span');
		container.className = 'ph_image_caption';
		if (is_map) container.className = 'ph_map_title';
		var last_num = 0;
		for (var i=0; i<captions.length; i++)
		{
			var caption = captions[i];
			if ((i < captions.length-1) && (caption == captions[i+1]))
				caption = "";
			if (caption && caption != "")
			{
				if (captions.length > 1)   // was is_group
				{
					for (var j=last_num; j<=i; j++)
					{
						var element;
						var alink = links[j];
						if (alink && alink != "")
						{
							element = document.createElement('a');
							element.href = alink;
						}
						else
						{
							element = document.createElement('span');
						}
						element.innerHTML = "" + (j+1) + ".";
						container.appendChild(element);
					}
					last_num = i+1;
				}
				caption = caption.replace(/\[/g,"<");
				caption = caption.replace(/\]/g,">");
				caption = caption.replace(/ /g,"&nbsp;");
				var span = document.createElement('span');
				span.innerHTML = "&nbsp;" + caption + "&nbsp;&nbsp; ";
				container.appendChild(span);
			}
		}	// foreach caption
		
		div.appendChild(container);
		
	}	// anycaptions
	
	// add the extra stuff for maps
	
	if (is_map)
	{
		var text = "";
		if (USE_MAP_WINDOW)	
		{
			map_link.href = 'javascript:openMap();';
			
			text += "Click on the image above for a Live Map!!<br>";
	 		text += "<a href='"+docloc+"?slideShow("+map_slideshow_index+")'>Big_Image</a>";
			text +=	" &nbsp; ";
			text += "<a href='javascript:openMap()'>Live_Map</a>";
			text +=	" &nbsp; ";
		}
		else
		{
			text += "Click on the map above for a bigger version<br>";
		}
			
		text += "<a href='javascript:getUserGeoData(\"kml\")'>KML</a>";
		text +=	" &nbsp;&nbsp; ";
		text += "<a href='javascript:getUserGeoData(\"gpx\")'>GPX</a>";

		var span = document.createElement('span');
		span.className = 'ph_map_extra';
		span.innerHTML = text;
		div.appendChild(span);
	}
		
}	// processPHDiv



function processPHDivs()
	// process any of my special divs
{
	var divs = document.getElementsByTagName("div");
	for (var i=0; i<divs.length; i++) 
	{
		var className = divs[i].className;
		if (className.match(/^ph_image|^ph_group|^ph_map/))	// includes justifications
			processPHDiv(className,divs[i]);
	}
}


function initializeCommon()
{
	processPHDivs();
}




