function openHelp (section) {
 window.open ( 'help_index.php?section=' + section, 'cal_help','dependent,menubar,scrollbars,height=500,width=600,innerHeight=520,outerWidth=620' );
}

function openAbout () {
  var mX = (screen.width / 2) -123, mY = 200;
  var MyPosition = 'left=' + mX + ',top=' + mY + ',screenx=' + mX + ',screeny=' + mY;
  window.open ( 'about.php', 'cal_about','dependent,toolbar=0, height=300,width=245,innerHeight=310,outerWidth=255,location=0,' + MyPosition );
}

function gotoAnalyticsSite()
{
  var currentUri = window.location.href;
  window.location.href = "http://localhost:10666/?sessionid=" + readCookie('PHPSESSID') +
    "&calendaruri=" + currentUri;
}

function addLoadHandler(handler)
{
    if (window.addEventListener)
    {
        window.addEventListener("load",handler,false);
    }
    else if (window.attachEvent)
    {
        window.attachEvent("onload",handler);
    }
    else if (window.onload)
    {
        var oldHandler = window.onload;
        window.onload = function piggyback()
        {
            oldHandler();
            handler();
        };
    }
    else
    {
        window.onload = handler;
    }
}

/* document.getElementsBySelector(selector)
   - returns an array of element objects from the current document
     matching the CSS selector. Selectors can contain element names,
     class names and ids and can be nested. For example:

       elements = document.getElementsBySelect('div#main p a.external')

     Will return an array of all 'a' elements with 'external' in their
     class attribute that are contained inside 'p' elements that are
     contained inside the 'div' element which has id="main"

   New in version 0.4: Support for CSS2 and CSS3 attribute selectors:
   See http://www.w3.org/TR/css3-selectors/#attribute-selectors

   Version 0.4 - Simon Willison, March 25th 2003
   -- Works in Phoenix 0.5, Mozilla 1.3, Opera 7, Internet Explorer 6, Internet Explorer 5 on Windows
   -- Opera 7 fails
*/

function getAllChildren(e) {
  // Returns all children of element. Workaround required for IE5/Windows. Ugh.
  return e.all ? e.all : e.getElementsByTagName('*');
}

document.getElementsBySelector = function(selector) {
  // Attempt to fail gracefully in lesser browsers
  if (!document.getElementsByTagName) {
    return new Array();
  }
  // Split selector in to tokens
  var tokens = selector.split(' ');
  var currentContext = new Array(document);
  for (var i = 0; i < tokens.length; i++) {
    token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');
    if (token.indexOf('#') > -1) {
      // Token is an ID selector
      var bits = token.split('#');
      var tagName = bits[0];
      var id = bits[1];
      var element = document.getElementById(id);
      if (tagName && element.nodeName.toLowerCase() != tagName) {
        // tag with that ID not found, return false
        return new Array();
      }
      // Set currentContext to contain just this element
      currentContext = new Array(element);
      continue; // Skip to next token
    }
    if (token.indexOf('.') > -1) {
      // Token contains a class selector
      var bits = token.split('.');
      var tagName = bits[0];
      var className = bits[1];
      if (!tagName) {
        tagName = '*';
      }
      // Get elements matching tag, filter them for class selector
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      continue; // Skip to next token
    }
    // Code to deal with attribute selectors
    if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
      var tagName = RegExp.$1;
      var attrName = RegExp.$2;
      var attrOperator = RegExp.$3;
      var attrValue = RegExp.$4;
      if (!tagName) {
        tagName = '*';
      }
      // Grab all of the tagName elements within current context
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      var checkFunction; // This function will be used to filter the elements
      switch (attrOperator) {
        case '=': // Equality
          checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
          break;
        case '~': // Match one of space separated words
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
          break;
        case '|': // Match start with value followed by optional hyphen
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
          break;
        case '^': // Match starts with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
          break;
        case '$': // Match ends with value - fails with "Warning" in Opera 7
          checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
          break;
        case '*': // Match ends with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
          break;
        default :
          // Just test for existence of attribute
          checkFunction = function(e) { return e.getAttribute(attrName); };
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (checkFunction(found[k])) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
      continue; // Skip to next token
    }
    // If we get here, token is JUST an element (not a class or ID selector)
    tagName = token;
    var found = new Array;
    var foundCount = 0;
    for (var h = 0; h < currentContext.length; h++) {
      var elements = currentContext[h].getElementsByTagName(tagName);
      for (var j = 0; j < elements.length; j++) {
        found[foundCount++] = elements[j];
      }
    }
    currentContext = found;
  }
  return currentContext;
}

/* That revolting regular expression explained
/^(\w+)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/
  \---/  \---/\-------------/    \-------/
    |      |         |               |
    |      |         |           The value
    |      |    ~,|,^,$,* or =
    |   Attribute
   Tag
*/

function sortTasks( order, cat_id, ele ) {
  ele.style.cursor = 'wait';
  document.body.style.cursor = 'wait';
  var cat = '';
  if ( cat_id > -99 )
    cat = '&cat_id=' + cat_id;
  var url = 'ajax.php';
  var params = 'page=minitask&name=' + order + cat;
  var ajax = new Ajax.Request(url,
    {method: 'post',
    parameters: params,
    onComplete: showResponse});
}

function showResponse(originalRequest) {
  miniTask = document.getElementById('minitask');
  if (originalRequest.responseText) {
    text = originalRequest.responseText;
    miniTask.innerHTML = text;
  }
  document.body.style.cursor = 'default';
}

function altrows() {  
   if(!document.getElementsByTagName) return false;  
   var rows = $$('div tbody tr');      
   for (var i=0; i<rows .length; i++) { 
     if ( ! rows[i].hasClassName('ignore') ) {
       rows[i].onmouseover = function() { $(this).addClassName('alt');}  
       rows[i].onmouseout = function() { $(this).removeClassName('alt');} 
    }
   }  
} 

function altps() {  
   if(!document.getElementsByTagName) return false;  
   var rows = $$('div p');      
   for (var i=0; i<rows .length; i++) { 
     if ( ! rows[i].hasClassName('ignore') ) {
       rows[i].onmouseover = function() { $(this).addClassName('alt');}  
       rows[i].onmouseout = function() { $(this).removeClassName('alt');} 
    }
   }  
} 
function showFrame(foo,f,section) {
  document.getElementById(foo).style.display = "block";
  if (f) { setCookie(foo, "o", section); }
}

function hideFrame(foo,f,section) {
  if (document.getElementById(foo)) {
    document.getElementById(foo).style.display = "none";
    if (f) { deleteCookie(foo, section); }
  }
}

function hideFilter()
{
  var div = document.getElementById('filter_selection');
  if (!div)
    return;
  
  div.style.display = "none";
  
  hideAllSelects();
}

function hideAllSelects()
{
  var form = document.getElementById('filter');
  if (!form)
    return;
  
  var selects = form.getElementsByTagName('select');
  for (var i=0, l=selects.length; i<l; i++)
  {
    selects[i].style.display = "none";
  }
  
  document.getElementById('filter_structure').style.display = "none";
  
  return form;
}

function linktoFilter()
{
  var div = document.getElementById('filter_link');
  var filters = 
  {
    "categories":true, 
    "users":true, 
    "groups":true, 
    "countries":true, 
    "regions":true, 
    "religions":true
  };
  var link = window.location.href;
  var query = link.split("?");
  link = query[0] + "?";
  if (query.length > 1)
  {
    var getVars = query[1].split("&");
    query = '';
    var re = /^[a-z]+/;
    for (var i=0, l=getVars.length; i<l; i++)
    {
      var v = getVars[i];
      var m = v.match(re);
      if (filters[m])
        query += v + "&";
    }
    
    link += query;
  }
  
  var filterNameInput = document.getElementById('filter_link_name');
  if (!filterNameInput.onblur)
    filterNameInput.onblur = linktoFilter;
  if (filterNameInput.value != '')
    link += "filtername=" + encodeURIComponent(filterNameInput.value);
  
  document.getElementById('filter_link_textbox').value = link;
  document.getElementById('filter_link_anchor').href = link;
}

function resetFilter()
{
  var form = document.getElementById('filter');
  if (!form)
    return;
  
  var selects = form.getElementsByTagName('select');
  for (var i=0, l=selects.length; i<l; i++)
  {
    selects[i].selectedIndex = 0;
  }
  
  form.submit();
}

function showFilter(args, which)
{
  var form = hideAllSelects();
  if (!form)
    return;
  
  var list = '';
  switch (which)
  {
    case 'regions':
      list = "List of Countries by Region";
      break;
    case 'groups':
      list = "List of Organizations By Group";
      break;
    default:
      list = '';
      break;
  }
  if (list.length)
  {
    var structure = document.getElementById('filter_structure');
    structure.innerHTML = '<a href="structures.php?show=' + which 
        + '" style="color:#FFFFFF;text-decoration:underline;">' 
        + list + '</a>';
    structure.style.display = "block";
  }
  
  which += "[]";
  var select = form[which];
  if (!select)
    return;
  var div = document.getElementById('filter_selection');
  if (!div)
    return;
  
  var posx = 0;
	var posy = 0;
  var e;
	if (args && args.length > 0) 
    e = args[0];
  else
    e = window.event;
	if (e.pageX || e.pageY)
  {
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY)
  {
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
  
  if (!posx || !posy)
    return;
  
  select.style.display = "block";
  div.style.top = posy + "px";
  div.style.left = posx + "px";
  div.style.display = "block";
}

// cookie functions taken (and slightly modified) from Scott Andrew (http://www.quirksmode.org/js/cookies.html)
function createCookie(name,value,days) 
{
  var expires = "";
	if (days) 
  {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		expires = "; expires="+date.toGMTString();
	}
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) 
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function setShowInstructions(value)
{
  if (value)
    value = "";
  else
    value = "true";
  createCookie("noinstructions", value, 365);
}

function showInstructions()
{ 
  var src = "";
  // Specialized Instruction pages for Organizations who want it.
  switch (location.hash)
  {
    case "#ispac":
      src = "http://phastrax.phxwg.com/Renderer.aspx?Page=389";
      break;
    case "#unicri":
      src = "http://phastrax.phxwg.com/Renderer.aspx?Page=388";
      break;
    case "#ISPAC":
      src = "http://phastrax.phxwg.com/Renderer.aspx?Page=389";
      break;
    case "#UNICRI":
      src = "http://phastrax.phxwg.com/Renderer.aspx?Page=388";
      break;
    case "#ICPC":
      src = "http://phastrax.phxwg.com/Renderer.aspx?Page=431";
      break;
    default:
      src = "http://phastrax.phxwg.com/Renderer.aspx?Page=387";
	  break;
  }
  
  var obj = getSbObj(src);
  obj.title = "Calendar Tutorial";
  Shadowbox.open(obj);
}

function showFilterHelp()
{
  var obj = getSbObj("http://phastrax.phxwg.com/Renderer.aspx?Page=429");
  obj.title = "Filter Tutorial";
  Shadowbox.open(obj);
}

function showGlossary()
{
  var obj = getSbObj("glossary.php");
  obj.title = "Glossary";
  Shadowbox.open(obj);
}

function getSbObj(src)
{
  var obj = 
  {
    type: "html",
    content: '<div style="padding:5px;overflow:hidden;height:500px;width:696px;"><iframe id="contentiframe" height="490" width="686" frameborder="0" src="' 
      + src + '" style="border:0;"></iframe></div>',
    height: 500,
    width: 700
  };
  return obj;
}

function getPage()
{
  var value = location.pathname;
  value = value.substr(value.lastIndexOf('/') + 1);
  return value;
}

// instructions pop-up
addLoadHandler(function()
{
  var checked = ((new Boolean(readCookie("noinstructions"))).valueOf() ? "" : ' checked="checked"');
  var setFloat = function(element, value)
  {
    if (typeof (element.style.cssFloat) != "undefined")
      element.style.cssFloat = value;
    else if (typeof (element.style.styleFloat) != "undefined")
      element.style.styleFloat = value;
  };
  
  Shadowbox.init(
  {
    skipSetup: true, 
    onFinish: function(a) 
    {
      var SL = Shadowbox.lib;
      var instrDiv;
      
      switch (a.title)
      {
        case "Calendar Tutorial":
          var closeDiv = SL.get('shadowbox_toolbar_inner');
          instrDiv = document.createElement('div');
          instrDiv.innerHTML = '<input type="checkbox"' + checked + ' id="showInstructions" onclick="setShowInstructions(this.checked);" /> <label for="showInstructions" style="font-size:16px;line-height:10px;vertical-align:45%;">Show these instructions automatically</label>';
          SL.setStyle(instrDiv, {"fontSize":"14px","lineHeight":"10px","float":"left"});
          closeDiv.insertBefore(instrDiv, closeDiv.firstChild);
          break;
        case "Glossary":
		case "Filter Tutorial":
          break;
      }
      
      instrDiv = SL.get('subscribe_div');
      if (!instrDiv)
      {
        var headDiv = SL.get('shadowbox_title');
        SL.setStyle(headDiv.firstChild, {"float":"left","width":"150px"});
        instrDiv = document.createElement('div');
        instrDiv.id = "subscribe_div";
        instrDiv.innerHTML = '&nbsp;';
        SL.setStyle(instrDiv, {"padding":"5px 8px 4px 0","fontSize":"16px","lineHeight":"16px","float":"right"});
        headDiv.appendChild(instrDiv);
      }
      onResize();
      SL.setStyle(SL.get('shadowbox_content'), "overflow", "hidden");
      
      // handle window resize events
      var timer = null;
      var resize = function()
      {
        clearTimeout(timer);
        timer = null;
        onResize();
      };
      SL.addEvent(window, 'resize', function()
      {
        if(timer)
        {
          clearTimeout(timer);
          timer = null;
        }
        if(!timer) timer = setTimeout(resize, 75);
      });
    }
  });
  var noInstructions = (new Boolean(readCookie("noinstructions"))).valueOf();
  // Breakout for Organizations that don't wish for the Instruction Pop-Up to Display.
  switch (location.hash)
  {
    case "#INPROL":
      return;
    default:
	  break;
  }
  if (noInstructions)
    return;
  
  var tutorialPagesObj = 
  {
    'month.php' : true
  };
  
  if (tutorialPagesObj[getPage()])
    showInstructions();
});

function setupLinktoFilter()
{
  var linkToFilterMenu = document.getElementById('cmSubMenuID4');
  if (linkToFilterMenu)
  {
    try
    {
      linkToFilterMenu = linkToFilterMenu.firstChild.firstChild.firstChild;
      var omoValue = linkToFilterMenu.getAttribute("onmouseover");
      // an IE hack because they can't follow standards...
      if (omoValue && omoValue instanceof Function)
      {
        linkToFilterMenu.detachEvent("onmouseover", omoValue);
        omoValue = omoValue.toString();
        omoValue = omoValue.substring(omoValue.indexOf('{')+1, omoValue.lastIndexOf('}'));
        omoValue = eval('omoValue = function(){linktoFilter();'+omoValue+'};');
      }
      else
      {
        omoValue = "linktoFilter();" + omoValue;
      }
      linkToFilterMenu.setAttribute("onmouseover", omoValue);
    }
    catch (e)
    {
    }
  }
}

function onResize()
{
  var SL = Shadowbox.lib;
  
  var content = SL.get('shadowbox_body_inner');
  var re = /[0-9]*/;
  var h = re.exec(SL.getStyle(content, "height"))[0] || "500";
  h -= 0;
  content = document.getElementById('shadowbox');
  var w = re.exec(SL.getStyle(content, "width"))[0] || "700";
  w -= 0;
  if (h != 500 || w != 700)
  {
    content = SL.get("contentiframe");
    content.height = (h-10);
    content.width = (w-14);
  }
}