// $Id: drupal.js,v 1.17 2005/12/31 10:48:56 dries Exp $

/**
 * Only enable Javascript functionality if all required features are supported.
 */
function isJsEnabled() {
  if (typeof document.jsEnabled == 'undefined') {
    // Note: ! casts to boolean implicitly.
    document.jsEnabled = !(
     !document.getElementsByTagName ||
     !document.createElement        ||
     !document.createTextNode       ||
     !document.documentElement      ||
     !document.getElementById);
  }
  return document.jsEnabled;
}

// Global Killswitch on the <html> element
if (isJsEnabled()) {
  document.documentElement.className = 'js';
}

/**
 * Make IE's XMLHTTP object accessible through XMLHttpRequest()
 */
if (typeof XMLHttpRequest == 'undefined') {
  XMLHttpRequest = function () {
    var msxmls = ['MSXML3', 'MSXML2', 'Microsoft']
    for (var i=0; i < msxmls.length; i++) {
      try {
        return new ActiveXObject(msxmls[i]+'.XMLHTTP')
      }
      catch (e) { }
    }
    throw new Error("No XML component installed!");
  }
}

/**
 * Creates an HTTP GET request and sends the response to the callback function
 */
function HTTPGet(uri, callbackFunction, callbackParameter) {
  var xmlHttp = new XMLHttpRequest();
  var bAsync = true;
  if (!callbackFunction) {
    bAsync = false;
  }
  xmlHttp.open('GET', uri, bAsync);
  xmlHttp.send(null);

  if (bAsync) {
    if (callbackFunction) {
      xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
          callbackFunction(xmlHttp.responseText, xmlHttp, callbackParameter);
        }
      }
    }
    return true;
  }
  else {
    return xmlHttp.responseText;
  }
}

/**
 * Creates an HTTP POST request and sends the response to the callback function
 *
 * Note: passing null or undefined for 'object' makes the request fail in Opera 8.
 *       Pass an empty string instead.
 */
function HTTPPost(uri, callbackFunction, callbackParameter, object) {
  var xmlHttp = new XMLHttpRequest();
  var bAsync = true;
  if (!callbackFunction) {
    bAsync = false;
  }
  xmlHttp.open('POST', uri, bAsync);

  var toSend = '';
  if (typeof object == 'object') {
    xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    for (var i in object)
      toSend += (toSend ? '&' : '') + i + '=' + escape(object[i]);
  }
  else {
    toSend = object;
  }
  xmlHttp.send(toSend);

  if (bAsync) {
    if (callbackFunction) {
      xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
          callbackFunction(xmlHttp.responseText, xmlHttp, callbackParameter);
        }
      }
    }
    return true;
  }
  else {
    return xmlHttp.responseText;
  }
}

/**
 * Redirects a button's form submission to a hidden iframe and displays the result
 * in a given wrapper. The iframe should contain a call to
 * window.parent.iframeHandler() after submission.
 */
function redirectFormButton(uri, button, handler) {
  // Insert the iframe
  // Note: some browsers require the literal name/id attributes on the tag,
  // some want them set through JS. We do both.
  var div = document.createElement('div');
  div.innerHTML = '<iframe name="redirect-target" id="redirect-target" class="redirect"></iframe>';
  var iframe = div.firstChild;
  with (iframe) {
    name = 'redirect-target';
    setAttribute('name', 'redirect-target');
    id = 'redirect-target';
  }
  with (iframe.style) {
    position = 'absolute';
    height = '1px';
    width = '1px';
    visibility = 'hidden';
  }
  document.body.appendChild(iframe);

  // Trap the button
  button.onmouseover = button.onfocus = function() {
    button.onclick = function() {
      // Prepare variables for use in anonymous function.
      var button = this;
      var action = button.form.action;
      var target = button.form.target;

      // Redirect form submission
      this.form.action = uri;
      this.form.target = 'redirect-target';

      handler.onsubmit();

      // Set iframe handler for later
      window.iframeHandler = function (data) {
        // Restore form submission
        button.form.action = action;
        button.form.target = target;
        handler.oncomplete(data);
      }

      return true;
    }
  }
  button.onmouseout = button.onblur = function() {
    button.onclick = null;
  }
}

/**
 * Adds a function to the window onload event
 */
function addLoadEvent(func) {
  var oldOnload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  }
  else {
    window.onload = function() {
      oldOnload();
      func();
    }
  }
}

/**
 * Adds a function to a given form's submit event
 */
function addSubmitEvent(form, func) {
  var oldSubmit = form.onsubmit;
  if (typeof oldSubmit != 'function') {
    form.onsubmit = func;
  }
  else {
    form.onsubmit = function() {
      return oldSubmit() && func();
    }
  }
}

/**
 * Retrieves the absolute position of an element on the screen
 */
function absolutePosition(el) {
  var sLeft = 0, sTop = 0;
  var isDiv = /^div$/i.test(el.tagName);
  if (isDiv && el.scrollLeft) {
    sLeft = el.scrollLeft;
  }
  if (isDiv && el.scrollTop) {
    sTop = el.scrollTop;
  }
  var r = { x: el.offsetLeft - sLeft, y: el.offsetTop - sTop };
  if (el.offsetParent) {
    var tmp = absolutePosition(el.offsetParent);
    r.x += tmp.x;
    r.y += tmp.y;
  }
  return r;
};

function dimensions(el) {
  return { width: el.offsetWidth, height: el.offsetHeight };
}

/**
 * Returns true if an element has a specified class name
 */
function hasClass(node, className) {
  if (node.className == className) {
    return true;
  }
  var reg = new RegExp('(^| )'+ className +'($| )')
  if (reg.test(node.className)) {
    return true;
  }
  return false;
}

/**
 * Adds a class name to an element
 */
function addClass(node, className) {
  if (hasClass(node, className)) {
    return false;
  }
  node.className += ' '+ className;
  return true;
}

/**
 * Removes a class name from an element
 */
function removeClass(node, className) {
  if (!hasClass(node, className)) {
    return false;
  }
  node.className = eregReplace('(^| )'+ className +'($| )', '', node.className);
  return true;
}

/**
 * Toggles a class name on or off for an element
 */
function toggleClass(node, className) {
  if (!removeClass(node, className) && !addClass(node, className)) {
    return false;
  }
  return true;
}

/**
 * Emulate PHP's ereg_replace function in javascript
 */
function eregReplace(search, replace, subject) {
  return subject.replace(new RegExp(search,'g'), replace);
}

/**
 * Removes an element from the page
 */
function removeNode(node) {
  if (typeof node == 'string') {
    node = $(node);
  }
  if (node && node.parentNode) {
    return node.parentNode.removeChild(node);
  }
  else {
    return false;
  }
}

/**
 * Prevents an event from propagating.
 */
function stopEvent(event) {
  if (event.preventDefault) {
    event.preventDefault();
    event.stopPropagation();
  }
  else {
    event.returnValue = false;
    event.cancelBubble = true;
  }
}

/**
 * Wrapper around document.getElementById().
 */
function $(id) {
  return document.getElementById(id);
}


function MM_swapImgRestore() { //v3.0
	var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
	var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
	var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
	if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
	var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
	d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
	if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
	for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
	if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
	var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
	if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
<!--
function activateConfirm() {
    if (confirm("Warning! Once activated, this survey can no longer be edited.  Any further changes must be done on a copy.")) {
        return true;
    }
    return false;
}

function cancelConfirm() {
    if (confirm("Warning! This survey has not been saved.  Canceling now will remove any changes.")) {
        return true;
    }
    return false;
}

function exportSubmit(type, f) {
    f.where.value=type;
    f.submit();
}

function clearTextInputs() {
    var i = 1;
    while (document.forms[1].elements["choice_content_" + i]) {
        document.forms[1].elements["choice_content_" + i].value = "";
        i++;
    }
}

function addAnswerLine() {
    var el = document.getElementById('answerlines');
    var numchoice = document.getElementById('num_choices').value;
    numchoice++;
    var tablerow = el.insertRow(numchoice+1);
    var tablecell = tablerow.insertCell(-1);
    tablecell.innerHTML = numchoice+".";
    tablecell.className = "numbered";
    tablecell = tablerow.insertCell(-1);
    var text = "<input type=\"hidden\" name=\"choice_id_"+numchoice+"\" value=\"\" />\n";
    text = text+"<input type=\"text\" size=\"60\" name=\"choice_content_"+numchoice+"\" value=\"\" />\n";
    tablecell.innerHTML = text;
    tablecell.className = "left";
    document.getElementById('num_choices').value = numchoice;
}


function validate() {
    return true;
}

function other_check(name)
{
    other = name.split("_");
    var f = document.survey_response;
    for (var i=0; i<=f.elements.length; i++) {
        if (f.elements[i].value == "other_"+other[1]) {
            f.elements[i].checked=true;
            break;
        }
    }
}

function merge(box) {
    if(box.options.length >= 2){
        ml = new Array();
        for(var i=0; i<box.options.length; i++) {
            ml[i] = box.options[i].value;
            sidsArray=ml;
        }
        sids = sidsArray.join("+");
        document.getElementById('sids').value = sids; 
        form = document.getElementById('merge');
        form.submit();
    } else {
        document.getElementById('error').innerHTML = "<h2>You must select at least two surveys before you can merge</h2>";
    }
}

function move(fbox,tbox) {
    for(var i=0; i<fbox.options.length; i++) {
        if(fbox.options[i].selected && fbox.options[i].value != "") {
            var no = new Option();
            no.value = fbox.options[i].value;
            no.text = fbox.options[i].text;
            tbox.options[tbox.options.length] = no;
            fbox.options[i].value = "";
            fbox.options[i].text = "";
        }
    }
    BumpUp(fbox);
}

function BumpUp(box)  {
    for(var i=0; i<box.options.length; i++) {
        if(box.options[i].value == "")  {
            for(var j=i; j<box.options.length-1; j++)  {
                box.options[j].value = box.options[j+1].value;
                box.options[j].text = box.options[j+1].text;
            }
            var ln = i;
            break;
        }
    }
    if(ln < box.options.length)  {
        box.options.length -= 1;
        BumpUp(box);
    }
}

function set_today(type)
{
	var d=new Date();
	var month = (d.getMonth()+1);
	var date = d.getDate();
	var year = d.getYear();
	if(month < 10)
		var month = "0" + month;
	if(date < 10)
		var date = "0" + date;
	if(year < 1900)
		var year = year + 1900;

	document.getElementsByName(type+"Month")[0].value = month;
	document.getElementsByName(type+"Day")[0].value = date;
	document.getElementsByName(type+"Year")[0].value = year;
}

function set_plus_minus_days(type, math)
{
	month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
	month = document.getElementsByName(type+"Month")[0].value * 1;
	date = document.getElementsByName(type+"Day")[0].value * 1;
	year = document.getElementsByName(type+"Year")[0].value * 1;

	if(month == 'Month' || date == 'Day' || year == 'Year')
	{
		d=new Date();
		month = (d.getMonth()+1);
		date = d.getDate();
		year = d.getYear();
	}

	if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0))
	{
		month_days[1] = 29;
	}

	if(math == '-')
	{
		if(date > 1)
		{
			date = date - 1;
		}
		else if(date == 1 && month > 1)
		{
			month = month - 1;
			date = month_days[month-1];
		}
		else if(date == 1 && month == 1)
		{
			year = year - 1;
			month = 12;
			date = 31;
		}		
	}
	else
	{
		if(date < month_days[month-1])
		{
			date = (date * 1 + 1);
		}
		else if(date == month_days[month-1] && month < 12)
		{
			month = (month * 1 + 1);
			date = 1;
		}
		else if(date == month_days[month-1] && month == 12)
		{
			year = (year * 1 + 1);
			month = 1;
			date = 1;
		}		
	}

	if(month < 10)
		var month = "0" + month;
	if(date < 10)
		var date = "0" + date;
	if(year < 1900)
		var year = year + 1900;

	document.getElementsByName(type+"Month")[0].value = month;
	document.getElementsByName(type+"Day")[0].value = date;
	document.getElementsByName(type+"Year")[0].value = year;
}

function checkReset(tid)
{
	if(!confirm('Are you sure you want to reset this check request?'))
	{
		alert('No changes were made.');
	}
	else
	{
		document.prometheus.checkreset.value = tid;
		document.prometheus.action = '/admin/prometheus/lookup/history/reset/'+tid;
		document.prometheus.submit();
	}
}

/***
** function used don the IQD page
**
****/

function toggleDiv(id,flagit) {
    if (flagit=="1"){
       if (document.layers) document.layers[''+id+''].display = "block"
       else if (document.all) document.all[''+id+''].style.display = "block"
	   else if (document.getElementById) document.getElementById(''+id+'').style.display = "block"
    }
    else
    if (flagit=="0"){
       if (document.layers) document.layers[''+id+''].display = "none"
       else if (document.all) document.all[''+id+''].style.display = "none"
       else if (document.getElementById) document.getElementById(''+id+'').style.display = "none"
    }
}
-->
