var sel=false, no_tbar=false, inversable=true, shift_down=false, ctrl_down=false, alt_down=false, zoomee=false, kbsc=true;

function normal_over() {return $('thct').cur.normal_over}

function rem(o) {
	if(!o) o=[sel]
	else if(o.constructor!=Array) o=[o]

	each(o, function(e) {
		if(typeof e=='string') e=$(e) 
		if(e&&!e.on_tbar) {
			if(e.broken&&e.opened_ids) rem(e.opened_ids)
			e.parentNode.parentNode.removeChild(e.parentNode)
			if(e==sel) sel=false
			if(e.is_thmb) {
				$('thct').cur.onscreen_thmbs = $('onscreen_thmbs').innerHTML = $f($('onscreen_thmbs').innerHTML)-1+''
				if(!e.opened) $('thct').cur.unopened_thmbs = $('unopened_thmbs').innerHTML = $f($('unopened_thmbs').innerHTML)-1+''
				e.hidden_img.src=''
			}
			else {
				clearInterval(e.check_broken)
				e.childNodes[1].src='abort', e.childNodes[1].aborted=true
				ELZR.display.hover('out');
				if($('imgs').innerHTML.match(/^(\s*\<div\>\s*\<\/div\>\s*)\1*\<br clear\=\"all\"\>$/)) $('imgs').innerHTML=''
			}
		}
	})
}
function intellizoom()	{
	if(zoomee&&!zoomee.on_tbar) {
		var d = -(x.now-x.old)/1000 //delta
		if(d!=0) zoomer(1-d, zoomee)	
	}
}
function intellizoom_off()	{ 
	if(zoomee) {disable_select(false); zoomee.imagxo.style.cursor='pointer'; zoomee=false}
}
function zoomer(md, s) {
	s = s||sel
	var i = s.imagxo, h = $f(i.style.height||s.h), w = $f(i.style.width||s.w)
	
	if(md>1) { if((h<20000)&&(w<20000)) zoom(md, h, w, s) }
	else if(md<1) {if((h>50)&&(w>50)) zoom(Math.max(md, 0), h, w, s)}
	else {zoom(md, s.h, s.w, s)}
}
function zoom(p, h, w, s) {
	s.tbar.style.top='-31px'
	var i=s.imagxo
	if(!s.verified) return;
	i.style.height = h*p + 'px', i.style.width = w*p + 'px' 
	s.style.height = h*p + 2 + 'px', s.style.width = w*p + 2 + 'px'
	s.tbar.style.width = w*p < 210 ? 212 : (w*p+2)
	s.tbar.lastChild.style.left = $f(s.tbar.style.width)-210
}
function fit() {
	var i=sel.imagxo
	if(!sel.verified) return;
	zoomer(Math.min(($f(window.innerHeight)-10)/$f(i.style.height||sel.h), ($f(window.innerWidth)-30)/$f(i.style.width||sel.w)))
	if(sel.fit=!sel.fit) sel.tbar.style.top=0
	write_location('#'+i.parentNode.id)
}
function write_location(str) { location=location.toString().replace(/\#?.*$/, str) }
function linger() {
	sel.style.borderColor = 'firebrick'
	setTimeout("$('"+sel.id+"').style.borderColor='#ccc'", 300)
}
function check_broken(id) {
	var o = $(id)
	if(($f(o.imagxo.height)<o.h)||($f(o.imagxo.width)<o.w)) { o.imagxo.complete&&broken(o) }
	else { 
		clearInterval(o.check_broken)
		o.verified = true
	}
}
function broken(o) { 
	var i = o.imagxo, t = $(o.thmbid)
	i.style.height = o.h, i.style.width = o.w
	if(t) {
		t.ghost.style.background = 'url(/images/imagery/broken.gif)'
		t.broken = true
	}
	o.broken = true
}
function source() { window.open(sel.refurl)}
function new_win() { 
	var h = $f(sel.h)+20, w = $f(sel.w)+20
	var ww = open(sel.imgurl, 'w'+(Math.random()*100), 'width='+w+', height='+h+', resizable')
	if(!ww) alert("Grr! A popup blocker may be preventing the image from opening in a new window.")
}
function img_load(o, url) {
	o.hidden_img = new Image()
	o.hidden_img.src = url
	o.hidden_img.onload = function() {
		o.style.backgroundImage = 'url('+o.hidden_img.src+')', o.loaded = true
		if(normal_over()||!o.over) {
			var temp_shift = shift_down, temp_ctrl = ctrl_down
			shift_down = false, ctrl_down = false
			o.onmouseout();
			shift_down = temp_shift, ctrl_down = temp_ctrl
		}
	}
	no_tbar = true; 
	if(normal_over()||!o.over) {o.onmouseover()};
	no_tbar = false
}
function img_error(o) { if(!o.aborted) { o.src='/images/imagery/sorry.gif', broken(o.parentNode) } }
function ini(o, p) {
	if(!o.h) {
		o.h = p.h, o.w = p.w, o.refurl = p.refurl, o.imgurl = p.imgurl, o.sz = p.sz
			if(!o.firstChild) {
				o.onclick = function() {sel.broken ? rem(sel) : (shift_down ? false : add_img())}
				for(var i=0;i<=4;i++) {o.appendChild(document.createElement('div'))}
				o.ghost = o.childNodes[0], o.ghost.className = 'ghost'
				o.gray = o.childNodes[1], o.green = o.childNodes[2]
				o.tbar = o.childNodes[3], o.tbar.className = 'tbar'
				o.canvas = o.childNodes[4], o.canvas.className = 'canvas'
				o.is_thmb = true
				
				o.tbar.onclick = function() {sel.on_tbar = true}
			}
			else {
				o.style.height = p.h+2, o.style.width = p.w+2, o.thmbid = p.id, o.thmbh = $f(p.style.height), o.thmbw = $f(p.style.width), o.thmburl = p.style.backgroundImage
				o.tbar = o.childNodes[0], o.imagxo = o.childNodes[1]
				o.onclick = function() {
					if(sel.broken) rem([sel, sel.thmbid])
					else if(shift_down) rem()
				}
				o.onmousedown = function(e) { if((!(e.button==2))&&!zoomee) {disable_select(true); zoomee=this; zoomee.imagxo.style.cursor='e-resize'} }
				o.ondblclick = function() {sel.broken ? rem([sel, sel.thmbid]) : (sel.on_tbar ? false:fit())}
				o.tbar.onclick = function() {sel.on_tbar = true}
			}
	}
}
function over(o) { 
	(sel=o).overNow = true
	if(ctrl_down || shift_down) return;
	normal_over() ? over_(o) : out_(o)
}
function over_(o) {//#h1, w1 are the thumbnail height, width; h2, w2 are the image height, width; h3, w3 are the window height, width
	over2_(o)
	if(!o.overed) {
		var h1=$f(o.style.height)-2, h2=$f(o.h), h3=$f(window.innerHeight)
		var w1=$f(o.style.width)-2, w2=$f(o.w), w3=$f(window.innerWidth)

		scale(h1, h2, h3, w1, w2, w3, o.gray, o.green)
		center(o.gray, o.green, h1, w1)
		order(o.gray, o.green)
		o.overed = true
	}
}
function over2_(o) {
	if(o.loaded) {
		ELZR.display.hover(normal_over() ? 'over' : 'out');
		o.gray.style.display = o.green.style.display = 'block'
		o.canvas.style.visibility = 'visible'
		o.on_tbar = false
	}
}
function out(o) {
	o.overNow = false
	if(ctrl_down || shift_down) return;
	ELZR.display.toolbar.out(o);
	normal_over()? out_(o) : over2_(o)
}
function out_(o) {
	ELZR.display.hover(normal_over() ? 'out' : 'over');
	if(o.loaded) {
		o.gray.style.display = o.green.style.display = 'none'
		o.canvas.style.visibility = 'hidden'
	}
}
add_img.c = 0
function add_img() {
	inversable = false
	if(!sel.on_tbar) {
		$('thct').cur.unopened_thmbs = $('unopened_thmbs').innerHTML = $f($('unopened_thmbs').innerHTML)-1, sel.opened = 'true'
		sel.opened_ids = ['i'+add_img.c].concat(sel.opened_ids ? sel.opened_ids : [])
		var imgs = $('imgs')
		if(imgs.innerHTML=='') imgs.innerHTML='<br clear="all">'
		sel.ghost.style.visibility = 'visible'
		linger()
		imgs.insertBefore(document.createElement("div"), imgs.firstChild)
		imgs.firstChild.innerHTML = '<div class="i"><div id="i'+add_img.c+'" onmousemove="this.overNow=true" onmouseover="sel=this; ELZR.display.toolbar.over(); ELZR.display.hover()" onmouseout="ELZR.display.toolbar.out(this); ELZR.display.hover(\'out\'); sel.overNow=false"><div class="tbar"></div><img src="'+sel.imgurl+'" class="img" onerror="img_error(this)"/></div></div>'
		ini($('i'+add_img.c), sel)
		$('i'+add_img.c).check_broken = setInterval('check_broken(\'i'+add_img.c+'\')', 250)
		add_img.c++
	}
}
function all_over() {
	no_tbar = true
		$('thct').cur.normal_over = !normal_over()
	no_tbar = false
}
function over_reset() {
	if(!$('thct').cur) return;
	no_tbar = true
		each($('thct').cur.childNodes, function(e) {(e.firstChild)&&(e.firstChild.overed = false)})
	no_tbar = false
}
function scale(h1, h2, h3, w1, w2, w3, one, two) {
	var hscale = (h1*h2)/h3, wscale = (w1*w2)/w3

	two.style.background="#69BF14"
	one.style.height = h1, 		one.style.width = w1
	two.style.height = hscale, 	two.style.width = wscale

	if(hscale > h1) {two.style.background="firebrick"; one.style.height=hscale*(h3*h3)/(h2*h2); two.style.height = h1}
	if(wscale > w1) {two.style.background="firebrick"; one.style.width=wscale*(w3*w3)/(w2*w2); two.style.width = w1}
}
function center(one, two, h, w) { 
	var c_ = function(smallh, bigh) {return Math.floor((bigh-$f(smallh))/2)}
	one.style.top = (c_(one.style.height, h)- h-3) + 'px', 						one.style.left = c_(one.style.width, w) + 'px'
	two.style.top = (c_(two.style.height, h)-$f(one.style.height)-4-h)+'px', 	two.style.left = c_(two.style.width, w) + 'px'
	two.nextSibling.nextSibling.style.top = -$f(one.style.height) -$f(two.style.height) -38 - h + 'px'
}
function order(one, two) { 
	var a1 = $f(one.style.height)*$f(one.style.width), a2 = $f(two.style.height)*$f(two.style.width)
	if(a1<a2) { one.style.zIndex=4; two.style.zIndex=3}
	else { one.style.zIndex=3; two.style.zIndex=4}
}
function params(md, p) {
	if(p) return p
	else {
		var c = $('thct').cur
		var q = 'q='+(md ? c.query : $('q').value),
		    safe = '&safe='+$('safe').value,
			imgsz = '&imgsz='+$('imgsz').value,
			imgc = '&imgc='+$('imgc').value,
			strt = (md ? ('&start=' + c.strt) : ''), 
			total = (md ? ('&total=' + c.total) : ''), 
			tanu = '&tab='+(md? c.tab.tanu: $('tact').tanu)
		return q+strt+total+safe+imgsz+imgc+tanu
	}
}
function after_results_back(qu, resSize, resTotal, tab) {
	if(($f(resTotal)>0)&&(resSize>0)) update_header(false, tab, qu, resSize, resTotal)
	else $('header').style.display='none'
}
function update_header(md, tab, qu, resSize, resTotal) {
	var c = $(typeof tab=='string'?('th'+tab):tab)
	if(!md) {
		c.query = qu
		c.onscreen_thmbs = $f(c.onscreen_thmbs||0) + $f(resSize)
		c.unopened_thmbs = $f(c.unopened_thmbs||0) + $f(resSize)
		c.total = resTotal
		c.strt = c.strt||0
		if((c.strt>0)&&!normal_over()) {all_over(); all_over()}
		c.strt = c.strt+resSize
	}
	if(c==$('thct').cur) {
		$('queryDisplay').innerHTML = c.query
		$('onscreen_thmbs').innerHTML = c.onscreen_thmbs
		$('unopened_thmbs').innerHTML = c.unopened_thmbs
		$('total').innerHTML = c.total
	}
	$('header').style.display= $f($('total').innerHTML)>0 ? 'block' : 'none'
}
function keyDown(e) {
	if(e.shiftKey) {
		if(sel.overNow) { sel.onmouseout(); sel.overNow=true }
		shift_down = true
	}
	if(e.altKey) alt_down = true
	if(e.which==27) $('q').blur()
}
function keyUp() {
	shift_down = false, alt_down = false
	window.status=''
	x.halt(), y.halt()
}
function keyPress(e) {
	var k = e.which
	if(kbsc) {
		if(sel&&!sel.is_thmb) {
			if(k==43)	zoomer(1.1)
			else if(k==45) zoomer(0.9)
			else if(k==48) zoomer(1)
			else if(k==70 || k==102) fit()
		}
		if(k==73 || k==105) 		$('thct').onclick()
		else if(k==68 || k==100)	sel.overNow&&rem()
		else if(k==44)				move_tab('previous')
		else if(k==46) 				move_tab('next')
		else if(k==113)				{$('q').focus();$('q').select()}
		else if(k==83 || k==115) 	sel.overNow&&source()
		else if(k==78 || k==110)	sel.overNow&&new_win()
		else if(k==80 || k==112)	(!e.altKey)&&fold('plus', 'prfs')
	}
}
function correct_location() {
	var nl = location.toString().replace(/\#[^\#]*$/, '')
	if(location.toString()!=nl) {location = nl}
}
correct_location();
function thmb_del_on() {
	if(shift_down) {
		var t = $('thmb_del')
		t.style.display='block'
		t.on=true
		t.style.top = y.now, t.style.left = x.now
		t.style.width = 0, t.style.height = 0, t.x2 = 0, t.y2 = 0
		inversable = false
	}
}
function thmb_del() {
	var t=$('thmb_del')
	if(shift_down&&t.on) {
		var nw = $f(x.now)-$f(t.style.left), nh = $f(y.now)-$f(t.style.top)
		t.style.width = $a(nw)+'px', t.style.height = $a(nh)+'px'
		t.style.marginLeft = (nw<0 ? nw : 0) +'px', t.style.marginTop = (nh<0 ? nh : 0) +'px'
		t.x2 = nw, t.y2 = nh
		check_within()
		if(t.toDelete.length>0) {
			window.status = t.toDelete.length+' thumbnails selected.'
			$('holding').innerHTML = '<b>'+t.toDelete.length+'</b> thumbnails selected.'
		}
		inversable = false
	}
}
function thmb_del_off() {
	var t = $('thmb_del')
	if(t.on) {
		each($('thct').cur.childNodes, function(e) {
			if(e.className=='t') {
				var div = e.firstChild
				if(!(div.opened||div.broken)) div.ghost.style.visibility = 'hidden'
				div.ghost.style.backgroundColor = 'white'
			}
		})
		t.style.display='none'
		if(shift_down) {
			check_within()
			rem(t.toDelete)
		}
		t.toDelete=t.on=false
		ELZR.display.hover('out');
		if(sel.constructor==Array) (sel=false)
	}
}
function check_within() {
	var t = $('thmb_del')
	var x1 = $f(t.style.left), y1 = $f(t.style.top)
	var x2 = x1+t.x2, y2 = y1+t.y2
	if(x1>x2) {var tx = x1; x1 = x2; x2 = tx}
	if(y1>y2) {var ty = y1; y1 = y2; y2 = ty}
	if(t.x2==0 && t.y2==0) return; 
	t.toDelete = []
	each($('thct').cur.childNodes, function(e) {
		if(e.className=='t') {
			var div = e.firstChild
			var xa = find_pos('x', div), 		ya = find_pos('y', div)
			var xb = xa+$f(div.style.width), 	yb = ya+$f(div.style.height)
			var l1 = int_sum(xa, xb, x1, x2),	l2 = int_sum(ya, yb, y1, y2)
			if((l1[0]-l1[1])*(l2[0]-l2[1])!=0) {
				div.ghost.style.visibility='visible'
				div.ghost.style.backgroundColor='#EFFF84'
				t.toDelete.push(div)
			}
			else {
				if(!(div.opened||div.broken)) div.ghost.style.visibility='hidden'
				div.ghost.style.backgroundColor='white'
			}
		}
	})
}
function find_pos(axis, obj) {
	var attr = axis=='x'?'offsetLeft':'offsetTop', cur = 0
	if (obj.offsetParent) while (obj.offsetParent) { cur += obj[attr], obj = obj.offsetParent }
	return cur
}
function int_sum(ma, mb, m1, m2) { //interval sum
	if($a(ma)<$a(m1)) {
		ma = m1; if($a(mb)<$a(m1)) mb = m1
	}
	if($a(mb)>$a(m2)) {
		mb = m2; if($a(ma)>$a(m2)) ma = m2
	}
	return [ma, mb]
}
function add_tab(md) {
	thct = $('thct');
	if(md!='first') {
		var nwth = document.createElement('div')
		nwth.className = 'thmbs', thct.appendChild(nwth)
	}
    else var nwth = $('nwth')

    thct.cur = nwth; thct.cur.normal_over = true;
	var nwta = document.createElement('div'), tact = $('tact');
	thct.cur.id = 'th'+(nwta.tanu = tact.tanu = (tact.tanu? (tact.tanu+1) : 1)), tact.appendChild(nwta), nwta.className="tab",  nwth.tab=nwta, nwta.thmbs = nwth;

	var a = document.createElement('a'); nwta.appendChild(a), a.innerHTML = $('q').value;
	a.onclick = tab_change
}

var tab_change = function() {
	each($('tact').childNodes, function(e) {e.className='tab'});
	this.parentNode.className = 'selTab';

	each($('thct').childNodes, function(e) {e.className='thmbs'});
	$('thct').cur = this.parentNode.thmbs;
	$('thct').cur.className = 'selThmbs';
	update_header(true, this.parentNode.thmbs);
	ELZR.display.hover('out');
	if(this.parentNode.thmbs.been_resized) reSz();
	document.title='Imagery: '+this.innerHTML;
}
function rem_tab() {
	var thct = $('thct'); t = thct.cur.tab, tact = $('tact');
	thct.removeChild(thct.cur);
	thct.cur = false;
	if(t.previousSibling) t.previousSibling.firstChild.onclick();
	else if(t.nextSibling) t.nextSibling.firstChild.onclick();
	tact.removeChild(t);
	if(tact.childNodes.length<2) tact.parentNode.style.display='none';
}
function move_tab(dir) {
	var tact = $('tact');
	if(tact.childNodes.length<2) return;
	var c=$('thct').cur.tab;
	if(dir=='next') var toMove = c.nextSibling||tact.firstChild;
	else var toMove = c.previousSibling||tact.lastChild;
	toMove.firstChild.onclick();
}
function hide_opened() { each($('thct').cur.childNodes, function(e) {if(e.firstChild&&e.firstChild.opened) e.style.display='none'}) }
function show_all() { each($('thct').cur.childNodes, function(e) {if(e.tagName=='DIV'||e.tagName=='div') e.style.display='block'}) }
function dym(o, q) {
	inversable = false;
	o.parentNode.style.display='none';
	var old_q = $('q').value;
	if(!$('thct').cur.total) rem_tab();
	$('q').value = q;
	$('form').onsubmit();
	$('q').value = old_q;
	return false;
}
function onReSz() {
	x.range = innerWidth, y.range = innerHeight;
	each($('tact').childNodes, function(e) {e.thmbs.been_resized=true} );
	reSz();
}
function reSz() { if($('thct').cur) {over_reset(); all_over(); all_over(); $('thct').cur.been_resized=false} }
document.captureEvents(Event.MOUSEMOVE);
document.onmousemove = function(e) {
	x.now = Math.max(0, e.pageX-pageXOffset), y.now = Math.max(0, e.pageY-pageYOffset);
	setTimeout('x.old='+x.now+'; y.old='+y.now, 100);
	navi(), thmb_del(), intellizoom();
}
function next_button(tab) {
	var f = document.createElement('form')
	f.className='next'; f.onclick = function() {if(!this.nonext) next_imgs()}; f.onmousemove = function() {this.nonext=false}
	f.innerHTML = '<select onclick="inversable=false; this.parentNode.nonext=true"><option value="20">20</option><option value="40">40</option><option value="60">60</option><option value="80">80</option><option value="100">100</option></select>'
	$('th'+tab).next = f; $('th'+tab).appendChild(f);
}

