// $Id: core.js,v 1.9 2008/10/07 02:22:43 nick Exp $ //

// common js code for ALL 83D apps.  should not contain app-specific code!

var gLastTimerId=0;
function delayCode(str, msecs)
{
	clearTimeout(gLastTimerId);
	gLastTimerId = setTimeout(str, msecs);
}

function getEl(id)
{
//	if (!document.getElementById(id))
//		alert(id);
	return document.getElementById(id);
}

function addLoadEvent(func)
{
	var oldonload = window.onload;
	if (typeof window.onload != 'function')
		window.onload = func;
	else
	{
		window.onload = function()
		{
			if (oldonload)
				oldonload();
			func();
		}
	}
}

function getRadioValue(elRadio)
{
	// example using element names:  document.forms['tagNameForm'].elements['tagName']
	if(!elRadio.length && elRadio.checked)
		return elRadio.value;

	for(var i = 0; i < elRadio.length; i++)
	{
		if(elRadio[i].checked)
			return elRadio[i].value;
	}
	return '';
}
function setRadioValue(elRadio, newValue)
{
	if(!elRadio)
		return;
	if(!elRadio.length)
		elRadio.checked = (elRadio.value == newValue.toString());
	else
	{
		for(var i = 0; i < elRadio.length; i++)
		{
			elRadio[i].checked = false;
			if(elRadio[i].value == newValue.toString())
				elRadio[i].checked = true;
		}
	}
}

function getElementPos(element)
{
  var coords = {x: 0, y: 0};
  do {
    coords.x += element.offsetLeft;
    coords.y += element.offsetTop;
  }
  while ((element = element.offsetParent));
  return coords;
}

function setElementPos(element, coords)
{
	element.style.left = coords.x+"px";
	element.style.top = coords.y+"px";
}

function getWinWidth()
{
    if (window.innerWidth)
    {
    	w = window.innerWidth;
    	if (document.body.scrollHeight && document.body.scrollHeight >= getWinHeight())
    		w-=16;
    	return w;
    }
    else if (document.documentElement && document.documentElement.clientWidth)
  		return document.documentElement.clientWidth;
    else if (document.body && document.body.clientWidth)
  		return document.body.clientWidth;
  	else if (document.body && document.body.parentNode && document.body.parentNode.clientWidth)
 		return document.body.parentNode.clientWidth;
}

function getWinHeight()
{
    if (window.innerHeight) return window.innerHeight;
  	else if (document.documentElement && document.documentElement.clientHeight)
  		return document.documentElement.clientHeight;
  	else if (document.body && document.body.clientHeight)
  		return document.body.clientHeight;
  	else if (document.body && document.body.parentNode && document.body.parentNode.clientHeight)
  		return document.body.parentNode.clientHeight;
}

function getWinLeft() {return typeof window.pageXOffset != 'undefined' ? window.pageXOffset:document.documentElement && document.documentElement.scrollLeft? document.documentElement.scrollLeft:document.body.scrollLeft? document.body.scrollLeft:0;}
function getWinTop() {return typeof window.pageYOffset != 'undefined' ? window.pageYOffset:document.documentElement && document.documentElement.scrollTop? document.documentElement.scrollTop: document.body.scrollTop?document.body.scrollTop:0;}
function getWinRight() {return getWinLeft()+getWinWidth();}
function getWinBottom() {return getWinTop()+getWinHeight();}


var gbNextRequestToDoc = 0;
var gaLastRequest = new Array;
function makeXmlHttpRequest(action, args, reaction)
{
    if (window.XMLHttpRequest)
    	req = new XMLHttpRequest();
    else if (window.ActiveXObject)
        req = new ActiveXObject("Microsoft.XMLHTTP");
    if (!req)
    {
    	alert("Your browser is outdated (missing XMLHttpRequest). This feature will not work on your broswer.");
    	return;
    }

    gaLastRequest['action'] = action;
	gaLastRequest['reaction'] = reaction;
	if (!window.gAltUserInfo)
		gAltUserInfo='';
	url = '/ajax.php?action='+action+'&'+args+'&'+gAltUserInfo;
	if (gbNextRequestToDoc)
	{
		document.location.href=url;
		return;
	}
    req.onreadystatechange = processReqChange;
    req.open("GET", url, true);
    req.send(null);
}
function makeXmlHttpPOSTRequest(action, data, reaction)
{
    if (window.XMLHttpRequest)
    	req = new XMLHttpRequest();
    else if (window.ActiveXObject)
        req = new ActiveXObject("Microsoft.XMLHTTP");
    if (!req)
    {
    	alert("Your browser is outdated (missing XMLHttpRequest). This feature will not work on your broswer.");
    	return;
    }

    data += '&'+gAltUserInfo;

	if (gbNextRequestToDoc)
	{
		document.location.href='/ajax.php?'+data;
		return;
	}

    gaLastRequest['action'] = action;
	gaLastRequest['reaction'] = reaction;
    req.onreadystatechange = processReqChange;
    req.open("POST", '/ajax.php', true);
    req.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=utf-8');
    req.send(data);
}

function NewWindow(url,name,w,h,scroll,additionalSettings)
{
  var left = (screen.width-w)/2;
  var top = (screen.height-h)/2;
  var settings  ='height='+h+',';
      settings +='width='+w+',';
      settings +='top='+top+',';
      settings +='left='+left+',';
      settings +='resizable,scrollbars,';
  win = window.open(url,name,settings+additionalSettings);
  win.focus();
}

function showWindowShade(id, displayMode) // block or none
{
	el = getEl(id);

	if (!el || el.style.display == displayMode)
		return;

	if (displayMode == 'block')
	{
		var biggestHeight = document.body.scrollHeight;
		if (getWinHeight() > biggestHeight)
			biggestHeight = getWinHeight();

		el.style.width=document.body.scrollWidth+'px';
		el.style.height=biggestHeight+'px';
	}

	el.style.display = displayMode;
}

function displayCenteredDiv(id,offsetTop)
{
	el = getEl(id);
	el.style.display = 'inline';

	winTop = getWinTop();
	if (offsetTop > 20)
		el.style.top = winTop + offsetTop + 'px';
	else
		el.style.top = winTop + 20 + 'px';
	el.style.left= (getWinWidth()/2 - el.offsetWidth/2) +'px';
	el.style.visibility = 'visible';
}

function toggleVisibility(id)
{
	el = getEl(id);
	if (!el)
		return;
	if (el.style.visibility == 'visible')
		el.style.visibility = 'hidden';
	else
		el.style.visibility = 'visible';
}
function toggleVisibilityOn(id)
{
	el = getEl(id);
	if (!el)
		return;
	el.style.visibility = 'visible';
}
function toggleVisibilityOff(id)
{
	el = getEl(id);
	if (!el)
		return;
	el.style.visibility = 'hidden';
}

function toggleDisplay(id)
{
	el = getEl(id);
	if (!el)
		return;
	if (el.style.display == 'block')
		el.style.display = 'none';
	else
		el.style.display = 'block';
}
function toggleDisplayOn(id)
{
	el = getEl(id);
	if (!el)
		return;
	var val='block';
	if (el.tagName.toLowerCase()=='tr')
		val='table-row';
	el.style.display = val;
}
function toggleDisplayOff(id)
{
	el = getEl(id);
	if (!el)
		return;
	el.style.display = 'none';
}

function goToUrlOnConfirm(message, url)
{
	if (confirm(message))
		document.location.href=url;
}

function getExpDate(days, hours, minutes) {
    var expDate = new Date();
    if (typeof days == "number" && typeof hours == "number" && typeof hours == "number") {
        expDate.setDate(expDate.getDate() + parseInt(days));
        expDate.setHours(expDate.getHours() + parseInt(hours));
        expDate.setMinutes(expDate.getMinutes() + parseInt(minutes));
        return expDate.toGMTString();
    }
}

// utility function called by getCookie()
function getCookieVal(offset) {
    var endstr = document.cookie.indexOf (";", offset);
    if (endstr == -1) {
        endstr = document.cookie.length;
    }

    // javascript doesn't unescape '+' symbols (php encodes spaces as pluses), so do it manually.
    val = unescape(document.cookie.substring(offset, endstr));
    val = val.replace(/\+/g, ' ');
    return val;
}

// primary function to retrieve cookie by name
function getCookie(name) {
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg) {
            return getCookieVal(j);
        }
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break;
    }
    return '';
}

// store cookie value with optional details as needed
function setCookie(name, value, expires) {
    document.cookie = name + "=" + escape (value) +
        ((expires) ? "; expires=" + expires : "") +
        "; path=/; domain="+gsCookieDomain;
}

// remove the cookie by setting ancient expiration date
function deleteCookie(name) {
    if (getCookie(name)) {
        document.cookie = name + "=; path=/; domain="+gsCookieDomain+"; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

function getPrefInCookie(name, defaultValue)
{
	cookie = getCookie('prefs');
	if (cookie && cookie.length)
	{
//alert(name);
		start = cookie.indexOf('['+name+'|');
		if (start >= 0)
		{
			start += name.length+2;
			end = cookie.indexOf(']', start);
			return cookie.substring(start, end);
		}
	}

	return defaultValue;
}

function setPrefInCookie(name, value)
{
	oldValue = getPrefInCookie(name, '');
	// delete the old setting and add the new
	cookie = getCookie('prefs');
	strOld = '['+name+'|'+oldValue+']';
	start = cookie.indexOf(strOld);
	if (start >= 0)
	{
		part1 = cookie.substr(0, start);
		part2 = cookie.substr(start+strOld.length);
		cookie = part1 + part2;
	}
	// only add if there is a new value
	value = value.toString();
	if (value.length)
		cookie += "["+name+"|"+value+"]";

	var expireDate = new Date();
	expireDate.setTime(expireDate.getTime() + (1000*60*60*24*365*10));
	setCookie('prefs', cookie, expireDate.toGMTString())
}

function delNode(id)
{
	el = getEl(id);
	el.parentNode.removeChild(el);
}

function flashHighlight(id,finishCode,startColor,cycles)
{
	if (!getEl(id))
		return;

	var hstr = '#';
	var hdig = "0123456789abcdef";
	var cbeg = '#ffff66'; // starts with a yellow
	if (startColor)
		cbeg = startColor;
	var cCoorectEnd = getEl(id).style.backgroundColor; // this correctly gets the color. The fade code is buggy
	var cend = '#ffffff';
	var iter = 20; // cycles
	if (cycles)
		iter = cycles;
	var time = 80; // ms

	var rbeg = hdig.indexOf(cbeg.substr(1,1))*16 + hdig.indexOf(cbeg.substr(2,1));
	var gbeg = hdig.indexOf(cbeg.substr(3,1))*16 + hdig.indexOf(cbeg.substr(4,1));
	var bbeg = hdig.indexOf(cbeg.substr(5,1))*16 + hdig.indexOf(cbeg.substr(6,1));
	var rend = hdig.indexOf(cend.substr(1,1))*16 + hdig.indexOf(cend.substr(2,1));
	var gend = hdig.indexOf(cend.substr(3,1))*16 + hdig.indexOf(cend.substr(4,1));
	var bend = hdig.indexOf(cend.substr(5,1))*16 + hdig.indexOf(cend.substr(6,1));
	for ( i = 1, r = rbeg, g = gbeg, b = bbeg;
	i <= iter;
	r = Math.round(rbeg + i * ((rend - rbeg) / (iter-1))),
	g = Math.round(gbeg + i * ((gend - gbeg) / (iter-1))),
	b = Math.round(bbeg + i * ((bend - bbeg) / (iter-1))), i++ )
	{
		hstr = '#' + hdig.charAt(Math.floor(r/16)) + hdig.charAt(r%16) +
		hdig.charAt(Math.floor(g/16)) + hdig.charAt(g%16) +
		hdig.charAt(Math.floor(b/16)) + hdig.charAt(b%16);
		setTimeout('var el = getEl("' + id + '"); el.style.backgroundColor = "' + hstr + '";', i * time);
	}
   	setTimeout('var el = getEl("' + id + '"); el.style.backgroundColor = "' + cCoorectEnd + '";', (i+1) * time);
   	if (finishCode && finishCode.length)
	   	setTimeout(finishCode, (i+2) * time);
}

