// Implement forEach for browsers which do not support it.
if (!Array.prototype.forEach)
{
  Array.prototype.forEach = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
        fun.call(thisp, this[i], i, this);
    }
  };
}
var ajaxResponse = {
  parseResponse: function(responseText, callbackFunction) {
    var doc;
    if (document.implementation.createDocument){
      // Mozilla, create a new DOMParser
      var parser = new DOMParser();
      doc        = parser.parseFromString(responseText, "text/xml");
    } else if (window.ActiveXObject){
      // Internet Explorer, create a new XML document using ActiveX and use loadXML as a DOM parser.
      doc = new ActiveXObject("Microsoft.XMLDOM")
      doc.async="false";
      doc.loadXML(responseText);
    }
    var rootNode = doc.documentElement;
    var ajaxCode, ajaxMesg, ajaxHtml;
    for(var i=0;i<rootNode.childNodes.length;i++) {
      switch(rootNode.childNodes[i].tagName) {
        case 'code':    if (rootNode.childNodes[i].firstChild) { ajaxCode = rootNode.childNodes[i].firstChild.nodeValue; } break;
        case 'message': if (rootNode.childNodes[i].firstChild) { ajaxMesg = rootNode.childNodes[i].firstChild.nodeValue; } break;
        case 'html':    if (rootNode.childNodes[i].firstChild) { ajaxHtml = rootNode.childNodes[i].firstChild.nodeValue; } break;
      }
    }
    callbackFunction(ajaxCode, ajaxMesg, ajaxHtml);
  }
}

function divMessage(item, text, after) {
  if(Element.visible(item))
  {
    // Shrink it first, then grow it
    new Effect.Shrink(item, {
        duration:    0.25,
        afterFinish: function(){
                       Element.hide(item);
                       Element.update(item, text);
                       new Effect.Grow(item, {
                               duration:    0.25,
                               direction:   'bottom-right',
                               afterFinish: after
                           });
                     }
        });
  } else {
    // Just grow it
    Element.update(item, text);
    new Effect.Grow(item, {
          duration:    0.25,
          direction:   'bottom-right',
          afterFinish: after });
  }
}
function updateInnerHTML(id, new_html)
{
  new Effect.BlindUp(id, {
      duration:    0.25,
      afterFinish: function(){
                     Element.hide(id);
                     Element.update(id, new_html);
                     new Effect.BlindDown(id, {
                         duration:    0.25,
                         afterFinish: function(){}});
                   }
      });
}
function loginFormSubmit() {
  var url = secureSiteRoot + 'login';
  $('loginSubmit').disabled = true;
  var username = $F('loginUsername');
  var password = $F('loginPassword');
  if(!(/[a-zA-Z0-9_-]{2,}/.test(username))) {
    divMessage('login_status', "Invalid Username", function(){$('loginSubmit').disabled = false;});
  }
  else if(!(/.{4,}/.test(password))) {
    divMessage('login_status', "Invalid Password", function(){$('loginSubmit').disabled = false;});
  }
  else {
    var pars = 'username=' + $F('loginUsername') + '&password=' + $F('loginPassword');
    divMessage('login_status', "Please Wait...", function(){
      var myAjax = new Ajax.Request(
                   url,
                   {
                     method: 'post',
                     parameters: pars,
                     onSuccess: function(originalRequest){
                       /* show the login response */
                       ajaxResponse.parseResponse(originalRequest.responseText, function(ajaxCode, ajaxMesg, ajaxHtml){
                         switch(ajaxCode) {
                         case '200': // login was successful
                           divMessage('login_status', ajaxMesg, function(){
                             $('loginSubmit').disabled = false;
                             updateInnerHTML('login_area', ajaxHtml);
                           });
                           break;
                         default: // login error
                           divMessage('login_status', ajaxMesg, function(){
                             $('loginSubmit').disabled = false;
                           });
                           break;
                         }
                       });
                     },
                     onFailure: function(){reportFailure('login_status', 'loginSubmit');}
                   });
    });
  }
}
function loginFormLogout() {
  var url = secureSiteRoot + 'login?opt=logout';
  $('loginSubmit').disabled = true;
  divMessage('login_status', "Please Wait...", function(){});
  var myAjax = new Ajax.Request(
               url,
               {
                 method: 'get',
                 onSuccess: function(originalRequest){
                   ajaxResponse.parseResponse(originalRequest.responseText, function(ajaxCode, ajaxMesg, ajaxHtml){
                     switch(ajaxCode) {
                     case '200': // login was successful
                       divMessage('login_status', ajaxMesg, function(){
                         $('loginSubmit').disabled = false;
                         // Update with the new html
                         updateInnerHTML('login_area', ajaxHtml);
                       });
                       break;
                     default: // login error
                       divMessage('login_status', ajaxMesg, function(){
                         $('loginSubmit').disabled = false;
                       });
                       break;
                     }
                 })},
                 onFailure: function(){reportFailure('login_status', 'loginSubmit');}
               });
}
function reportFailure(status_item, disabled_button) {
  divMessage(status_item, '<img src="' + siteRoot + 'img/incorrect.gif" style="float:left;display:block;height:.75em;padding:.375em .25em 0 0;vertical-align:middle;" alt="animation" />Error processing your request.', function(){$(disabled_button).disabled = false;});
}

function getElementPosition(element) {
  /* a portable way to find the X,Y position of an element */
	var curleft = curtop = 0;
	if (element.offsetParent) {
		curleft = element.offsetLeft;
		curtop = element.offsetTop;
		
		if(element.offsetParent.style.position == 'relative')
		  return [curleft,curtop];
		
		while (element = element.offsetParent) {
			curleft += element.offsetLeft
			curtop += element.offsetTop
		}
	}
	return [curleft,curtop];
}

var menuTimer;
var timeoutElement;
function menuMouseOver(element) {
  var listItem = element.parentNode;
  for(var i=0; i<element.parentNode.childNodes.length; i++) {
    if(element.parentNode.childNodes.item(i).className == 'menu') {
      var menu = element.parentNode.childNodes.item(i);
      if(timeoutElement != menu) {
        // IE hax workaround
        menu.style.left = '148px';
        menu.style.top = element.offsetTop + 'px';
        menu.style.display = 'block';
        menu.style.zIndex = '5';
        
        menu.onmouseover = function(){ clearMenuTimer(); }
        menu.onmouseout = function(){ setMenuTimer(menu); }
      }
      else {
        clearMenuTimer();
      }
    }
  }
}
function menuMouseOut(element) {
  var listItem = element.parentNode;
  for(var i=0; i<element.parentNode.childNodes.length; i++) {
    if(element.parentNode.childNodes.item(i).className == 'menu') {
      var menu = element.parentNode.childNodes.item(i);
      setMenuTimer(menu);
    }
  }
}
function hideMenu() {
  if(timeoutElement) {
    timeoutElement.style.display = 'none';
    timeoutElement = undefined;
    menuTimer = undefined;
  }
}
function setMenuTimer(menu) {
  if(menuTimer) {
    hideMenu();
    clearMenuTimer();
  }
  timeoutElement = menu;
  menuTimer = setTimeout('hideMenu()', 25);
}
function clearMenuTimer() {
  clearTimeout(menuTimer);
  timeoutElement = undefined;
  menuTimer = undefined;
}
function showAnswer(fid) {
  // First, hide all answers.
  $$('div.faqs div').forEach(function(e, i, a){e.style.display = 'none';});
  $$('div.faqs p a').forEach(function(e, i, a){e.style.display = 'inline';});

  new Effect.Appear('faq_answer_'+fid, { duration: 0.5 });
  $('show_answer_'+fid).style.display = 'none';
}
function hideAnswer(fid) {
  $('show_answer_'+fid).style.display = 'inline';
  $('faq_answer_'+fid).style.display = 'none';
}

// Fix IE's broken <abbr> via JS.
function styleAbbr() {
  var oldBodyText, newBodyText, reg
  if (isIE) {
    oldBodyText = document.body.innerHTML;
    reg = /<ABBR([^>]*)>([^<]*)<\/ABBR>/g;
    newBodyText = oldBodyText.replace(reg, '<ABBR $1><SPAN class=\"abbr\" $1>$2</SPAN></ABBR>');
    document.body.innerHTML = newBodyText;
  }
}

window.onload = function(){
  styleAbbr()
};

isIE = (document.all) ? true:false;

