// ilanio.js


// globals

var	curPageName ;
var	fadeList = new Array() ;


// constants
var	kDefaultFadeMS = 400 ;
var	kThumbWidth = 98 ;
var	kThumbsPerRow = 7 ;


function ilanioInit(pageName)
{
	checkBrowser() ;

	curPageName = pageName ? pageName : "undefined" ;
	if (pageName)
		initExpandState() ;

	// necessary to keep content centered on _outer_ width of window, so that appearance of scroll bars doesn't shift content 
	if (!isOldMSIE)
		myAddEventListener(window, "resize", function() { document.getElementById('hdr_div').style.marginLeft = getHdrLeftMargin() + 'px'} ) ;
}

function writeHdrDiv()
{
	var	s = "<div id='hdr_div' style='display: block; width: 800px; margin-left: " ;

	checkBrowser() ;
    if (!isOldMSIE)
		s += getHdrLeftMargin() + "px; " ;
	else
		s += "auto; margin-right: auto; padding-left: 150px; padding-right: 150px; " ;
	s += "margin-top: 100px;'>" ;
	document.write(s) ;
}

function getHdrLeftMargin()
{
	return (parseInt(Math.max(150, (window.outerWidth - 800) / 2))) ;
}

function fadeObj(id, startOpacity, endOpacity, time, steps)		// time in ms
{
	var	i, ms, opacity ;

	for (var i = ms = 0, opacity = startOpacity ; i < steps ; ms = Math.round(ms + time / steps), ++i)
	{
		opacity += (endOpacity - startOpacity) / steps ;
		if (i == steps - 1)
			opacity = endOpacity ;
		setTimeout("setEltOpacity(document.getElementById('" + id + "'), " + opacity + ")", ms) ;
	}
}

function fadeIn(id, time)			// time in ms
{
	if (!time)
		time = kDefaultFadeMS ;

	fadeObj(id, 0, 1, time, 10) ;
}

function fadeOut(id, time)			// time in ms
{
	if (!time)
		time = kDefaultFadeMS ;

	fadeObj(id, 1, 0, time, 10) ;
}

function newFade(id, startMS)
{
	var	startOpacity = parseFloat(document.getElementById(id).style.opacity) ;
	var	i ;

	cancelFade(id) ;		// just in case it was in the fade list already

	if (!startOpacity)
		startOpacity = 1 ;

	for (i = 0 ; i < fadeList.length ; i += 2)		// look for an empty slot
		if (fadeList[i] == '')
			break ;

	fadeList[i] = id ;
	fadeList[i + 1] = setTimeout("updateFade(" + i + ", 0, " + startOpacity + ")", startMS) ;
}

function updateFade(i, step, startOpacity)
{
	++step ;
	setEltOpacity(document.getElementById(fadeList[i]), (10 - step) / 10 * startOpacity) ;
	if (step < 10)
		fadeList[i + 1] = setTimeout("updateFade(" + i + ", " + step + ", " + startOpacity + ")", kDefaultFadeMS / 10) ;
	else
		fadeList[i] = '', fadeList[i + 1] = 0 ;
}

function cancelFade(id)
{
	for (var i = 0 ; i < fadeList.length ; i += 2)
		if (fadeList[i] == id)
		{
			clearTimeout(fadeList[i + 1]) ;
			fadeList[i] = '', fadeList[i + 1] = 0 ;
		}
}

function fadeInContent()
{
	var	elt = document.getElementById('content') ;

	if (!isOldMSIE)
		setEltOpacity(elt, 0) ;
	elt.style.visibility = 'visible' ;
	if (!isOldMSIE)
		fadeIn('content', 400) ;
}

function handleThumbClick(thumbType, evt, viewerURL)
{
	var imgIndex ;
	var	theIframe = document.getElementById("viewer_iframe") ;
	var	x, y ;
	var	s ;
	var	elt = getEvtSrc(evt) ;

	if (thumbType == 'photo')
	{
		x = Math.floor((evt.offsetX ? evt.offsetX : evt.layerX) / kThumbWidth) ;
		y = Math.floor((evt.offsetY ? evt.offsetY : evt.layerY) / kThumbWidth) ;
		imgIndex = y * kThumbsPerRow + x ;
		
		s = getEltPos(elt).split(',') ;		// get top left screen coords of selected thumb
		x = x * kThumbWidth + parseInt(s[0])
		y = y * kThumbWidth + parseInt(s[1]) ;

		if (isPhone() || isOldMSIE)
			self.location = viewerURL + '?startImg=' + imgIndex ;
		else
		{
			theIframe.style.left = (x - self.pageXOffset) + "px" ;
			theIframe.style.top = (y - self.pageYOffset) + "px" ;
			theIframe.style.width = theIframe.style.height = kThumbWidth + "px" ;
			animateThumbGrow(0, viewerURL + '?startImg=' + imgIndex) ;
		}
	}
	else if (thumbType == 'video')
	{
		if (isOldMSIE || isPhone())
		{
			self.location = 'http://www.youtube.com/v/' + viewerURL + '?rel=0&fs=1&autoplay=1&autohide=1' ;
			return ;
		}

		s = getEltPos(elt).split(',') ;		// get top left screen coords of selected thumb
		x = parseInt(s[0]), y = parseInt(s[1]) ;

		theIframe.style.left = (x - self.pageXOffset) + "px" ;
		theIframe.style.top = (y - self.pageYOffset) + "px" ;
		theIframe.style.width = myObjWidth(elt) + "px" ;
		theIframe.style.height = myObjHeight(elt) + "px" ;

		animateThumbGrow(0, '/video.html?' + viewerURL) ;
	}
	else
		self.location = viewerURL ;
}

function animateThumbGrow(step, url)
{
	var	theIframe = document.getElementById("viewer_iframe") ;

	if (step == 0)
		theIframe.style.display = 'block' ;
	else
	{
		theIframe.style.left = (parseInt(theIframe.style.left) - 200) + 'px' ;
		theIframe.style.top = (parseInt(theIframe.style.top) - 200) + 'px' ;
		theIframe.style.width = (parseInt(theIframe.style.width) + 400) + 'px' ;
		theIframe.style.height = (parseInt(theIframe.style.height) + 400) + 'px' ;
	}
	if (step == 5)
	{
		doOnPageReturn("document.getElementById('viewer_iframe').style.display = 'none'") ;
		self.location = url ;
	}
	else
		setTimeout("animateThumbGrow(" + (step + 1) + ", '" + url + "')", 50) ;
}


var	expandTimeout = 0 ;

function initExpandState()
{
	var	s ;
	var	i, theDiv ;

	if ((x = myGetCookie('expandState:' + curPageName)) == '')
		return ;

	for (i = 0, s = x.split(',') ; i < s.length - 1 ; ++i)			// show all open "expand" divs
	{
		theDiv = document.getElementById(s[i]) ;
		setEltOpacity(theDiv.firstChild, 1) ;
		theDiv.style.height = (myObjHeight(theDiv.firstChild) + 50) + 'px' ;
		document.getElementById(s[i] + '_img').src = '/i/icons/expand-opened.png' ;
	}
}

function handleExpand(divID, clickDiv)
{
	var	expandImg = clickDiv.getElementsByTagName('IMG')[0] ;
	var	doExpand = (expandImg.src.search(/opened/) >= 0) ? 0 : 1 ;
	var	elts, s ;

	if (expandTimeout)		// ignore this click if another section is expanding
		return ;

	expandImg.src = doExpand ? '/i/icons/expand-opened.png' : '/i/icons/expand-closed.png' ;
	
	animateExpand(divID, doExpand, doExpand ? 0 : 1.0) ;

	if (!isOldMSIE)
		for (var i = 0, s = '', elts = document.getElementsByClassName('expand_div') ; i < elts.length ; ++i)
			if ((elts[i].id == divID) ? doExpand : (elts[i].style.height != '1px'))
				s += elts[i].id + ',' ;
	mySetCookie('expandState:' + curPageName, s) ;
}

var	kAnimateTime = 0.2 ;				// seconds
var kAnimateSteps = 20 ;

function animateExpand(divID, doExpand, ratio)
{
	var	theDiv = document.getElementById(divID) ;
	var	innerHeight = myObjHeight(theDiv.firstChild) + 50 ;

	ratio += (doExpand ? 1 : -1) / kAnimateSteps ;
	if (ratio < 0.05)
		ratio = 0 ;
	if (ratio > 0.95)
		ratio = 1 ;
	theDiv.style.height = Math.max(1, Math.round(ratio * innerHeight)) + 'px' ;
	setEltOpacity(theDiv.firstChild, ratio) ;

	if ((ratio == 0) || (ratio > 0.95))
		expandTimeout = 0 ;
	else
		expandTimeout = setTimeout('animateExpand("' + divID + '", ' + doExpand + ', ' + ratio + ' )', kAnimateTime * 1000 / kAnimateSteps) ;
}

function dispEmail(user, domain, isLink)
{
	var s = "" ;

	if (isLink)
		s += "<a href='mailto:" + user + "@" + domain + "'>" ;
	s += user + "@" + domain ;
	if (isLink)
		s += "</a>" ;

	document.write(s) ;
	document.close() ;
}		

function checkEmail(email)			// returns false on bad email
{
	var s = email.split('@') ;
	return (((s.length < 2) || (s[1].split('.').length < 2)) ? false : true) ;
}


/////////////////////////////////////
//                                 //
//      xmlhttp req stuff          //
//                                 //
/////////////////////////////////////

var gXMLReq ;
var gXMLReqFailed = false ;

function loadXMLDoc(url, method, data, handler)
{
	gXMLReq = false;

	if (window.XMLHttpRequest)			// branch for native XMLHttpRequest object
	{
		try
		{
			gXMLReq = new XMLHttpRequest() ;
		}
		catch(e)
		{
			gXMLReq = false ;
		}
	}
	else if (window.ActiveXObject)		// branch for IE/Windows ActiveX version
	{
		try
		{
			gXMLReq = new ActiveXObject("Msxml2.XMLHTTP") ;
		}
		catch(e)
		{
			try
			{
				gXMLReq = new ActiveXObject("Microsoft.XMLHTTP") ;
			}
			catch(e)
			{
				gXMLReq = false ;
			}
		}
	}

	if (gXMLReq)
	{
		if (handler)
			gXMLReq.onreadystatechange = handler ;
		gXMLReq.open(method, url, true) ;
		if (method.toUpperCase() == 'POST')
			gXMLReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded') ;
		gXMLReq.send(data) ;
	}
}

function aSampleXMLReqHandler()
{
	if (gXMLReq.readyState == 4)			// only if gXMLReq shows "loaded"
	{
		if (gXMLReq.status == 200)
			alert(gXMLReq.responseText) ;
		else
		{
			gXMLReqFailed = true ;				// xml req failed; try again as normal post
			// do something
		}
	}
}

function formToString(theForm)
{
	var s = '' ;
	var elt ;
	
	for (var i = 0 ; i < theForm.elements.length ; ++i)
	{
		elt = theForm.elements[i];
		if ((elt.type == 'text') || (elt.type == 'hidden') || (elt.type == 'select-one') || (elt.type == 'textarea'))
			s += ((i > 0) ? '&' : '') + elt.name + '=' + escape(elt.value) ;
	}
	return (s) ;
}

function doXMLReq(target, method, data, handler)
{
	gXMLReq = false ;
	if (method == "GET")
		target += '?' + data, data = '' ;
	if (!gXMLReqFailed)
		loadXMLDoc(target, method, data, handler) ;
	return (gXMLReq) ;
}



///////////////////////////
//						 //
// browser compatibility //
//						 //
///////////////////////////

var	checkedBrowser = 0 ;
var	isMSIE = 0 ;
var	isOpera = 0 ;
var	isFirefox = 0 ;
var	isSafari = 0 ;
var	isAndroid = 0 ;
var	msieCSS1 = 0 ;
var	msieVer = 0 ;
var	isOldMSIE = 0 ;
var	userAgent ;

function getEvtSrc(e)
{
	return (e.srcElement ? e.srcElement : e.target) ;
}

function myInnerWidth()
{
	return (isOldMSIE ? (msieCSS1 ? document.documentElement.offsetWidth : document.body.clientWidth) : self.innerWidth) ;
}

function myInnerHeight()
{
	return (isOldMSIE ? (msieCSS1 ? document.documentElement.offsetHeight : document.body.clientHeight) : self.innerHeight) ;
}

function myScreenLeft()
{
	return (isNaN(self.screenLeft) ? self.screenX : self.screenLeft) ;
}

function myScreenTop()
{
	return (isNaN(self.screenTop) ? self.screenY : self.screenTop) ;
}

function myObjWidth(obj)
{
	return (isOldMSIE ? obj.offsetWidth : obj.clientWidth) ;
}

function myObjHeight(obj)
{
	return (isOldMSIE ? obj.offsetHeight : obj.clientHeight) ;
}

function isFullScreen()
{
	if (isOldMSIE)
		return (myScreenTop() <= 0) ;
	return ((screen.availWidth - myInnerWidth() < 10) && (screen.availHeight - myInnerHeight() < 10))
}

function myAddEventListener(elt, eventName, eventHandler)
{
	if (elt.addEventListener)
		elt.addEventListener(eventName, eventHandler, false) ;
	else if (elt.attachEvent)
		elt.attachEvent('on' + eventName, eventHandler) ;
}

function fixMSIEOpacity(tagType)
{
	var	elts ;

	if (!isOldMSIE)
		return ;
	
	for (var i = 0, elts = document.getElementsByTagName(tagType) ; i < elts.length ; ++i)
		if (elts[i].style && elts[i].style.opacity)
			setEltOpacity(elts[i], parseFloat(elts[i].style.opacity)) ;
}

function setEltOpacity(elt, opacity)
{
	elt.style.opacity = opacity ;
	if (isOldMSIE)
	{
		elt.style.filter = 'alpha(opacity=' + Math.round(opacity * 100) + ')' ;
		elt.style.zoom = '1' ;
	}
}

function checkBrowser()
{
    var s = navigator.userAgent.toLowerCase() + navigator.appVersion.toLowerCase() ;
	var browserList = new Array("chrome", "opera", "firefox", "safari", "msie") ;
	var	platformList = new Array("android", "mac", "linux", "windows") ;
	var	i ;

	if (checkedBrowser)
		return ;
	checkedBrowser = 1 ;

	for (i = 0, userAgent = 'unknown' ; i < browserList.length ; ++i)
		if (s.indexOf(browserList[i]) >= 0)
		{
			userAgent = browserList[i] ;
			break ;
		}
    isMSIE = (userAgent == 'msie') ;
	isOpera = (userAgent == 'opera') ;
	isFirefox = (userAgent == 'firefox') ;
	isSafari = (userAgent == 'safari') ;

	if (isMSIE)
	{
		msieCSS1 = (document.compatMode == 'CSS1Compat')
		msieVer = parseFloat(navigator.appVersion.replace(/^.*MSIE /, '')) ;
		isOldMSIE = (msieVer < 9) ;
	}

	for (i = 0 ; i < platformList.length ; ++i)
		if (s.indexOf(platformList[i]) >= 0)
		{
			userAgent += '/' + platformList[i] ;
			break ;
		}
	if (i == platformList.length)
		userAgent += '/unknown' ;

	isAndroid = (userAgent.search(/android/) > -1) ;

	return (true) ;
}

function isPhone()			// this is a bit of hack, it's true, but hopefully it will catch most cases
{
	return (window.devicePixelRatio && (window.devicePixelRatio != 1)) ;
}


/////////////////////
//				   //
//  misc routines  //
//				   //
/////////////////////

function getEltPos(tgtElt, withinDiv)
{
	var	x = 0 ;
	var y = 0 ;

	while (true)
	{
		y += tgtElt.offsetTop, x += tgtElt.offsetLeft ;
		tgtElt = tgtElt.offsetParent ;
		if ((!tgtElt) || (withinDiv && (tgtElt.tagName == 'DIV')))
			break ;
	}
	return (x + ',' + y) ;
}

function pointInElt(x, y, elt)
{
	var	s = getEltPos(elt).split(',') ;
	var	left = parseInt(s[0]) ;
	var	top = parseInt(s[1]) ;

	if ((x < left) || (x > left + myObjWidth(elt)))
		return (0) ;
	if ((y < top) || (y > top + myObjHeight(elt)))
		return (0) ;
	return (1) ;
}

function delObjChildren(obj)
{
	while (obj.childNodes.length > 0)
		obj.removeChild(obj.childNodes[0]) ;
}

function setInnerText(obj, str)
{
	var theText = document.createTextNode(str) ;

	delObjChildren(obj) ;
	obj.appendChild(theText) ;
}

function mySetCookie(name, value, maxAge) 
{
    var expDate = new Date() ;

	if (!maxAge)
		maxAge = 1000 * 60 * 60 * 24 * 365 * 10 ;      // default: expires 10 years from now

	expDate.setTime(expDate.getTime() + maxAge) ;
	document.cookie = name + "=" + escape(value) + "; expires=" + expDate.toGMTString() + "; path=/" ;
}

function myGetCookie(name)
{
	var	s = document.cookie.split(';') ;

	for (var i = 0 ; i < s.length ; ++i)
	{
		var x = s[i].split('=') ;

		if (x[0].replace(/^ */, '') == name)
			return (unescape(x[1])) ;
	}
	return ('') ;
}

function loadScript(url)
{
	var head = document.getElementsByTagName('head')[0] ;
	var	script = document.createElement('script') ;

	script.type = 'text/javascript' ;
	script.src = url ;
	head.appendChild(script) ;
}


// doOnPageReturn: a way to detect when we've returned to this page via the back button & then execute an action
// note that action should not have any double quotes in it

var	pageReturnPrevTime ;

function doOnPageReturn(action, step)		
{
	var	now = new Date() ;

	if (!step)
		step = 0 ;
	else if ((step >= 10) || (now.getTime() - pageReturnPrevTime > 1000))
	{
		eval(action) ;
		return ;
	}
	pageReturnPrevTime = now.getTime() ;
	setTimeout('doOnPageReturn("' + action + '", ' + (step + 1) + ')', 100) ;
}



