var tolliumWF_RequestObject, tolliumWF_SubmittedFrame, tolliumWF_RequestActive, tolliumWF_AddToSubmit=[];
var tolliumWF_WindowMap=[], tolliumWF_FrameMap=[], tolliumWF_PressedButton;
var tolliumWF_ModalOverlay;

function tolliumWF_GetMyForm(node)
{
  while(node&&node.nodeName.toUpperCase()!='FORM')
    node=node.parentNode;
  return node;
}
function tolliumWF_Submit(node, evt, addname, addvalue) //easy way for custom buttons to add their submittable values
{
  if(!evt) evt=window.event;
  if(addname)
    tolliumWF_AddToSubmit = [{ name: addname, value: addvalue }];

  tolliumWF_PressedButton = node;
  var form = tolliumWF_GetMyForm(node);
  if(tolliumWF_FormSubmit(form, evt))
    return true;

  tolliumWF_AddToSubmit = [];
  toddDontPropagateEvent(evt);
  return false;
}

function tolliumWF_FallbackSubmit(node)
{
  //Add any values to the form anyway
  for(var j=0;j<tolliumWF_AddToSubmit.length;++j)
  {
    var inp = document.createElement('input');
    inp.type='hidden';
    inp.name=tolliumWF_AddToSubmit[j].name;
    inp.value=tolliumWF_AddToSubmit[j].balue;
    node.appendChild(inp);
  }
  node.submit();
}

function tolliumWF_FormSubmit(node)
{
  if(tolliumWF_RequestActive)
    return false;

  var forminfo = tolliumWF_GetWebFormsData(node);
  if(forminfo.dialogmode != 'popup') //not really popup mode, probably a forcedonclick or similar handler invoking us
  {
    tolliumWF_FallbackSubmit(node);
    return false;
  }

  var postdata='';
  for(var j=0;j<tolliumWF_AddToSubmit.length;++j)
    postdata += (postdata==''?'':'&') + encodeURIComponent(tolliumWF_AddToSubmit[j].name) + '=' + encodeURIComponent(tolliumWF_AddToSubmit[j].value);

  var elements=node.getElementsByTagName('*');
  for(var i = 0;i<elements.length;++i)
  {
    var el=elements[i], name='', value;
    switch(el.nodeName.toUpperCase())
    {
      case 'A':
        if(el!=tolliumWF_PressedButton)
          break;

        var toks = el.href.split('&').join('?').split('?'); //convert & to ?, and resplit
        for(var j=0;j<toks.length;++j)
          if(toks[j].substr(0,16) == '$tollium_action=' || toks[j].substr(0,14) == '$tollium_data=')
            postdata += (postdata==''?'':'&') + toks[j];
        break;

      case 'BUTTON':
        if(el!=tolliumWF_PressedButton)
          break;

        name=el.name;
        value=el.value;
        break;

      case 'INPUT':
        switch(el.type.toUpperCase())
        {
          case 'FILE':
            tolliumWF_FallbackSubmit(node);
            return true; //cannot intercept forms containing file elements

          case 'SUBMIT':
          case 'IMAGE':
            if(el!=tolliumWF_PressedButton)
             break;

            name=el.name;
            value=el.value;
            break;

          case 'RADIO':
          case 'CHECKBOX':
            if(el.checked)
            {
              name=el.name;
              value=el.value;
            }
            break;

          case 'HIDDEN':
            if(el.name=='webforms_js_info')
              break;

            name=el.name;
            value=el.value;
            break;

          default: /*fall-through*/
            name=el.name;
            value=el.value;
            break;
        }
        break;
      case 'TEXTAREA':
        name=el.name;
        value=el.value;
        break;
      case 'SELECT':
        if(el.name)
          for(var j=0;j<el.options.length;++j)
            if(el.options[j].selected && el.options[j].value)
              postdata += (postdata==''?'':'&') + encodeURIComponent(el.name) + '=' + encodeURIComponent(el.options[j].value);
        break;
    }
    if(name)
      postdata += (postdata==''?'':'&') + encodeURIComponent(name) + '=' + (value ? encodeURIComponent(value) : '');
  }

  if(!tolliumWF_RequestObject)
  {
    tolliumWF_RequestObject = toddCreateRequestObject();
    if(!tolliumWF_RequestObject)
      return true; //no xmlhttp is no form interception
  }

  //Make sure this frame is registered
  var framename = tolliumWF_GetWebFormsData(node).wstack.slice(-1);
  if(!tolliumWF_FrameMap[framename])
    tolliumWF_FrameMap[framename] = node;

  tolliumWF_RequestActive = true;
  tolliumWF_SubmittedFrame = node;
  tolliumWF_RequestObject.open('POST', node.action, true);
  tolliumWF_RequestObject.onreadystatechange = tolliumWF_FormResponseHandler;
  tolliumWF_RequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  tolliumWF_RequestObject.setRequestHeader('X-Tollium-Webforms-Req', '1');
  tolliumWF_RequestObject.send(postdata);

  return false;
}

function tolliumWF_GetWebFormsData(webform)
{
  return eval('('+webform.getElementsByTagName("INPUT")[0].value+')');
}

function tolliumWF_FormResponseHandler()
{
  if(tolliumWF_RequestObject.readyState != 4)
    return;

  var connection_status = 0;
  try
  {
    connection_status = tolliumWF_RequestObject.status;
  }
  catch(e)
  {
  }

  var isinternalerror = connection_status == 500;
  if(!isinternalerror && tolliumWF_RequestObject.getResponseHeader('Content-Type').substr(0,16)=='application/json')
  {
    var data=eval('(' + tolliumWF_RequestObject.responseText + ')');
    if(data.length > 0 && data[0].instr == 'gotourl')
    {
      location.href = data[0].url;
      return;
    }

    //confused..
    location.href = tolliumWF_SubmittedFrame.action;
    return;
  }

  if(!isinternalerror && tolliumWF_RequestObject.getResponseHeader('X-Tollium-Webforms') != '1')
  {
    location.href = tolliumWF_SubmittedFrame.action;
    return;
  }
  tolliumWF_RequestActive = false;

  if(!tolliumWF_ModalOverlay)
  {
    tolliumWF_ModalOverlay = document.createElement('div');
    tolliumWF_ModalOverlay.className = 'tollium-modaloverlay';
    document.body.appendChild(tolliumWF_ModalOverlay);
  }

  var tempy = document.createElement('div');
  tempy.className = 'tollium-offscreen';
  tempy.style.display = 'inline-block';
  tempy.innerHTML = tolliumWF_RequestObject.responseText;
  document.body.appendChild(tempy);

  var lastforminfo = tolliumWF_GetWebFormsData(tolliumWF_SubmittedFrame);
  var newforminfo;
  if(isinternalerror)
  {
    newforminfo = {wstack: lastforminfo.wstack.splice(0,lastforminfo.wstack.length) }; //deep copy of lastforminfo.wstack
    newforminfo.wstack.push('errorwindow'); //add an extra window to hold the error
  }
  else
  {
    newforminfo = tolliumWF_GetWebFormsData(tempy.firstChild);
  }
  if(newforminfo.gotoanchor && newforminfo.gotoanchor[0]=='#')
  {
    location.href = newforminfo.gotoanchor;
  }

  if (lastforminfo.wstack.length < newforminfo.wstack.length) //open a window
  {
    tolliumWF_FrameMap[ newforminfo.wstack.slice(-1) ] = tempy.firstChild;

    var win = tolliumWF_OpenWindow(tempy.firstChild, newforminfo.wstack.length, isinternalerror);
    tolliumWF_WindowMap[ newforminfo.wstack.slice(-1) ] = win;

    tolliumWF_ModalOverlay.style.zIndex = 1000 + (2*newforminfo.wstack.length);
    tolliumWF_ModalOverlay.style.display = 'block';
  }
  else
  {
    while (lastforminfo.wstack.length > newforminfo.wstack.length) //close a window ( ADDME Support multiple window
    {
      var topopname = lastforminfo.wstack.slice(-1);
      if(tolliumWF_WindowMap[topopname])
        tolliumWF_CloseWindow(tolliumWF_WindowMap[topopname]);

      delete tolliumWF_WindowMap[topopname];
      delete tolliumWF_FrameMap[topopname];
      lastforminfo.wstack.pop();
    }
    var toreplacename = lastforminfo.wstack.slice(-1);
    if(!tolliumWF_FrameMap[toreplacename]) //the page isn't there - we popped too many frames. fallback to non-js handlers
    {
      location.href = tolliumWF_SubmittedFrame.action;
      return;
    }

    if(newforminfo.wstack.length >= 2) //no more windows
    {
      tolliumWF_ModalOverlay.style.zIndex = 1000 + (2*newforminfo.wstack.length);
    }
    else
    {
      tolliumWF_ModalOverlay.style.display = 'none';
    }

    var oldnode = tolliumWF_FrameMap[toreplacename];
    tolliumWF_FrameMap[toreplacename] = tempy.firstChild;
    oldnode.parentNode.replaceChild(tempy.firstChild, oldnode);
  }
  document.body.removeChild(tempy);
}

function tolliumWF_OpenWindow(newform, depth, isinternalerror)
{
  var viewport;
  if (document.body.clientHeight && document.documentElement.clientHeight)
  {
    if (document.body.clientHeight > document.documentElement.clientHeight)
      viewport = { width: document.body.clientWidth, height: document.body.clientHeight };
    else
      viewport = { width: document.documentElement.clientWidth, height: document.documentElement.clientHeight };
  }
  else
    viewport = { width: document.body.clientWidth, height: document.body.clientHeight };

  var data = { formwidth: newform.offsetWidth
             , formheight: newform.offsetHeight
             , screenwidth: viewport.width
             , screenheight: viewport.height
             , viewportoffsetx: document.body.scrollLeft+document.documentElement.scrollLeft
             , viewportoffsety: document.body.scrollTop+document.documentElement.scrollTop
             , bgwidth: document.body.scrollWidth
             , bgheight: document.body.scrollHeight
             , form: newform
             , zindex: 1001 + (2*depth)
             , isinternalerror: isinternalerror
             };

  if(data.screenheight < window.innerHeight)
    data.screenheight = window.innerHeight;
  if(data.screenwidth < window.innerWidth)
    data.screenwidth = window.innerWidth;

  //If body and/or html are set to height:100%, clientHeight seems to be useless under at least FF
  if(document.documentElement.scrollHeight > data.bgheight)
    data.bgheight = document.documentElement.scrollHeight;
  if(document.documentElement.scrollWidth > data.bgwidth)
    data.bgwidth = document.documentElement.scrollWidth;

  if(data.bgheight < viewport.height)
    data.bgheight = viewport.height;

  if(data.bgwidth < viewport.width)
    data.bgwidth = viewport.width;

  data.formsuggestwidth = data.formwidth > (data.screenwidth*0.8) ? parseInt(data.screenwidth*0.8) : data.formwidth;
  data.formsuggestheight = data.formheight > (data.screenheight*0.8) ? parseInt(data.screenheight*0.8) : data.formheight;
  //alert(data.formsuggestheight + ' ' + data.formheight + ' ' + data.screenheight + ' ' + viewport.height + ' ' + toddGetViewPortDimensions().height);

  //Calculate the centerpositioning x and y
  data.centerposx = parseInt(data.viewportoffsetx + (data.screenwidth - data.formsuggestwidth) / 2);
  data.centerposy = parseInt(data.viewportoffsety + (data.screenheight - data.formsuggestheight) / 2);

  tolliumWF_ModalOverlay.style.height = data.bgheight + 'px';
  tolliumWF_ModalOverlay.style.width = data.bgwidth + 'px';

  if(typeof tolliumWFHook_OpenWindow != 'undefined')
  {
    var newwin = tolliumWFHook_OpenWindow(data);
    if(newwin)
      return newwin;
  }
  return tolliumWFDefault_OpenWindow(data);
}
function tolliumWF_CloseWindow(win)
{
  if(typeof tolliumWFHook_CloseWindow != 'undefined')
  {
    if(tolliumWFHook_CloseWindow(win))
      return;
  }
  tolliumWFDefault_CloseWindow(win);
}


// Default form opener. To overwrite it, supply a function named tolliumWFHook_OpenWindow
function tolliumWFDefault_OpenWindow(data)
{
  //add space for 1px borders on all edges
  data.formwidth += 2;
  data.formheight += 2;

  var newwin = document.createElement('div');
  newwin.className = 'tollium-popupdialog';
  newwin.style.top = (data.centerposy - 1) + 'px';
  newwin.style.left = (data.centerposx - 1) + 'px';

  newwin.style.width = (data.formsuggestwidth + 2) + 'px';
  newwin.style.height = (data.formsuggestheight  +2) + 'px';
  newwin.style.zIndex = data.zindex;
  newwin.appendChild(data.form);
  document.body.appendChild(newwin);
  return newwin;
}

// Default form closer.. To overwrite it, supply a function named tolliumWFHook_CloseWindow
function tolliumWFDefault_CloseWindow(win)
{
  document.body.removeChild(win);
  return true;
}

if(typeof toddMarkScriptComplete != 'undefined')
  toddMarkScriptComplete("webforms.js");
