var pops = [];
function uP(url, id) {
  if(url.substr(0,4) != "http") {
     url = pathToMain + url;
  }
  if(pops[id] && !pops[id].closed) {
    pops[id].location = url;
    pops[id].focus();
  } else {    
    pops[id] = window.open(url, id, 'toolbar=1,menubar=1,location=1,directories=1,width=760,height=400,scrollbars=1,resizable=1,status=1');  
  }
}

// addEvent() taken from
// http://www.dustindiaz.com/rock-solid-addevent/
function addEvent( obj, type, fn ) {
  //alert('adding ' + type + ' to ' + obj.id );
  if (obj.addEventListener) {
    obj.addEventListener( type, fn, false );
    EventCache.add(obj, type, fn);
  }
  else if (obj.attachEvent) {
    obj["e"+type+fn] = fn;
    obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
    obj.attachEvent( "on"+type, obj[type+fn] );
    EventCache.add(obj, type, fn);
  }
  else {
    obj["on"+type] = obj["e"+type+fn];
  }
}

function rmEvent( obj, type, fn ) {
  if(obj.removeEventListener) {
    obj.removeEventListener(type, fn, null);
  }
  if(obj.detachEvent) {
    obj.detachEvent(type, fn);
  }
}

var EventCache = function() {
  var listEvents = [];
  return {
    listEvents : listEvents, 
    add : function(node, sEventName, fHandler) {
            listEvents.push(arguments);
          },
    flush : function() {
              var i, item;
              for(i = listEvents.length - 1; i >= 0; i = i - 1) {
                item = listEvents[i];
                if(item[0].removeEventListener) {
                  item[0].removeEventListener(item[1], item[2], item[3]);
                };
                if(item[1].substring(0, 2) != "on") {
                  item[1] = "on" + item[1];
                };
                if(item[0].detachEvent) {
                  item[0].detachEvent(item[1], item[2]);
                };
                item[0][item[1]] = null;
              };
	    }
    };
  }();
addEvent(window,'unload',EventCache.flush);

// return the object that was just targeted by the event
function getTarget(evt)
{
  if (evt && evt.target)   //Moz
    return evt.target;
  else if(window.event)    //IE
    return window.event.srcElement;
  else                     //no event
    return;
}

// return the first parent object with the id prefix
function findObjParentById(el, id)
{
  if(el.id && el.id.indexOf(id) == 0) {
    return el;
  } else {
    return findObjParentById(el.parentNode, id);
  }
}

// get the kode of the key that was just pressed
// This is from http://www.howtocreate.co.uk/tutorials/index.php?tut=0&part=17  
function getKeyCode(e)
{
  if( !e ) {
    if( window.event ) {
      e = window.event;
    } else {
      return;
    }
  }
  if( typeof( e.which ) == 'number' ) {
     //NS 4, NS 6+, Mozilla 0.9+, Opera
     e = e.which;
  } else if( typeof( e.keyCode ) == 'number'  ) {
     //IE, NS 6+, Mozilla 0.9+
     e = e.keyCode;
  } else if( typeof( e.charCode ) == 'number'  ) {
     //also NS 6+, Mozilla 0.9+
     e = e.charCode;
  } else {
     return;
  }
  return e;
}

function processKey(e)
{
  e = getKeyCode(e);
  if(e == 13) {
    xajax_signup(i$('email').value);
  } else if(e == 27 && maxMode) {    // 27 => ESC 
    restoreMap();
  }
}
function i$(id)
{
    return document.getElementById(id);
}

/*
 * Gets an element's Y coordinate in the browser window
 */
function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

/*
 * Computes the visible window height
 */
function getWindowHeight()
{
	if(typeof(window.innerWidth) == 'number')
	{
		// Non-IE
		return window.innerHeight;
	}
	else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight))
	{
		// IE 6+ in 'standards compliant mode'
		return document.documentElement.clientHeight;
	}
	else if (document.body && (document.body.clientWidth || document.body.clientHeight))
	{
		// IE 4 compatible
		return document.body.clientHeight;
	}
}

/*
 * Gets an element's Y coordinate in the browser window
 */
function findPosX(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curtop += obj.x;
	return curtop;
}

/*
 * Computes the visible window height
 */
function getWindowWidth()
{
	if(typeof(window.innerWidth) == 'number')
	{
		// Non-IE
		return window.innerWidth;
	}
	else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight))
	{
		// IE 6+ in 'standards compliant mode'
		return document.documentElement.clientWidth;
	}
	else if (document.body && (document.body.clientWidth || document.body.clientHeight))
	{
		// IE 4 compatible
		return document.body.clientWidth;
	}
}

/*
 * Resizes map to fill window
 */
function resizeViewbox(isInit)
{
    // this is for home page login situation, for later
    //if(isInit) {
    //    xajax_check_login();
    //}
    var tg = i$("gis");
    var wheight	= getWindowHeight();
    var ycoord = findPosY(tg);
    var wwidth = getWindowWidth();
    var xcoord = findPosX(tg);

    if(maxMode) {
        tg.style.width = wwidth - 2 + 'px';
        tg.style.height = wheight - 2 + 'px';
        return true;
    }
    if(wheight - ycoord - 168 > 350)
        tg.style.height = (wheight - ycoord - 168) + 'px';
    if(wwidth  - xcoord - 50 > 500)
        tg.style.width  = (wwidth  - xcoord - 50) + 'px';
    map.checkResize();
    var v = getParam('v');
    if(isInit && v) {
        var el = v.split(',');
        map.setCenter(new GLatLng(Number(el[0]),Number(el[1])),Number(el[2]));
    } else if(isInit) {
        map.setCenter(new GLatLng(18, 15), 2);
    }
    //TODO: allow link with multiple diseases in disease= param
    var disease = getParam('disease');
    if(isInit && Number(disease)) {
        if(in_array(disease, diseaseIds)) {
            setAllCheck('feed', 1);
            mSl('diz', disease, '');
        } else {
            alert('Selected disease is not currently active on HealthMap. Showing all active diseases.');
            updMap();
        }
    }
    var fs = getParam('fs');
    if(isInit && Number(fs) == 1) {
        maxMap();
    }
    return true;
}

function getParam(name) {
    var qs = location.search.substring(1);
    //var qs = unescape(location.hash.substring(1));
    var pairs = qs.split('&');
    for(var i=0; i<pairs.length; i++) {
        elts = pairs[i].split("=");
        if(elts[0] == name) {
            return elts[1];
        }
    }
}

function toggleVisible(evt) {
    var tg = getTarget(evt);
    var target = i$(tg.id + 'i');
    target.style.display == '' ? target.style.display = 'none' : target.style.display = '';
    tg.innerHTML == '+' ? tg.innerHTML = '&ndash;' : tg.innerHTML = '+';
}
function plusMouseover(evt) {
    var tg = getTarget(evt);
    tg.style.color = '#4284B5';
    tg.style.backgroundColor = 'white';
}
function plusMouseout(evt) {
    var tg = getTarget(evt);
    tg.style.color = 'white';
    tg.style.backgroundColor = '';
}
function hilite(evt) {
    getTarget(evt).className = 'hilight';
}
function unHilite(evt) {
    getTarget(evt).className = '';
}

var maxMode = false;
var hopMode = false;
var oldL = [];
var timeHandle;
var j = 0;   // index into marker array for hopping function
var updTimer = 1;
//var showMC;
function maxMap()
{
    var tg = i$("gis");
    oldL['map'] = {};
    oldL['map'].position = tg.style.position;
    oldL['map'].width = tg.style.width;
    oldL['map'].height = tg.style.height;
    oldL['map'].top = tg.style.top;
    oldL['map'].left = tg.style.left;
    oldL['map'].zIndex = tg.style.zIndex;
    maxMode = true;
    resizeViewbox();
    tg.style.position = 'absolute';
    tg.style.top = '0px';
    tg.style.left = '0px';
    tg.style.zIndex = 10;
    //var ctlW = 200;
    for(var i = 1; i <= 4; i++) {
        i$("ctlbox" + i).style.display = 'none';
    }
    i$("maxctl").style.zIndex = 11;
   
    map.checkResize();
    document.onkeyup = processKey;
    addEvent(i$('main'), 'mouseover', function(){if(maxMode && !hopMode) { map.showControls(); } });
    addEvent(i$('main'), 'mouseout', function(){if(maxMode && !hopMode) map.hideControls();});
    addEvent(i$('page'), 'mouseover', function(){if(maxMode) i$('maxctl').style.display = '';});
    addEvent(i$('page'), 'mouseout', function(){if(maxMode) i$('maxctl').style.display = 'none';});
    hopMode = true;
    i$('togButton').innerHTML = stopMrkStr; // 'Stop marker rotation';
    mHopHandle = setInterval('markerHop()', 8000);
    updHandle = setInterval('updPoll()', 600000); // reload every hour
    //map.enableScrollWheelZoom();
    markerHop();
    xajax_logMaxMap('init');
}
function updPoll()
{
    // updPoll gets called every 10 minutes, so we increment the counter 6 times in order to refresh once per hour
    if(updTimer >= 6) {
        //GLog.write('refreshing page!');
        updTimer = 1;
        if(hopMode) {
            clearInterval(mHopHandle);
        }
        var now = new Date();   // if page has been open past midnight, need to start getting next day's alerts
        edate = now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate();
        updMap();
        if(hopMode) {
            mHopHandle = setInterval('markerHop()', 8000);
        }
    } else {
        //GLog.write('adding 1 to updTimer');
        updTimer++;
    }
}
function restoreMap()
{
    clearInterval(mHopHandle);
    clearInterval(updHandle);
    maxMode = false;
    var tg = i$("gis");
    tg.style.position = oldL['map'].position;
    tg.style.width = oldL['map'].width;
    tg.style.height = oldL['map'].height;
    tg.style.top = oldL['map'].top;
    tg.style.left = oldL['map'].left;
    tg.style.zIndex = oldL['map'].zIndex;
    map.checkResize();
    for(var i = 1; i <= 4; i++) {
        i$("ctlbox" + i).style.display = '';
    }
    i$("maxctl").style.display = 'none';
    hopMode = false;
    //map.disableScrollWheelZoom();
    xajax_logMaxMap('restore');
}
function markerHop() {
    GEvent.trigger(markers[j], "click");
    j = Math.floor(Math.random() * (markers.length - 1));
    //j++;
    //if(j == markers.length)
    //  j = 0;
}
function toggleHop() {
    if(hopMode) {
       //i$('togButton').innerHTML = 'Start marker rotation';
       i$('togButton').innerHTML = startMrkStr;
       clearInterval(mHopHandle);
       hopMode = false;
    } else {
       i$('togButton').innerHTML = stopMrkStr;
       hopMode = true;
       mHopHandle = setInterval('markerHop()', 8000);
       markerHop();
    }
}
// fixme: why not do this by elt id?
function clearBox(id, color) {
    i$(id).value = '';
    if(!color) {
        color = '#000';
    }
    i$(id).style.color = color;
//    if(cn == "lg_default") { 
//        i$('url').className = 'lg_textbox';
//        i$('url').value = '';
//    } else if(cn == "sm_default") {
//        i$('uname').className = 'sm_textbox';
//        i$('uname').value = '';
//    }
}
function doNothing() {
};
function hideById(id0, id1, id2, id3) {
  if(id0) {
    i$(id0).className = 'hidden';
  }
  if(id1) {
    i$(id1).className = 'hidden';
  }
  if(id2) {
    i$(id2).className = 'hidden';
  }
  if(id3) {
    i$(id3).className = 'hidden';
  }
  //var id = id0;
  //for(var i = 0; id != '' && i < 7; id = eval('id' + i)) {
  //  if(i$(id)) {
  //    i$(id).className = 'hidden';
  //  }
  //  i++;
  //}
}
// take some text, shorten and add +/- for expand collapse
function elideText(val, length) {
  if(val.length <= length) {
    return val;
  }
  var d = new Date;
  var uniq = 'e' + d.getTime();
  var show = val.substring(0, length);
  var hide = val.substring(length);
  var ret = show + '<span id="'+uniq+'" class="hidden">' + hide + '</span>' + '<a href="javascript:;" title="Expand" style="text-decoration:none" onclick="if(this.innerHTML == \'+\') { i$(\''+uniq+'\').className=\'\'; this.innerHTML=\'-\'; this.title=\'Collapse\'; } else { i$(\''+uniq+'\').className=\'hidden\'; this.innerHTML=\'+\'; this.title=\'Expand\'; }">+</a>';
  return ret;
}
function in_array(needle, haystack, argStrict) {
  // http://kevin.vanzonneveld.net
  var key = '', strict = !!argStrict;
  if(strict) {
    for (key in haystack) {
      if (haystack[key] === needle) {
        return true;
      }
    }
  } else {
    for (key in haystack) {
      if (haystack[key] == needle) {
        return true;
      }
    }
  }
  return false;
}
function chkGrp(tagid, idlist, elt, action) {
    var stat = true;
    if(action == 'uncheck') {
      stat = false;
    }
    for(var i = 0; i < idlist.length; i++) {
      i$(elt + tagid + idlist[i]).checked = stat;
    }
    i$('all_' + elt + 's').checked = false;
}
function maskmailto (container,addr,domain) { 
    var n = i$(container); 
    if(!n ) return; 
    n.innerHTML = "<a href='mailto:" + addr + "@" + domain + "'>" + addr + "@" + domain + "</a>" 
};
